From 5760816159441119bef50d73de4ae29d4e16f46b Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 15:54:18 +0900 Subject: [PATCH 1/5] feat(sv): support unpacked structures Unpacked structures (IEEE 1800-2023 7.2) were rejected. A variable of an unpacked structure type is now a set of leaf variables, one per member that is not itself an unpacked structure, named by the member path (`s.a.b`). Each leaf keeps its member's type, so `string`, class handle, enumeration and 2-state or 4-state integral members behave like variables of those types, and the heap collector finds handle members through their own slots. A whole structure value is the concatenation of its leaves; it only lives within one evaluation. Supported: - module variables, procedural locals, and subroutine arguments of any direction and results (a structure argument is passed flat and copied into and out of its members' variables); - member reads and writes, whole assignment (also continuous, in `always_comb` and nonblocking), `==`, `!=`, `===`, `!==`, `?:`; - assignment patterns: positional, by member name, `default` (applied recursively to nested structures, 10.9.2) and typed `T'{...}`. Only patterns and values of the same structure type may be assigned (6.22.3); other operators, selects and casts of a whole structure are rejected. Ports, nets, parameters, class properties, arrays and container elements of an unpacked structure type, and members with unpacked dimensions or default values, are rejected with dedicated diagnostics; unpacked unions stay unsupported (#440). The concatenation parts of an assignment target now take the raw bits of the value, so a string member receives its handle instead of the bytes of an integral value. sv-tests chapter-7/structures/unpacked/basic now passes in both state modes. Icarus 13.0 does not support unpacked structures, Verilator 5.052 misapplies a nested `default`, and xezim 0.11.3 shows four defects on the new cases; these are retained as reviewed limitations and xezim review entries. Change-Id: I9a94c0cc4394766e17f949f72af405c2a3442b0f --- conformance/sv-tests/expected.tsv | 4 +- crates/celox-frontend-sv/src/lowering/ff.rs | 28 +- crates/celox-sv-analyzer/src/analyze.rs | 2 + crates/celox-sv-analyzer/src/ast.rs | 31 +- .../src/ast/bound_patterns.rs | 1 + .../src/ast/bound_patterns/binding.rs | 8 +- crates/celox-sv-analyzer/src/ast/classes.rs | 3 + .../celox-sv-analyzer/src/ast/comb_process.rs | 15 + .../celox-sv-analyzer/src/ast/containers.rs | 3 + .../celox-sv-analyzer/src/ast/declarations.rs | 32 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 4 + .../src/ast/expression_binding/direct.rs | 30 ++ .../src/ast/expression_binding/objects.rs | 4 + .../src/ast/expression_binding/references.rs | 9 + .../src/ast/expression_binding/strings.rs | 9 + crates/celox-sv-analyzer/src/ast/functions.rs | 1 + .../src/ast/generate/memo/sites.rs | 2 + .../src/ast/packed_structs.rs | 2 +- .../src/ast/packed_structs/layout.rs | 5 +- .../src/ast/packed_structs/selects.rs | 1 + .../src/ast/packed_structs/tests.rs | 2 +- .../celox-sv-analyzer/src/ast/parameters.rs | 6 + .../src/ast/parameters/skipped.rs | 1 + .../src/ast/patterns/binding.rs | 142 ++++++ .../celox-sv-analyzer/src/ast/procedural.rs | 356 +++++++++++++- .../celox-sv-analyzer/src/ast/type_binding.rs | 6 +- .../src/ast/type_binding/binding.rs | 22 +- .../src/ast/unpacked_structs.rs | 439 ++++++++++++++++++ crates/celox-test-suite/LIMITATIONS.md | 2 + crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../src/sv/cases/unpacked_structs.vtest | 279 +++++++++++ .../repros/sv_icarus_unpacked_structs.sv | 1 + .../sv_verilator_nested_struct_default.sv | 9 + ...sv_xezim_constructor_argument_in_always.sv | 26 ++ .../sv_xezim_struct_default_argument.sv | 14 + .../repros/sv_xezim_struct_output_default.sv | 16 + .../repros/sv_xezim_unpacked_structs.sv | 26 ++ .../verification/sv/icarus.json | 3 +- .../sv/icarus/unpacked_structs.json | 188 ++++++++ .../verification/sv/limitations.json | 41 ++ .../verification/sv/verilator.json | 3 +- .../sv/verilator/unpacked_structs.json | 104 +++++ .../verification/sv/xezim.json | 3 +- .../sv/xezim/unpacked_structs.json | 92 ++++ .../verification/xezim-review.json | 72 +++ .../systemverilog/unpacked_structs.rs | 207 +++++++++ crates/celox/tests/systemverilog.rs | 2 + docs/guide/systemverilog-reference.md | 21 +- docs/guide/systemverilog.md | 2 +- docs/ja/guide/systemverilog-reference.md | 21 +- docs/ja/guide/systemverilog.md | 2 +- 51 files changed, 2265 insertions(+), 41 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/unpacked_structs.rs create mode 100644 crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest create mode 100644 crates/celox-test-suite/verification/repros/sv_icarus_unpacked_structs.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_verilator_nested_struct_default.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_xezim_constructor_argument_in_always.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_xezim_struct_default_argument.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_xezim_struct_output_default.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_xezim_unpacked_structs.sv create mode 100644 crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json create mode 100644 crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json create mode 100644 crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json create mode 100644 crates/celox/tests/frontends/systemverilog/unpacked_structs.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index aad26f6f9c8..6dbe602fca6 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1451,8 +1451,8 @@ chapter-7/structures/packed/signed.sv 2state pass chapter-7/structures/packed/signed.sv 4state pass chapter-7/structures/packed/unsigned.sv 2state pass chapter-7/structures/packed/unsigned.sv 4state pass -chapter-7/structures/unpacked/basic.sv 2state fail -chapter-7/structures/unpacked/basic.sv 4state fail +chapter-7/structures/unpacked/basic.sv 2state pass +chapter-7/structures/unpacked/basic.sv 4state pass chapter-7/structures/unpacked/default-value.sv 2state fail chapter-7/structures/unpacked/default-value.sv 4state fail chapter-7/unions/packed/basic.sv 2state pass diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b4688e9cd7e..fb0cf6b38c3 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -3138,11 +3138,24 @@ impl<'p, 'a> Ff<'p, 'a> { &mut self, lhs: &sv::ir::LValue, rhs: &sv::ir::Expr, + ) -> Result<(), sv::AnalyzerError> { + self.assign_value(lhs, rhs, true) + } + + /// Assign `rhs` to `lhs`; `convert` turns an integral value assigned to + /// a string variable into its bytes. The parts of a concatenation target + /// take the bits of the value instead: a part that is a string is a + /// member of an unpacked structure, and its bits are a handle. + fn assign_value( + &mut self, + lhs: &sv::ir::LValue, + rhs: &sv::ir::Expr, + convert: bool, ) -> Result<(), sv::AnalyzerError> { let lhs = self.propagate_lvalue(lhs); let lhs = self.hoist_lvalue(&lhs)?; let converted = match self.m.id(lhs.name()) { - Some(id) if matches!(lhs, sv::ir::LValue::Ident(_)) => { + Some(id) if convert && matches!(lhs, sv::ir::LValue::Ident(_)) => { self.string_conversion(id, rhs.clone()) } _ => rhs.clone(), @@ -3622,7 +3635,7 @@ impl<'p, 'a> Ff<'p, 'a> { lsb: sv::ir::ConstExpr::Literal(lsb.to_string()), signed: false, }; - self.assign(part, &slice)?; + self.assign_value(part, &slice, false)?; } Ok(()) } @@ -4744,7 +4757,10 @@ impl<'p, 'a> Ff<'p, 'a> { })?; let guards = tagged_actual_guards(reference); self.check_tagged_guards(&guards)?; - outputs.push((param.name.clone(), id, lvalues, guards)); + // The members of an unpacked structure take the formal's + // bits, even a single string or handle member. + let concat = matches!(reference, sv::ir::Expr::Concat(_)); + outputs.push((param.name.clone(), id, lvalues, guards, concat)); } } if param.direction.is_read() { @@ -4855,10 +4871,12 @@ impl<'p, 'a> Ff<'p, 'a> { self.jump(return_block); } self.b.switch_to_block(return_block); - for (formal, id, lvalues, guards) in outputs { + for (formal, id, lvalues, guards, concat) in outputs { self.check_tagged_guards(&guards)?; let signed = self.m.var(id).signed; - if let [lvalue] = lvalues.as_slice() { + if let [lvalue] = lvalues.as_slice() + && !concat + { self.assign(lvalue, &sv::ir::Expr::Ident(formal))?; } else { let _ = signed; diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index cfb68bee17c..699f39e19e9 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -134,6 +134,8 @@ fn analyze_source_impl(source: ast::Source) -> Result { let signals = module .signals() .iter() + // A variable of unpacked structure type is its leaf variables. + .filter(|signal| !signal.is_aggregate()) .map(|signal| { ir::Signal::new( signal.name().to_string(), diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 1814f0c8f34..8ea57e2326b 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -185,6 +185,7 @@ mod subroutine_owners; pub(crate) mod timescales; pub(crate) mod type_parameters; mod types; +mod unpacked_structs; pub(crate) mod validation; pub(crate) mod warnings; @@ -1183,12 +1184,20 @@ impl Module { } // A generate block shares its name space with the module's other // declarations (IEEE 1800-2023 27.6, 23.9). + // The members of a variable of unpacked structure type are named + // like declarations of a scope of the variable's name. + let aggregates: HashSet<&str> = signals + .iter() + .filter(|signal| signal.is_aggregate()) + .map(Signal::name) + .collect(); let scope_heads: HashSet<&str> = signals .iter() .filter(|signal| signal.hierarchical.is_none()) .map(Signal::name) .chain(instances.iter().map(Instance::name)) .filter_map(generate_scope_head) + .filter(|head| !aggregates.contains(head)) .collect(); if let Some(conflict) = ports .iter() @@ -1984,6 +1993,12 @@ impl Signal { &self.name } + /// A variable of unpacked structure type, which only names its leaf + /// variables. + pub(crate) fn is_aggregate(&self) -> bool { + self.r#type.unpacked_struct.is_some() + } + pub fn r#type(&self) -> &Type { &self.r#type } @@ -2248,6 +2263,8 @@ pub struct Type { class: Option>, /// The typedef that names an enumeration, struct or union type. nominal: Nominal, + /// The members of an unpacked structure type (IEEE 1800-2023 7.2). + unpacked_struct: Option>, } /// The declaration that names an enumeration, struct or union type, which @@ -2291,6 +2308,7 @@ impl Type { class: None, container: None, nominal: Nominal::default(), + unpacked_struct: None, } } @@ -2307,6 +2325,7 @@ impl Type { signed_element_depth: None, class: None, container: None, + unpacked_struct: None, nominal: Nominal::default(), } } @@ -2315,7 +2334,9 @@ impl Type { /// unless an earlier typedef already named it (`typedef A B` names the /// type of `A`). fn name_declaration(&mut self, name: impl FnOnce() -> String) { - if (self.is_enum || !self.members.is_empty()) && self.nominal.0.is_none() { + if (self.is_enum || !self.members.is_empty() || self.unpacked_struct.is_some()) + && self.nominal.0.is_none() + { self.nominal = Nominal(Some(name().into())); } } @@ -2325,6 +2346,11 @@ impl Type { self.nominal.0.as_deref() } + /// The members of an unpacked structure type. + pub(in crate::ast) fn unpacked_struct(&self) -> Option<&Arc> { + self.unpacked_struct.as_ref() + } + /// The class of an object handle type. pub fn class(&self) -> Option<&str> { self.class.as_deref() @@ -3090,6 +3116,9 @@ struct VariableDimensions { members: Vec, /// See [`Type::signed_element_depth`]. signed_element_depth: Option, + /// A variable of unpacked structure type: the names of its members + /// are variables (see [`unpacked_structs`]). + unpacked_struct: Option>, } type VariablePackedDimensions = HashMap; diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs index f151c001d4a..d9ba65455d1 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -296,6 +296,7 @@ impl BoundPattern { packed: Vec::new(), signed: false, signed_element_depth: None, + unpacked_struct: None, ..shape.clone() }; width diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs index 4dac52c909e..8e1aabe5721 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs @@ -60,9 +60,13 @@ pub(in crate::ast) fn prepare_native( if shape.is_some_and(|shape| { shape.unpacked.is_empty() && shape.packed.len() <= 1 - && shape.members.iter().any(|member| { + && (shape.members.iter().any(|member| { member.name() == instances::normalize_identifier(&name.spelling) - }) + }) || shape.unpacked_struct.as_ref().is_some_and(|aggregate| { + aggregate + .member(&instances::normalize_identifier(&name.spelling)) + .is_some() + })) }) || !dims .const_env .contains_key(&instances::normalize_identifier(&name.spelling)) => diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 61a9dad89fe..fd0d179b66b 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -1167,6 +1167,9 @@ fn field( env: &HashMap, offset: u32, ) -> Converted { + if ty.unpacked_struct().is_some() { + return Err(unsupported("class property of unpacked structure type")); + } 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)), diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 4bc6aaf825e..9d708ca1e75 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -267,6 +267,21 @@ fn continuous_assignments( tree, dimensions, )?; + // A variable of unpacked structure type: drive its leaves. + if let LValue::Ident(name) = &lhs + && let Some(parts) = unpacked_structs::targets(name, dimensions) + { + unpacked_structs::check_assignment(name, assignment.right, tree, dimensions)?; + return Ok(CombProcess::procedural( + CombProcessKind::ContinuousAssign, + None, + vec![Stmt::AssignConcat { + parts, + rhs, + nonblocking: false, + }], + )); + } let rhs = if matches!( lhs, LValue::Select { diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index 236e11d6afe..5c7aadc5856 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -79,6 +79,9 @@ pub(super) fn with_dimensions( if matches!(base.kind(), TypeKind::Real | TypeKind::Shortreal) { return Err(unsupported("real dynamic container elements")); } + if base.unpacked_struct().is_some() { + return Err(unsupported("dynamic container of unpacked structures")); + } let shape = casts::expr_type_from_type(&tree.state, &base, &context.const_env) .ok_or_else(|| unsupported("dynamic container element type"))?; if shape.width == 0 || shape.width > 64 { diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 9fe31e0b168..bdba2b9e6be 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -395,7 +395,37 @@ pub(super) fn signals_from_body_item( _ => Vec::new(), }; substitute_signal_local_constants(&mut declared, env); - signals.extend(declared); + for signal in declared { + if signal.r#type.unpacked_struct().is_none() { + signals.push(signal); + continue; + } + if signal.is_net { + return Err(unsupported("net of unpacked structure type")); + } + if !signal.r#type.unpacked_ranges.is_empty() { + return Err(unsupported("array of unpacked structures")); + } + if signal.is_const { + return Err(unsupported("const variable of unpacked structure type")); + } + if signal.package_variable.is_some() || signal.hierarchical.is_some() { + return Err(unsupported("shared variable of unpacked structure type")); + } + // The variable and its structure members only name its leaf + // variables; they are not storage (see `unpacked_structs`). + let leaves = signal + .r#type + .unpacked_struct() + .expect("checked above") + .leaves(); + for (name, r#type) in unpacked_structs::aggregates(&signal.name, &signal.r#type) { + signals.push(Signal::new(name, r#type)); + } + for leaf in leaves { + signals.push(Signal::new(leaf.name(&signal.name), leaf.r#type)); + } + } Ok(()) } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 6a9c799395f..eb94a5d85ed 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -155,6 +155,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals( ), members: port.r#type().members.clone(), signed_element_depth: port.r#type().signed_element_depth, + unpacked_struct: port.r#type().unpacked_struct.clone(), }, ); } @@ -186,6 +187,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals( ), members: signal.r#type().members.clone(), signed_element_depth: signal.r#type().signed_element_depth, + unpacked_struct: signal.r#type().unpacked_struct.clone(), }, ); } @@ -377,6 +379,7 @@ fn extend_variable_dimensions_from_const_env( signed_element_depth: None, class: None, nominal: Nominal::default(), + unpacked_struct: None, }; let mut shape = procedural::dimensions_from_type(&ty); if let Some(existing) = context.get(name) { @@ -565,6 +568,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP is_2state: parameter.declared_is_2state, members: parameter.members.clone(), signed_element_depth: parameter.signed_element_depth, + unpacked_struct: None, }, ) }) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 847b186a6fb..54e4c835587 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -280,6 +280,24 @@ pub(in crate::ast) fn bind_value( match job { Job::Enter(id, target, scope) => { let dimensions = scope.as_deref().unwrap_or(dimensions); + unpacked_structs::check_operands(id, native, tree, dimensions)?; + // An argument, result or other value received as an unpacked + // structure is a pattern or a value of its type (6.22.3). + if let Some(aggregate) = target + .as_deref() + .filter(|shape| shape.unpacked.is_empty()) + .and_then(|shape| shape.unpacked_struct.as_deref()) + { + unpacked_structs::check_value(aggregate, id, native, tree, dimensions)?; + } else if target + .as_deref() + .is_some_and(|shape| shape.unpacked.is_empty() && shape.container.is_none()) + && unpacked_structs::native_struct(id, native, tree, dimensions)?.is_some() + { + return Err(unsupported( + "unpacked structure value received by a destination that is not of its type", + )); + } if let Some(shape) = target.as_deref() && shape .members @@ -463,6 +481,10 @@ pub(in crate::ast) fn bind_value( { return Err(unsupported(format!("`{name}`"))); } + if let Some(value) = unpacked_structs::whole(&name, dimensions) { + values.push(value); + continue; + } if let Some(value) = objects::unqualified_property(tree, dimensions, &name)? { values.push(value); @@ -1592,6 +1614,9 @@ fn path( } } parts.reverse(); + if qualified.is_none() { + unpacked_structs::collapse(&mut parts, dimensions); + } if qualified.is_none() && let Some(name) = interface_binding::unindexed_parameter(&parts, tree, dimensions, authored) @@ -1720,6 +1745,11 @@ fn selected_value( &selected_lvalue(root, native, tree, dimensions, false)?, dimensions, ); + if let Expr::Ident(name) = &value + && let Some(value) = unpacked_structs::whole(name, dimensions) + { + return Ok(value); + } let guards = member_context(root, native, tree, dimensions)? .map(|(guards, _)| guards) .unwrap_or_default(); 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 3103b79bf8f..f436e4d63e5 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -42,6 +42,10 @@ pub(in crate::ast) fn native_class( { return Some(super::super::processes::CLASS.to_owned()); } + // A class handle member of an unpacked structure variable. + if let Some(name) = unpacked_structs::native_member(ungroup(id, native), native, dimensions) { + return dimensions.get(&name)?.class.clone(); + } let expression = native.expression(ungroup(id, native)); if let ExprKind::Select { expression, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs index 86071720434..6c419491854 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs @@ -134,6 +134,15 @@ pub(super) fn check_actual( .subroutine_param_shapes .get(name) .and_then(|shapes| shapes.get(position)); + // The members of a structure are separate variables, which one reference + // cannot alias. + if formal.is_some_and(|formal| formal.unpacked_struct.is_some()) + || shape.unpacked_struct.is_some() + { + return Err(unsupported(format!( + "ref argument of `{name}` of unpacked structure type" + ))); + } // Bounded and unbounded queues are equivalent (6.22.2), but a formal's // operations would apply its own bound to the actual. if let (Some(formal), Some(actual)) = ( 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 ebde30f4eab..0fadf8370fa 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -179,6 +179,15 @@ pub(in crate::ast) fn native_string( } // `e.name` without parentheses (6.19.5.6, 6.19.5.7). ExprKind::Member { .. } if enum_name(tree, id, native, dimensions) => true, + // A string member of an unpacked structure variable. + ExprKind::Member { .. } + if unpacked_structs::native_member(ungroup(id, native), native, dimensions) + .is_some() => + { + unpacked_structs::native_member(ungroup(id, native), native, dimensions) + .and_then(|name| dimensions.get(&name)) + .is_some_and(|ty| ty.string) + } // A string property of a class object. _ => objects::property(tree, id, native, dimensions) .ok() diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 0c0813c79aa..a6d1e25580f 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -263,6 +263,7 @@ fn native_signature( !ty.members.is_empty() || !ty.unpacked_ranges.is_empty() || ty.packed_ranges.len() > 1 + || ty.unpacked_struct.is_some() }) .and_then(|ty| { ty.pattern_target(&const_functions::Environment { diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs index f44b20d91d2..0dadfcf2e14 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs @@ -161,6 +161,7 @@ impl CallSites for Type { class: _, container: _, nominal: _, + unpacked_struct: _, } = self; packed_ranges.call_sites(visit); unpacked_ranges.call_sites(visit); @@ -201,6 +202,7 @@ impl CallSites for VariableDimensions { is_2state: _, members, signed_element_depth: _, + unpacked_struct: _, } = self; packed.call_sites(visit); unpacked.call_sites(visit); diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs.rs b/crates/celox-sv-analyzer/src/ast/packed_structs.rs index 9d89177852c..b7de43e09ed 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs.rs @@ -11,7 +11,7 @@ pub(in crate::ast) use tagged::{ #[cfg(test)] mod tests; -pub(super) use layout::{AggregateKind, native_type}; +pub(super) use layout::{AggregateKind, capture_member_type, native_type}; pub(super) use selects::{select_member, whole_member}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index 2409ee97561..f2f72a5e809 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -17,7 +17,10 @@ pub(in crate::ast) fn capture_member_type( mut ty: Type, env: &HashMap, ) -> Option { - if !ty.unpacked_ranges.is_empty() || matches!(ty.kind, TypeKind::Real | TypeKind::Shortreal) { + if !ty.unpacked_ranges.is_empty() + || ty.unpacked_struct.is_some() + || matches!(ty.kind, TypeKind::Real | TypeKind::Shortreal) + { return None; } for range in &mut ty.packed_ranges { diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 3c033e560da..afa4c904d67 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -87,6 +87,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - is_2state: r#type.kind == TypeKind::Bit, members: r#type.members.clone(), signed_element_depth: r#type.signed_element_depth, + unpacked_struct: None, }, ); result diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs index 6c745e2f934..5611d331d71 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs @@ -47,7 +47,7 @@ fn preserves_layout_signedness_and_state_kind() { #[test] fn rejects_invalid_or_unsupported_struct_shapes() { for body in [ - "struct { logic a; } value;", + "union { logic a; } value;", "union packed { logic a; logic [1:0] b; } value;", "union soft { real a; bit [63:0] b; } value;", "union soft { logic a[2]; logic b; } value;", diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 7f519807931..98b15012880 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -375,6 +375,12 @@ pub(super) fn parameters_from_native_with_environment( && declared_alias .as_ref() .is_none_or(|alias| alias.members.is_empty() && alias.unpacked_ranges.is_empty()); + if declared_alias + .as_ref() + .is_some_and(|alias| alias.unpacked_struct().is_some()) + { + return Err(unsupported("parameter of unpacked structure type")); + } let parameter_members = declared_alias .as_ref() .map(|ty| ty.members.clone()) diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index f05a05e2eb9..84e9584282b 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -527,6 +527,7 @@ fn pattern_items( signed: false, is_2state: shape.is_2state, signed_element_depth: None, + unpacked_struct: None, }, ) }; diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 0e5444bf9a0..8077603163b 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -102,6 +102,15 @@ fn select<'a>( shape: Shape<'a>, dims: &PackedDimensions, ) -> Converted<(Vec>, bool, bool)> { + if let Some(aggregate) = shape.unpacked_struct.clone() + && shape.unpacked.is_empty() + { + return Ok(( + unpacked_struct_items(&aggregate, kind, bindings)?, + false, + true, + )); + } if let Some((dim, rest)) = shape.unpacked.split_first() { let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { @@ -153,6 +162,7 @@ fn select<'a>( .signed_element_depth .and_then(|depth| depth.checked_sub(1)) .filter(|depth| *depth > 0), + unpacked_struct: None, })); let items = indexed_items(kind, bindings, count, |index| { (left.min(right)..=left.max(right)) @@ -262,6 +272,7 @@ fn select<'a>( is_2state: shape.is_2state, members: Vec::new(), signed_element_depth: None, + unpacked_struct: None, })); let items = indexed_items(kind, bindings, width, |index| { usize::try_from(index) @@ -415,6 +426,69 @@ pub(in crate::ast) fn bind_native( if check { check_native_array(&tree.state, id, native, &shape, dims)?; } + // A typed pattern of a member must name the member's + // structure type (6.22.3). + if pattern && let Some(aggregate) = shape.unpacked_struct.as_deref() { + unpacked_structs::check_value(aggregate, id, native, tree, dims)?; + } + if let Some(aggregate) = shape.unpacked_struct.clone() + && !pattern + { + // A default that is not a structure of the member's type + // applies to each of its members (IEEE 1800-2023 10.9.2). + if default && unpacked_structs::native_struct(id, native, tree, dims)?.is_none() + { + let members = aggregate.members(); + jobs.push(Job::Finish { + count: members.len(), + reverse: false, + keep: true, + }); + jobs.extend(members.iter().rev().map(|member| { + Job::Value(Selected { + value: id, + shape: Shape::Owned(Rc::new(procedural::dimensions_from_type( + &member.r#type, + ))), + default: true, + check: false, + }) + })); + continue; + } + unpacked_structs::check_value(&aggregate, id, native, tree, dims)?; + values.push(expression_binding::bind_value( + id, native, tree, dims, None, + )?); + continue; + } + if let Some(class) = shape.class.as_deref() + && !pattern + { + if let Some(call) = + expression_binding::object_constructor(tree, id, native, dims, class)? + { + values.push(call); + continue; + } + expression_binding::check_handle_assignment( + tree, + id, + native, + dims, + class, + || "assignment pattern member".into(), + )?; + } + if (shape.string || shape.class.is_some()) && !pattern { + let value = expression_binding::bind_value(id, native, tree, dims, None)?; + values.push(if shape.string { + expression_binding::string_operand(value, dims) + } else { + value + }); + continue; + } if pattern { let typed = typed_shape(id, tree, dims)?; jobs.push(Job::Pattern( @@ -475,6 +549,74 @@ pub(in crate::ast) fn bind_native( } values.pop().ok_or_else(mismatch) } +/// The member values of an assignment pattern for an unpacked structure +/// (IEEE 1800-2023 10.9.2), first declared first. +fn unpacked_struct_items<'a>( + aggregate: &unpacked_structs::UnpackedStruct, + kind: NativeKind, + bindings: Vec, +) -> Converted>> { + let members = aggregate.members(); + let values = match kind { + NativeKind::List => { + if bindings.len() != members.len() { + return Err(unsupported(format!( + "assignment pattern with {} items for {} structure members", + bindings.len(), + members.len() + ))); + } + bindings.into_iter().map(|value| (value, false)).collect() + } + NativeKind::Keyed(keys) => { + let mut named = Vec::new(); + let mut default = None; + for (key, value) in keys.into_iter().zip(bindings) { + match key { + Key::Member(name) if aggregate.member(&name).is_some() => { + named.push((name, value)) + } + Key::Member(name) => { + return Err(unsupported(format!( + "assignment pattern key `{name}` that is not a structure member" + ))); + } + Key::Default => default = Some(value), + Key::Index(_) | Key::Name { .. } => { + return Err(unsupported("structure assignment pattern form")); + } + } + } + members + .iter() + .map(|member| { + named + .iter() + .find(|(name, _)| *name == member.name) + .map(|(_, value)| (*value, false)) + .or(default.map(|value| (value, true))) + .ok_or_else(|| { + unsupported(format!( + "assignment pattern without a value for member `{}`", + member.name + )) + }) + }) + .collect::>>()? + } + _ => return Err(unsupported("structure assignment pattern form")), + }; + Ok(members + .iter() + .zip(values) + .map(|(member, (value, default))| Selected { + value, + shape: Shape::Owned(Rc::new(procedural::dimensions_from_type(&member.r#type))), + default, + check: false, + }) + .collect()) +} fn native_rank( mut id: ExprId, native: &celox_sv_syntax::Declarations, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 95062607189..cb235b27221 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -100,6 +100,7 @@ pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { ), members: r#type.members.clone(), signed_element_depth: r#type.signed_element_depth, + unpacked_struct: r#type.unpacked_struct.clone(), } } @@ -121,6 +122,60 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - r#type } +/// Run `epilogue` at each `return` in `body`. A returned value is first +/// stored in the result variable `result`, so the epilogue sees the effects +/// of evaluating it. +fn before_returns(body: &mut Vec, epilogue: &[Stmt], result: Option<&str>) { + let mut pending = vec![body]; + while let Some(stmts) = pending.pop() { + let mut index = 0; + while index < stmts.len() { + if let Stmt::Return(value) = &mut stmts[index] { + let mut exit = Vec::new(); + if let (Some(value), Some(result)) = (value.take(), result) { + exit.push(Stmt::Assign { + lhs: LValue::Ident(result.to_owned()), + rhs: value, + nonblocking: false, + }); + stmts[index] = Stmt::Return(Some(Expr::Ident(result.to_owned()))); + } + exit.extend(epilogue.iter().cloned()); + let count = exit.len(); + stmts.splice(index..index, exit); + index += count + 1; + continue; + } + index += 1; + } + for stmt in stmts.iter_mut() { + match stmt { + Stmt::If { + then_body, + else_body, + .. + } => { + pending.push(then_body); + pending.push(else_body); + } + Stmt::Case { items, default, .. } => { + pending.extend(items.iter_mut().map(|item| &mut item.body)); + pending.extend(default.as_mut()); + } + Stmt::Loop { + init, step, body, .. + } => { + pending.push(init); + pending.push(step); + pending.push(body); + } + // A `return` in a forked branch ends only that branch. + _ => {} + } + } + } +} + /// The `int` type of a loop variable declared by `foreach`. pub(super) fn int_type() -> Type { Type { @@ -139,6 +194,7 @@ pub(super) fn int_type() -> Type { signed_element_depth: None, class: None, nominal: Nominal::default(), + unpacked_struct: None, } } @@ -554,6 +610,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if let Some(stmt) = self.property_assignment(op, nonblocking, left, right)? { return Ok(stmt); } + if let Some(stmt) = self.aggregate_assignment(op, nonblocking, left, right)? { + return Ok(stmt); + } if op != "=" { self.reject_tagged_integral_target(left)?; } @@ -624,6 +683,51 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }) } + /// An assignment to a whole variable or member of unpacked structure + /// type, which writes each of its leaf variables (IEEE 1800-2023 7.2). + fn aggregate_assignment( + &self, + op: &str, + nonblocking: bool, + left: celox_sv_syntax::ExprId, + right: celox_sv_syntax::ExprId, + ) -> Result, AnalyzerError> { + let Ok(written) = expression_binding::variable_lvalue( + left, + self.tree.declarations(), + self.tree, + &self.dims, + ) else { + return Ok(None); + }; + let LValue::Ident(name) = &written else { + return Ok(None); + }; + let Some(mut parts) = unpacked_structs::targets(name, &self.dims) else { + return Ok(None); + }; + if op != "=" { + return Err(unsupported(format!( + "operator `{op}` on an unpacked structure" + ))); + } + let mut rhs = expression_binding::expression( + right, + self.tree.declarations(), + &written, + self.tree, + &self.dims, + )?; + unpacked_structs::check_assignment(name, right, self.tree, &self.dims)?; + parts.iter_mut().for_each(|part| self.rename_lvalue(part)); + self.rename_expr(&mut rhs); + Ok(Some(Stmt::AssignConcat { + parts, + rhs, + nonblocking, + })) + } + /// `str[i] = c`, which replaces one character like `str.putc(i, c)` /// (IEEE 1800-2023 6.16.2). fn string_character_assignment( @@ -1226,17 +1330,28 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } None => None, }; + let automatic = match native.lifetime.as_deref() { + Some("automatic") => true, + Some("static") => false, + _ => self.automatic, + }; + if signal.r#type().unpacked_struct().is_some() { + let explicit = native.lifetime.as_deref() == Some("static"); + stmts.extend(self.aggregate_local( + &signal, + assignment.value, + init, + automatic, + explicit, + )?); + continue; + } let name = self.declare(signal.name(), signal.r#type().clone()); if signal.is_const { let mut shape = self.dims.get(signal.name()).unwrap().clone(); shape.randomizable = false; self.dims.insert(signal.name().to_string(), shape); } - let automatic = match native.lifetime.as_deref() { - Some("automatic") => true, - Some("static") => false, - _ => self.automatic, - }; if !automatic { if native.lifetime.as_deref() == Some("static") { self.state.explicit_statics.insert(name.clone()); @@ -1249,6 +1364,124 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { Ok(stmts) } + /// A local of unpacked structure type: its leaf variables, then the + /// assignment of its initializer. + fn aggregate_local( + &mut self, + signal: &crate::ast::Signal, + root: Option, + init: Option, + automatic: bool, + explicit: bool, + ) -> Result, AnalyzerError> { + if signal.is_const { + return Err(unsupported("const variable of unpacked structure type")); + } + if let Some(root) = root { + let aggregate = signal + .r#type() + .unpacked_struct() + .expect("an unpacked structure local"); + unpacked_structs::check_value( + aggregate, + root, + self.tree.declarations(), + self.tree, + &self.dims, + )?; + } + let leaves = self.declare_aggregate(signal.name(), signal.r#type())?; + // A static variable is initialized once, not on each entry: each leaf + // keeps its part of the initializer, which is hoisted with it. + let aggregate = signal + .r#type() + .unpacked_struct() + .expect("an unpacked structure local") + .clone(); + let mut init = init; + let mut parts = match init.take() { + Some(value) + if !automatic && unpacked_structs::leaf_parts(&aggregate, &value).is_some() => + { + unpacked_structs::leaf_parts(&aggregate, &value) + .expect("checked by the guard") + .into_iter() + .map(Some) + .collect() + } + Some(_) if !automatic => { + return Err(unsupported( + "initializer of a static variable of unpacked structure type that is not a pattern or variable", + )); + } + other => { + init = other; + vec![None; leaves.len()] + } + }; + let mut stmts = Vec::new(); + for ((name, r#type), part) in leaves.iter().zip(parts.drain(..)) { + if !automatic { + // An explicitly static member of a repeating process is + // initialized before simulation, like a scalar. + if explicit { + self.state.explicit_statics.insert(name.clone()); + } + let r#type = scoped_type(r#type.clone(), &self.dims.const_env); + self.state.statics.push((name.clone(), r#type)); + } + stmts.push(Stmt::Local { + name: name.clone(), + init: part, + }); + } + if let Some(rhs) = init { + stmts.push(Stmt::AssignConcat { + parts: leaves + .into_iter() + .map(|(name, _)| LValue::Ident(name)) + .collect(), + rhs, + nonblocking: false, + }); + } + Ok(stmts) + } + + /// Declare a variable of unpacked structure type: hide the names of it + /// and its members, then declare its leaf variables. Returns their unique + /// names and types, first declared first. + pub(super) fn declare_aggregate( + &mut self, + source: &str, + r#type: &Type, + ) -> Result, AnalyzerError> { + if !r#type.unpacked_ranges.is_empty() { + return Err(unsupported("array of unpacked structures")); + } + for (name, ty) in unpacked_structs::aggregates(source, r#type) { + let entry = self.take_binding(&name, None, 0); + self.dims.insert(name.clone(), dimensions_from_type(&ty)); + self.scopes + .last_mut() + .expect("a body always has a scope") + .entries + .push(entry); + } + let aggregate = r#type + .unpacked_struct() + .expect("an unpacked structure type") + .clone(); + Ok(aggregate + .leaves() + .into_iter() + .map(|leaf| { + let name = self.declare(&leaf.name(source), leaf.r#type.clone()); + (name, leaf.r#type) + }) + .collect()) + } + /// Make the parameters of a declaration in the body known as constants. fn local_parameters( &mut self, @@ -2556,7 +2789,8 @@ pub(super) fn lower_subroutine( .map(|(_, _, ty, default)| { default .map(|root| { - let shape = ty.tagged_identity().map(|_| dimensions_from_type(ty)); + let shape = (ty.tagged_identity().is_some() || ty.unpacked_struct().is_some()) + .then(|| dimensions_from_type(ty)); let mut value = expression_binding::bind_value( root, tree.declarations(), @@ -2587,8 +2821,12 @@ pub(super) fn lower_subroutine( .map(|_| None) .chain(defaults) .collect::>(); + let mut aggregate_formals = Vec::new(); for ((source, direction, r#type, _), default) in this.into_iter().chain(params).zip(defaults) { let name = builder.declare(&source, r#type.clone()); + if r#type.unpacked_struct().is_some() { + aggregate_formals.push((lowered_params.len(), r#type.clone())); + } formal_types.insert(name.clone(), scoped_type(r#type.clone(), declaration_env)); lowered_params.push(SubroutineParam { name, @@ -2612,8 +2850,72 @@ pub(super) fn lower_subroutine( } builder.return_shape = return_type .as_ref() - .filter(|ty| ty.tagged_identity().is_some()) + .filter(|ty| ty.tagged_identity().is_some() || ty.unpacked_struct().is_some()) .map(dimensions_from_type); + // An argument of unpacked structure type is passed as its flat value; + // the body works on its members (see `unpacked_structs`). + let mut aggregate_prologue = Vec::new(); + let mut aggregate_epilogue = Vec::new(); + // A result of unpacked structure type assigned through the function's + // name is assembled from its members when the body ends without + // `return` (IEEE 1800-2023 13.4.1). + let mut result_leaves = None; + if dispatch.is_none() + && let (Some(result), Some(r#type)) = (&return_var, &return_type) + && r#type.unpacked_struct().is_some() + && !constructor + { + let leaves = builder + .declare_aggregate(&name, r#type)? + .into_iter() + .map(|(leaf, _)| leaf) + .collect::>(); + // An automatic result starts each call at its default. + if builder.automatic { + aggregate_prologue.extend(leaves.iter().map(|leaf| Stmt::Local { + name: leaf.clone(), + init: None, + })); + } + result_leaves = Some((result.clone(), leaves)); + } + if dispatch.is_none() { + for (index, r#type) in &aggregate_formals { + let param = &lowered_params[*index]; + let (name, source, direction) = ( + param.name.clone(), + param.source_name.clone(), + param.direction, + ); + let leaves = builder + .declare_aggregate(&source, r#type)? + .into_iter() + .map(|(leaf, _)| leaf) + .collect::>(); + if direction.is_read() { + aggregate_prologue.push(Stmt::AssignConcat { + parts: leaves.iter().cloned().map(LValue::Ident).collect(), + rhs: Expr::Ident(name.clone()), + nonblocking: false, + }); + } else if builder.automatic { + // An automatic output starts each call at its default. + aggregate_prologue.extend(leaves.iter().map(|leaf| Stmt::Local { + name: leaf.clone(), + init: None, + })); + } + if direction.is_written() { + aggregate_epilogue.push(Stmt::Assign { + lhs: LValue::Ident(name), + rhs: Expr::Concat(leaves.into_iter().map(Expr::Ident).collect()), + nonblocking: false, + }); + } + } + } + // The members of formals and of the result have the subroutine's + // lifetime, like the formals themselves. let parameter_locals_end = builder.state.locals.len(); let mut items = native.items.clone(); let mut prologue = Vec::new(); @@ -2649,8 +2951,24 @@ pub(super) fn lower_subroutine( &lowered_params, return_var.as_deref(), )), - None => body.extend(builder.native_body(&items, &native.authored_statements)?), + None => { + body.extend(aggregate_prologue); + body.extend(builder.native_body(&items, &native.authored_statements)?); + } + } + if !aggregate_epilogue.is_empty() { + // Copy the members back on every way out of the body, after the + // value of a `return` is taken. + before_returns(&mut body, &aggregate_epilogue, return_var.as_deref()); } + if let Some((result, leaves)) = result_leaves { + body.push(Stmt::Assign { + lhs: LValue::Ident(result), + rhs: Expr::Concat(leaves.into_iter().map(Expr::Ident).collect()), + nonblocking: false, + }); + } + body.extend(aggregate_epilogue); builder.pop_scope(); if class.is_some() { builder.pop_scope(); @@ -3375,10 +3693,24 @@ pub(super) fn initial_processes_from_scope( tree, item_dimensions, )?; - let mut stmt = Stmt::Assign { - lhs, - rhs, - nonblocking: false, + let LValue::Ident(name) = lhs else { + unreachable!("an initializer target is a variable") + }; + // A variable of unpacked structure type initializes its leaves. + let mut stmt = match unpacked_structs::targets(&name, item_dimensions) { + Some(parts) => { + unpacked_structs::check_assignment(&name, native, tree, item_dimensions)?; + Stmt::AssignConcat { + parts, + rhs, + nonblocking: false, + } + } + None => Stmt::Assign { + lhs: LValue::Ident(name), + rhs, + nonblocking: false, + }, }; // The parameters of the class are its own constants. if scoped.is_some() { diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 371ab227f0c..e354b7d1df5 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -56,7 +56,11 @@ pub(super) fn port_type( let Some(id) = port.data_type else { return Ok(None); }; - bind(id, tree, &context) + let ty = bind(id, tree, &context)?; + if ty.as_ref().is_some_and(|ty| ty.unpacked_struct().is_some()) { + return Err(unsupported("port of unpacked structure type")); + } + Ok(ty) } /// Formal/return implicit types use scalar logic rather than an unsized local. diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 3a451b401ed..c19067bbbbb 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -88,6 +88,7 @@ fn bind_in_mode( signed: bool, names: Vec, ranges: Vec, + packed: bool, }, } let mut jobs = vec![Job::Enter(root)]; @@ -281,7 +282,8 @@ fn bind_in_mode( packed, fields, } => { - if !packed && !soft { + // Unpacked unions are not supported (IEEE 1800-2023 7.3). + if !packed && !soft && (*union || *tagged) { return Ok(None); } let mut names = Vec::new(); @@ -325,6 +327,7 @@ fn bind_in_mode( signed: data.signed.unwrap_or(false), names, ranges, + packed: *packed || *soft, }); jobs.extend(fields.iter().zip(voids).rev().map(|(field, is_void)| { if is_void { @@ -383,11 +386,28 @@ fn bind_in_mode( signed, names, ranges, + packed, } => { let start = values .len() .checked_sub(names.len()) .ok_or_else(|| unsupported("aggregate fields"))?; + if !packed { + if !ranges.is_empty() { + return Ok(None); + } + let fields = names.into_iter().zip(values.split_off(start)).collect(); + let Some(ty) = unpacked_structs::native_type( + &tree.state, + owner, + fields, + &context.const_env, + ) else { + return Ok(None); + }; + values.push(ty); + continue; + } let fields = names .into_iter() .zip(values.split_off(start)) diff --git a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs new file mode 100644 index 00000000000..0b7bb83d67b --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs @@ -0,0 +1,439 @@ +//! Unpacked structures (IEEE 1800-2023 7.2). +//! +//! An unpacked structure is not storage of its own. A variable of such a type +//! is a set of *leaf* variables, one for each member that is not itself an +//! unpacked structure, named by its member path (`s.a.b`). Each leaf keeps the +//! type of its member, so a `string` or class handle member is an ordinary +//! string or handle variable. +//! +//! A value of the whole structure is the concatenation of its leaves, the +//! first declared member in the most significant bits. Such a flat value only +//! lives inside one evaluation, so the handles it carries need no root of +//! their own. + +use super::*; +use celox_sv_syntax::{ExprId, ExprKind}; + +/// The members of an unpacked structure type. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(in crate::ast) struct UnpackedStruct { + /// Nominal identity (IEEE 1800-2023 6.22.1): the declaration. + owner: Arc, + members: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(in crate::ast) struct Member { + pub(in crate::ast) name: String, + pub(in crate::ast) r#type: Type, + /// Bits of the member in a flat value. + pub(in crate::ast) width: usize, +} + +/// A member that is not an unpacked structure, with its place in a flat value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::ast) struct Leaf { + /// Member names from the structure down to the leaf. + pub(in crate::ast) path: Vec, + pub(in crate::ast) r#type: Type, + /// Least significant bit in a flat value. + pub(in crate::ast) offset: usize, + pub(in crate::ast) width: usize, +} + +impl Leaf { + /// The name of this leaf of the variable `base`. + pub(in crate::ast) fn name(&self, base: &str) -> String { + leaf_name(base, &self.path) + } +} + +/// The leaf or member variable `path` of `base`. +pub(in crate::ast) fn leaf_name(base: &str, path: &[String]) -> String { + let mut name = base.to_owned(); + for part in path { + name.push('.'); + name.push_str(part); + } + name +} + +impl UnpackedStruct { + pub(in crate::ast) fn same_type(&self, other: &Self) -> bool { + self.owner == other.owner + } + + pub(in crate::ast) fn members(&self) -> &[Member] { + &self.members + } + + pub(in crate::ast) fn member(&self, name: &str) -> Option<&Member> { + self.members.iter().find(|member| member.name == name) + } + + /// Bits of a flat value. + pub(in crate::ast) fn width(&self) -> usize { + self.members.iter().map(|member| member.width).sum() + } + + /// The leaves in declaration order. + pub(in crate::ast) fn leaves(&self) -> Vec { + let mut leaves = Vec::new(); + let mut offset = self.width(); + // Depth-first in declaration order: members are pushed in reverse. + fn push<'m>( + stack: &mut Vec<(Vec, &'m Member)>, + path: &[String], + members: &'m [Member], + ) { + for member in members.iter().rev() { + let mut member_path = path.to_vec(); + member_path.push(member.name.clone()); + stack.push((member_path, member)); + } + } + let mut stack = Vec::new(); + push(&mut stack, &[], &self.members); + while let Some((path, member)) = stack.pop() { + if let Some(inner) = member.r#type.unpacked_struct() { + push(&mut stack, &path, &inner.members); + continue; + } + offset -= member.width; + leaves.push(Leaf { + path, + r#type: member.r#type.clone(), + offset, + width: member.width, + }); + } + leaves + } +} + +/// The type of an unpacked structure with `fields`, or `None` when a member +/// type has no supported unpacked-structure representation. +pub(in crate::ast) fn native_type( + state: &AnalysisState, + owner: Arc, + fields: Vec<(String, Type)>, + env: &HashMap, +) -> Option { + let members = fields + .into_iter() + .map(|(name, ty)| { + if !ty.unpacked_ranges.is_empty() + || ty.container.is_some() + || matches!(ty.kind, TypeKind::Real | TypeKind::Shortreal) + { + return None; + } + let ty = match ty.unpacked_struct() { + Some(_) => ty, + None => packed_structs::capture_member_type(state, ty, env)?, + }; + let width = match ty.unpacked_struct() { + Some(inner) => inner.width(), + None => casts::expr_type_from_type(state, &ty, env)?.width, + }; + Some(Member { + name, + r#type: ty, + width, + }) + }) + .collect::>>()?; + let aggregate = UnpackedStruct { owner, members }; + let four_state = aggregate.leaves().iter().any(|leaf| { + matches!( + leaf.r#type.kind, + TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit + ) + }); + let width = aggregate.width(); + let mut r#type = Type::new(if four_state { + TypeKind::Logic + } else { + TypeKind::Bit + }); + r#type.packed_ranges.push(PackedRange::new( + ConstExpr::Literal(width.checked_sub(1)?.to_string()), + ConstExpr::Literal("0".into()), + )); + r#type.unpacked_struct = Some(Arc::new(aggregate)); + Some(r#type) +} + +/// The flat value of the variable or member `name` of unpacked structure +/// type: the concatenation of its leaf variables. +pub(in crate::ast) fn whole(name: &str, dims: &PackedDimensions) -> Option { + let aggregate = dims.get(name)?.unpacked_struct.clone()?; + Some(Expr::Concat( + aggregate + .leaves() + .iter() + .map(|leaf| Expr::Ident(leaf.name(name))) + .collect(), + )) +} + +/// The leaf variables that an assignment to the whole variable or member +/// `name` of unpacked structure type writes, first declared first. +pub(in crate::ast) fn targets(name: &str, dims: &PackedDimensions) -> Option> { + let aggregate = dims.get(name)?.unpacked_struct.clone()?; + Some( + aggregate + .leaves() + .iter() + .map(|leaf| LValue::Ident(leaf.name(name))) + .collect(), + ) +} + +/// Join the leading names of a member path that select within a variable of +/// unpacked structure type: they name one of its member variables. +pub(in crate::ast) fn collapse(parts: &mut Vec, dims: &PackedDimensions) { + if parts.len() < 2 + || !dims + .get(&parts[0]) + .is_some_and(|shape| shape.unpacked_struct.is_some()) + { + return; + } + let mut name = parts[0].clone(); + let mut used = 1; + for part in &parts[1..] { + let candidate = format!("{name}.{part}"); + if dims.get(&candidate).is_none() { + break; + } + name = candidate; + used += 1; + } + parts.splice(..used, [name]); +} + +/// Every variable and member of unpacked structure type in a variable +/// `base` of type `aggregate`, outermost first, with its type. +pub(in crate::ast) fn aggregates(base: &str, r#type: &Type) -> Vec<(String, Type)> { + let mut found = Vec::new(); + let mut jobs = vec![(base.to_owned(), r#type.clone())]; + while let Some((name, ty)) = jobs.pop() { + if let Some(aggregate) = ty.unpacked_struct() { + for member in aggregate.members.iter().rev() { + jobs.push((format!("{name}.{}", member.name), member.r#type.clone())); + } + found.push((name, ty)); + } + } + found +} + +/// The unpacked structure type of native expression `id`, judged before it +/// is bound, or `None` when it is not a value of such a type. +pub(in crate::ast) fn native_struct( + id: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted>> { + let id = expression_binding::ungroup(id, native); + Ok(match &native.expression(id).kind { + ExprKind::Name(_) | ExprKind::Member { .. } => member_path(id, native) + .map(|mut parts| { + collapse(&mut parts, dims); + parts + }) + .filter(|parts| parts.len() == 1) + .and_then(|parts| dims.get(&parts[0])?.unpacked_struct.clone()), + ExprKind::Conditional { + then_expression, + else_expression, + .. + } => { + let then_type = native_struct(*then_expression, native, tree, dims)?; + let else_type = native_struct(*else_expression, native, tree, dims)?; + then_type.filter(|then_type| { + else_type + .as_ref() + .is_some_and(|else_type| then_type.same_type(else_type)) + }) + } + // A typed assignment pattern, `T'{...}`. + ExprKind::Pattern { + target: Some(_), .. + } if std::ptr::eq(native, tree.declarations()) => { + patterns::typed_shape(id, tree, dims)?.and_then(|shape| shape.unpacked_struct) + } + ExprKind::Call { expression, .. } => { + expression_binding::callable_name(&tree.state, *expression, native) + .and_then(|name| dims.functions.get(&name)) + .and_then(|function| function.return_type.as_ref()) + .and_then(|ty| ty.unpacked_struct().cloned()) + } + _ => None, + }) +} + +/// The names of a native `a.b.c` path, or `None` for another expression. +fn member_path(mut id: ExprId, native: &celox_sv_syntax::Declarations) -> Option> { + let mut parts = Vec::new(); + loop { + match &native.expression(id).kind { + ExprKind::Name(name) => { + parts.push(instances::normalize_identifier(&name.spelling)); + break; + } + ExprKind::Member { + expression, + separator, + name, + } if separator == "." => { + parts.push(instances::normalize_identifier(&name.spelling)); + id = *expression; + } + ExprKind::Group(inner) => id = *inner, + _ => return None, + } + } + parts.reverse(); + Some(parts) +} + +/// The variable that native member path `id` names when it selects within a +/// variable of unpacked structure type. +pub(in crate::ast) fn native_member( + id: ExprId, + native: &celox_sv_syntax::Declarations, + dims: &PackedDimensions, +) -> Option { + let mut parts = member_path(id, native)?; + if parts.len() < 2 { + return None; + } + collapse(&mut parts, dims); + (parts.len() == 1).then(|| parts.pop().expect("one part")) +} + +/// Check that `right` may be assigned to the variable or member `name` of +/// unpacked structure type: an assignment pattern or a value of the same +/// type (IEEE 1800-2023 6.22.3). +pub(in crate::ast) fn check_assignment( + name: &str, + right: ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted<()> { + let target = dims + .get(name) + .and_then(|shape| shape.unpacked_struct.clone()) + .ok_or_else(|| unsupported("unpacked structure target"))?; + check_value(&target, right, tree.declarations(), tree, dims) +} + +/// Check that `value` is an assignment pattern or a value of type `target`. +pub(in crate::ast) fn check_value( + target: &UnpackedStruct, + value: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted<()> { + let value = expression_binding::ungroup(value, native); + // An untyped pattern takes the target's type; a typed one, `T'{...}`, + // must name it. + if matches!( + native.expression(value).kind, + ExprKind::Pattern { target: None, .. } + ) { + return Ok(()); + } + if let ExprKind::Conditional { + then_expression, + else_expression, + .. + } = &native.expression(value).kind + { + check_value(target, *then_expression, native, tree, dims)?; + return check_value(target, *else_expression, native, tree, dims); + } + match native_struct(value, native, tree, dims)? { + Some(actual) if actual.same_type(target) => Ok(()), + _ => Err(unsupported( + "assignment to an unpacked structure of a value that is not of its type", + )), + } +} + +/// Reject an operator applied to a whole unpacked structure value: only the +/// equality operators, the conditional operator and assignment take one +/// (IEEE 1800-2023 7.2, 11.2.2). +pub(in crate::ast) fn check_operands( + id: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted<()> { + let operands: Vec = match &native.expression(id).kind { + ExprKind::Unary { expression, .. } => vec![*expression], + ExprKind::Binary { + left, + operator, + right, + } => { + if matches!(operator.as_str(), "==" | "!=" | "===" | "!==") { + let left_type = native_struct(*left, native, tree, dims)?; + let right_type = native_struct(*right, native, tree, dims)?; + return match (left_type, right_type) { + (None, None) => Ok(()), + (Some(left), Some(right)) if left.same_type(&right) => Ok(()), + _ => Err(unsupported(format!( + "operator `{operator}` comparing an unpacked structure with a value of another type" + ))), + }; + } + vec![*left, *right] + } + ExprKind::Concatenation(items) => items.clone(), + ExprKind::Replication { expressions, .. } => expressions.clone(), + ExprKind::Cast { expression, .. } => vec![*expression], + ExprKind::Select { expression, .. } => vec![*expression], + _ => return Ok(()), + }; + for operand in operands { + if native_struct(operand, native, tree, dims)?.is_some() { + return Err(unsupported( + "operator, select or cast applied to an unpacked structure", + )); + } + } + Ok(()) +} + +/// The leaf values of a flat value `value` of type `aggregate` when it is +/// made of one part per member (a pattern or a whole variable), with nested +/// structure members split in turn; `None` otherwise. +pub(in crate::ast) fn leaf_parts(aggregate: &UnpackedStruct, value: &Expr) -> Option> { + let Expr::Concat(parts) = value else { + return None; + }; + // A pattern has one part per member; descend into the parts of nested + // structure members, so a string leaf gets its string value. + if parts.len() == aggregate.members.len() { + let mut leaves = Vec::new(); + for (member, part) in aggregate.members.iter().zip(parts) { + match member.r#type.unpacked_struct() { + Some(inner) => match leaf_parts(inner, part) { + Some(inner_parts) => leaves.extend(inner_parts), + // A whole variable member with one leaf is that leaf. + None if inner.leaves().len() == 1 => leaves.push(part.clone()), + None => return None, + }, + None => leaves.push(part.clone()), + } + } + return Some(leaves); + } + // A whole variable is one part per leaf. + (parts.len() == aggregate.leaves().len()).then(|| parts.clone()) +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index cfce249e732..9255cac7101 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -627,6 +627,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_integral_format_string` | execute | icarus | 1 | Icarus 13.0 compiles `$sformatf` with a `bit` vector variable as the format, then `vvp` stops: "$sformatf's first argument must be a string or a register." IEEE 1800-2023 21.3.3 reads the content of an integral format expression as the format; Verilator 5.052 gives the expected output, xezim 0.11.3 prints the format as a value (`sv_integral_format_string` in the xezim review). | | `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. | | `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). | +| `sv_icarus_unpacked_structs` | compile | icarus | 8 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | +| `sv_verilator_nested_struct_default` | execute | verilator | 1 | Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 ("5 0000 1" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101. | The `string_format` cases compare `$sformatf`, `$sformat` and `$swrite` with `$display` / `$write` of the same format and arguments. The [Icarus observations](verification/sv/limitations/string-format-icarus.json) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index e05343c487d..a528e737d53 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -135,6 +135,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/packed_structs.vtest", text: include_str!("packed_structs.vtest"), }, + Group { + file: "src/sv/cases/unpacked_structs.vtest", + text: include_str!("unpacked_structs.vtest"), + }, Group { file: "src/sv/cases/procedural.vtest", text: include_str!("procedural.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest new file mode 100644 index 00000000000..507b071581e --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest @@ -0,0 +1,279 @@ +(group unpacked_structs (category types)) + +(case members_whole_copies_and_equality + (source "unpacked_struct_locals.sv" #" +module Top(output bit done); + typedef struct { int level; string name; bit [3:0] l; bit b; } row_t; + typedef struct { row_t r; string tag; } outer_t; + initial begin + row_t a, b; + outer_t o; + $display("def %0d [%s] %b %b", a.level, a.name, a.l, a.b); + a.level = 3; + a.name = "n"; + a.l = 4'b1011; + a.b = 1; + b = a; + b.name = "m"; + $display("%0d %s %b %b | %0d %s", a.level, a.name, a.l, a.b, b.level, b.name); + $display("eq %0d %0d", a == b, a != b); + b.name = "n"; + $display("eq %0d %0d len=%0d", a == b, a === b, b.name.len()); + o.r = b; + o.tag = "t"; + o.r.level++; + o.r.name = {o.r.name, o.tag}; + $display("nest %0d %s %s %0d", o.r.level, o.r.name, o.tag, o.r == a); + b = o.r; + $display("copy %0d %s", b.level, b.name); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "def 0 [] 0000 0\n3 n 1011 1 | 3 m\neq 0 1\neq 1 1 len=1\nnest 4 nt t 0\ncopy 4 nt\n")) + +(case assignment_patterns + (source "unpacked_struct_patterns.sv" #" +module Top(output bit done); + typedef struct { int level; string name; bit [3:0] l; } row_t; + typedef struct { row_t r; string tag; } outer_t; + initial begin + row_t b; + outer_t o; + b = '{level: 7, name: "pat", default: 0}; + $display("named %0d %s %b", b.level, b.name, b.l); + b = '{1, "pos", 4'b0011}; + $display("positional %0d %s %b", b.level, b.name, b.l); + b = row_t'{-2, "typed", 4'hf}; + $display("typed %0d %s %b", b.level, b.name, b.l); + o = '{r: '{default: 0, name: "z"}, tag: "q"}; + $display("nested %0d %s %b %s", o.r.level, o.r.name, o.r.l, o.tag); + o = '{r: b, tag: "w"}; + $display("member %0d %s %s", o.r.level, o.r.name, o.tag); + o = '{default: 5, tag: "d"}; + $display("default %0d %b %s", o.r.level, o.r.l, o.tag); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "named 7 pat 0000\npositional 1 pos 0011\ntyped -2 typed 1111\nnested 0 z 0000 q\nmember -2 typed w\ndefault 5 0101 d\n")) + +(case subroutine_arguments_and_results + (source "unpacked_struct_subroutines.sv" #" +module Top(output bit done); + typedef struct { int level; string name; } row_t; + function automatic string format(row_t r); + string s; + s.itoa(r.level); + return {s, ":", r.name}; + endfunction + function automatic row_t make(int level, string name); + row_t r; + r.level = level; + r.name = name; + return r; + endfunction + function automatic void bump(inout row_t r, output row_t o); + r.level++; + o = '{level: -1, name: {r.name, "!"}}; + if (r.level > 0) return; + o.level = 99; + endfunction + task automatic later(row_t r, output row_t q); + #2 q = r; + q.name = {r.name, "+"}; + endtask + initial begin + row_t a, b; + a = make(5, "five"); + $display("%s %s", format(a), format('{1, "one"})); + bump(a, b); + $display("%s %s", format(a), format(b)); + b = a.level > 5 ? a : b; + $display("%s %0d %0d", format(b), make(2, "x") == make(2, "x"), make(2, "x") == make(2, "y")); + later(a, b); + $display("%0d %s", $time, format(b)); + done = 1; + end +endmodule +"#) + (top Top) (run_until 2) (assert_eq done 1) + (expect_output "5:five 1:one\n6:five -1:five!\n6:five 1 0\n2 6:five+\n")) + +(case initializers_results_and_defaults + (source "unpacked_struct_initializers.sv" #" +module Top(output bit done); + typedef struct { int a; string s; } row_t; + typedef struct { int a; bit [3:0] b; } int_t; + row_t g = '{1, "g"}; + function automatic row_t make(); + make = '{2, "m"}; + endfunction + function automatic row_t make_members(); + make_members.a = 3; + make_members.s = "n"; + endfunction + function automatic row_t bump(inout row_t r); + r.a++; + return r; + endfunction + function automatic row_t twice(inout row_t r); + return bump(r); + endfunction + function automatic int f(row_t r = '{default: 0, s: "d"}); + return r.a + r.s.len(); + endfunction + initial begin + row_t x, y; + $display("g %0d %s", g.a, g.s); + x = make(); + y = make_members(); + $display("make %0d %s %0d %s", x.a, x.s, y.a, y.s); + y = twice(x); + $display("twice %0d %0d", x.a, y.a); + $display("default %0d %0d", f(), f(x)); + repeat (2) begin + static int_t r = '{0, 5}; + $display("static %0d %0d", r.a, r.b); + r.a++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "g 1 g\nmake 2 m 3 n\ntwice 3 3\ndefault 1 4\nstatic 0 5\nstatic 1 5\n")) + +(case results_and_outputs + (source "unpacked_struct_results.sv" #" +module Top(output bit done); + typedef struct { int a; } row_t; + typedef struct { string s; } str_t; + typedef struct { int x, y; } inner_t; + typedef struct { inner_t i; } outer_t; + function automatic row_t make(bit set); + if (set) make.a = 7; + endfunction + function automatic void outs(output str_t r); + r.s = "abc"; + endfunction + function automatic void outz(output row_t r); + if (0) r.a = 1; + endfunction + initial begin + row_t r; + str_t s; + r = make(1); + r = make(0); + $display("make %0d", r.a); + outs(s); + $display("outs %s", s.s); + r.a = 5; + outz(r); + $display("outz %0d", r.a); + repeat (2) begin + static outer_t o = '{'{1, 2}}; + $display("static %0d %0d", o.i.x, o.i.y); + o.i.x++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "make 0\nouts abc\noutz 0\nstatic 1 2\nstatic 2 2\n")) + +(case module_variables + (source "unpacked_struct_module.sv" #" +module Top(input bit clk, input bit [7:0] a, input bit [3:0] b, + output bit [7:0] next_a, output bit [3:0] next_b, + output bit [7:0] stored_a, output bit [3:0] stored_b, output bit same); + typedef struct { bit [7:0] a; bit [3:0] b; } pair_t; + pair_t p, q, c, r; + assign p = '{a: a, b: b}; + always_comb begin + q = p; + q.b = p.b + 1; + end + assign c = '{a: q.a + 1, b: q.b}; + always_ff @(posedge clk) begin + r <= c; + r.b <= c.b ^ 4'hf; + end + assign next_a = c.a; + assign next_b = c.b; + assign stored_a = r.a; + assign stored_b = r.b; + assign same = p == q; +endmodule +"#) + (top Top) + (for (x y) (list (0x10 3) (0xfe 15)) + (modify (set a x) (set b y)) + (assert_eq next_a (& (+ x 1) 0xff)) + (assert_eq next_b (& (+ y 1) 15)) + (assert_eq same 0) + (tick clk) + (assert_eq stored_a (& (+ x 1) 0xff)) + (assert_eq stored_b (^ (& (+ y 1) 15) 15)))) + +(case handle_members_survive_heap_collections + (source "unpacked_struct_handles.sv" #" +module Top(output int n); + class Node; + string text; + function new(string text); + this.text = text; + endfunction + function string get(); + return text; + endfunction + endclass + typedef struct { Node m_type; string m_type_name; } pair_t; + logic clk = 0; + always #1 clk = ~clk; + pair_t kept, last; + Node node; + string number; + initial begin + kept.m_type = new("kept"); + kept.m_type_name = {"na", "me"}; + end + always @(posedge clk) begin + number.itoa(n); + node = new(number); + last = '{m_type: node, m_type_name: {number, "!"}}; + node = null; + n = n + 1; + end + initial #6000 $display("[%s] [%s] [%s] [%s] %0d %0d", kept.m_type.get(), kept.m_type_name, + last.m_type.text, last.m_type_name, kept.m_type != null, n); +endmodule +"#) + (top Top) + (run_until 6000) + (expect_output "[kept] [name] [2999] [2999!] 1 3000\n")) + +(case four_state_members + (four_state) + (source "unpacked_struct_four_state.sv" #" +module Top(output bit done); + typedef struct { time t; logic [3:0] l; int i; bit [1:0] b; } access_t; + access_t a, b; + initial begin + $display("def %0d %b %0d %b", a.t, a.l, a.i, a.b); + a.l = 4'b1z0x; + b = a; + $display("copy %b %0d %0d", b.l, a == b, a === b); + b = '{t: 5, l: 4'bxx11, i: 'x, b: 2'bx1}; + $display("pattern %0d %b %0d %b", b.t, b.l, b.i, b.b); + b = '{default: 0}; + $display("default %0d %b %0d %b", b.t, b.l, b.i, b.b); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "def x xxxx 0 00\ncopy 1z0x x 1\npattern 5 xx11 0 01\ndefault 0 0000 0 00\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_icarus_unpacked_structs.sv b/crates/celox-test-suite/verification/repros/sv_icarus_unpacked_structs.sv new file mode 100644 index 00000000000..d45870ee5ed --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_icarus_unpacked_structs.sv @@ -0,0 +1 @@ +module top; typedef struct { int a; } s_t; s_t s; initial begin s.a = 1; $display("%0d", s.a); end endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_verilator_nested_struct_default.sv b/crates/celox-test-suite/verification/repros/sv_verilator_nested_struct_default.sv new file mode 100644 index 00000000000..f8e142aee0f --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_verilator_nested_struct_default.sv @@ -0,0 +1,9 @@ +module top; + typedef struct { int level; bit [3:0] l; } row_t; + typedef struct { row_t r; int tag; } outer_t; + outer_t o; + initial begin + o = '{default: 5, tag: 1}; + $display("%0d %b %0d", o.r.level, o.r.l, o.tag); + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_xezim_constructor_argument_in_always.sv b/crates/celox-test-suite/verification/repros/sv_xezim_constructor_argument_in_always.sv new file mode 100644 index 00000000000..e9725d4f2b1 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_xezim_constructor_argument_in_always.sv @@ -0,0 +1,26 @@ +// xezim 0.11.3: an object constructed with `new(s)` in an always procedure +// keeps an empty string property; IEEE 1800-2023 8.7 runs the constructor. +// Expected: "[2] 3". +module top; + class Node; + string text; + function new(string t); + text = t; + endfunction + endclass + Node node, keep; + string number; + int n; + logic clk = 0; + always #1 clk = ~clk; + always @(posedge clk) begin + number.itoa(n); + node = new(number); + keep = node; + n = n + 1; + end + initial begin + #6 $display("[%s] %0d", keep.text, n); + $finish; + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_xezim_struct_default_argument.sv b/crates/celox-test-suite/verification/repros/sv_xezim_struct_default_argument.sv new file mode 100644 index 00000000000..495303a1b41 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_xezim_struct_default_argument.sv @@ -0,0 +1,14 @@ +// xezim 0.11.3: a structure assignment pattern as the default of a +// subroutine argument loses its named members (IEEE 1800-2023 13.5.3, +// 10.9.2). Expected: "1 d". +module top; + typedef struct { int a; string s; } row_t; + function automatic int f(row_t r = '{default: 0, s: "d"}); + $write("%0d ", r.s.len()); + return r.a; + endfunction + initial begin + void'(f()); + begin row_t r; r = '{default: 0, s: "d"}; $display("%s", r.s); end + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_xezim_struct_output_default.sv b/crates/celox-test-suite/verification/repros/sv_xezim_struct_output_default.sv new file mode 100644 index 00000000000..4d449b16053 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_xezim_struct_output_default.sv @@ -0,0 +1,16 @@ +// xezim 0.11.3: an automatic output argument of unpacked structure type that +// the function does not write is copied out as X for a 2-state member; IEEE +// 1800-2023 13.5.2 and 6.8 give the formal its type's default, 0. +// Expected: "0". +module top; + typedef struct { int a; } row_t; + function automatic void outz(output row_t r); + if (0) r.a = 1; + endfunction + initial begin + row_t r; + r.a = 5; + outz(r); + $display("%0d", r.a); + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_xezim_unpacked_structs.sv b/crates/celox-test-suite/verification/repros/sv_xezim_unpacked_structs.sv new file mode 100644 index 00000000000..3bea89716ce --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_xezim_unpacked_structs.sv @@ -0,0 +1,26 @@ +// xezim 0.11.3 reproductions of the unpacked-structure defects retained for +// the unpacked_structs cases (IEEE 1800-2023 7.2, 10.9.2, 11.4.11). +// Expected: "cond 6 a", "member 6 a w", "p 10 3 q 10 4". +module top; + typedef struct { int level; string name; } row_t; + typedef struct { row_t r; string tag; } outer_t; + typedef struct { bit [7:0] a; bit [3:0] b; } pair_t; + row_t a, b; + outer_t o; + pair_t p, q; + bit [7:0] x = 8'h10; + assign p = '{a: x, b: 4'h3}; + always_comb begin + q = p; + q.b = p.b + 1; + end + initial begin + a = '{6, "a"}; + b = '{1, "b"}; + b = a.level > 5 ? a : b; + $display("cond %0d %s", b.level, b.name); + o = '{r: a, tag: "w"}; + $display("member %0d %s %s", o.r.level, o.r.name, o.tag); + #1 $display("p %h %h q %h %h", p.a, p.b, q.a, q.b); + end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index fe9e438501d..c10f9fe0aeb 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -27,7 +27,8 @@ "icarus/tagged_unions.json", "icarus/timing.json", "icarus/types.json", - "icarus/unions.json" + "icarus/unions.json", + "icarus/unpacked_structs.json" ], "exclude_stronger_than_sv": false, "include_ignored": false, diff --git a/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json new file mode 100644 index 00000000000..6b919f07e53 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json @@ -0,0 +1,188 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::assignment_patterns", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::four_state_members", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::handle_members_survive_heap_collections", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::initializers_results_and_defaults", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::members_whole_copies_and_equality", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::module_variables", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::results_and_outputs", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::subroutine_arguments_and_results", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 28a1966ca95..9f1345b58d9 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2969,5 +2969,46 @@ "string_format::sformatf_with_associative_index" ] } + }, + { + "id": "sv_icarus_unpacked_structs", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [], + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "unpacked_structs::assignment_patterns", + "unpacked_structs::four_state_members", + "unpacked_structs::handle_members_survive_heap_collections", + "unpacked_structs::initializers_results_and_defaults", + "unpacked_structs::members_whole_copies_and_equality", + "unpacked_structs::module_variables", + "unpacked_structs::results_and_outputs", + "unpacked_structs::subroutine_arguments_and_results" + ] + } + }, + { + "id": "sv_verilator_nested_struct_default", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 (\"5 0000 1\" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101.", + "upstream": [], + "evidence": [ + "verification/repros/sv_verilator_nested_struct_default.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "unpacked_structs::assignment_patterns" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index 182e769d1f0..2e2c18d9260 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -27,7 +27,8 @@ "verilator/system_functions.json", "verilator/tagged_unions.json", "verilator/timing.json", - "verilator/types.json" + "verilator/types.json", + "verilator/unpacked_structs.json" ], "exclude_stronger_than_sv": false, "include_ignored": false, diff --git a/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json new file mode 100644 index 00000000000..1344517bc8f --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json @@ -0,0 +1,104 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 (\"5 0000 1\" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_verilator_nested_struct_default.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_nested_struct_default", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 (\"5 0000 1\" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101.", + "upstream": [] + }, + "name": "unpacked_structs::assignment_patterns", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "unpacked_structs::four_state_members", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::handle_members_survive_heap_collections", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::initializers_results_and_defaults", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::members_whole_copies_and_equality", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::module_variables", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::results_and_outputs", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::subroutine_arguments_and_results", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/xezim.json b/crates/celox-test-suite/verification/sv/xezim.json index 1d89248a43f..ff2b063c499 100644 --- a/crates/celox-test-suite/verification/sv/xezim.json +++ b/crates/celox-test-suite/verification/sv/xezim.json @@ -36,7 +36,8 @@ "xezim/tagged_unions.json", "xezim/timing.json", "xezim/types.json", - "xezim/unions.json" + "xezim/unions.json", + "xezim/unpacked_structs.json" ], "exclude_stronger_than_sv": false, "include_ignored": false, diff --git a/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json new file mode 100644 index 00000000000..736d7342928 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json @@ -0,0 +1,92 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "unpacked_structs::assignment_patterns at 61:3: expect_output: expected [110, 97, 109, 101, 100, 32, 55, 32, 112, 97, 116, 32, 48, 48, 48, 48, 10, 112, 111, 115, 105, 116, 105, 111, 110, 97, 108, 32, 49, 32, 112, 111, 115, 32, 48, 48, 49, 49, 10, 116, 121, 112, 101, 100, 32, 45, 50, 32, 116, 121, 112, 101, 100, 32, 49, 49, 49, 49, 10, 110, 101, 115, 116, 101, 100, 32, 48, 32, 122, 32, 48, 48, 48, 48, 32, 113, 10, 109, 101, 109, 98, 101, 114, 32, 45, 50, 32, 116, 121, 112, 101, 100, 32, 119, 10, 100, 101, 102, 97, 117, 108, 116, 32, 53, 32, 48, 49, 48, 49, 32, 100, 10], got [110, 97, 109, 101, 100, 32, 55, 32, 112, 97, 116, 32, 48, 48, 48, 48, 10, 112, 111, 115, 105, 116, 105, 111, 110, 97, 108, 32, 49, 32, 112, 111, 115, 32, 48, 48, 49, 49, 10, 116, 121, 112, 101, 100, 32, 45, 50, 32, 116, 121, 112, 101, 100, 32, 49, 49, 49, 49, 10, 110, 101, 115, 116, 101, 100, 32, 48, 32, 122, 32, 48, 48, 48, 48, 32, 113, 10, 109, 101, 109, 98, 101, 114, 32, 48, 32, 32, 119, 10, 100, 101, 102, 97, 117, 108, 116, 32, 53, 32, 48, 49, 48, 49, 32, 100, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::assignment_patterns", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::four_state_members", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::handle_members_survive_heap_collections at 257:3: expect_output: expected [91, 107, 101, 112, 116, 93, 32, 91, 110, 97, 109, 101, 93, 32, 91, 50, 57, 57, 57, 93, 32, 91, 50, 57, 57, 57, 33, 93, 32, 49, 32, 51, 48, 48, 48, 10], got [91, 107, 101, 112, 116, 93, 32, 91, 110, 97, 109, 101, 93, 32, 91, 32, 93, 32, 91, 50, 57, 57, 57, 33, 93, 32, 49, 32, 51, 48, 48, 48, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::handle_members_survive_heap_collections", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::initializers_results_and_defaults at 147:3: expect_output: expected [103, 32, 49, 32, 103, 10, 109, 97, 107, 101, 32, 50, 32, 109, 32, 51, 32, 110, 10, 116, 119, 105, 99, 101, 32, 51, 32, 51, 10, 100, 101, 102, 97, 117, 108, 116, 32, 49, 32, 52, 10, 115, 116, 97, 116, 105, 99, 32, 48, 32, 53, 10, 115, 116, 97, 116, 105, 99, 32, 49, 32, 53, 10], got [103, 32, 49, 32, 103, 10, 109, 97, 107, 101, 32, 50, 32, 109, 32, 51, 32, 110, 10, 116, 119, 105, 99, 101, 32, 51, 32, 51, 10, 100, 101, 102, 97, 117, 108, 116, 32, 48, 32, 52, 10, 115, 116, 97, 116, 105, 99, 32, 48, 32, 53, 10, 115, 116, 97, 116, 105, 99, 32, 49, 32, 53, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::initializers_results_and_defaults", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::members_whole_copies_and_equality", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::module_variables at 215:5: assert_eq next_a: expected 0x11, got 0x0", + "expectation": "Simulation", + "name": "unpacked_structs::module_variables", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::results_and_outputs at 186:3: expect_output: expected [109, 97, 107, 101, 32, 48, 10, 111, 117, 116, 115, 32, 97, 98, 99, 10, 111, 117, 116, 122, 32, 48, 10, 115, 116, 97, 116, 105, 99, 32, 49, 32, 50, 10, 115, 116, 97, 116, 105, 99, 32, 50, 32, 50, 10], got [109, 97, 107, 101, 32, 48, 10, 111, 117, 116, 115, 32, 97, 98, 99, 10, 111, 117, 116, 122, 32, 120, 10, 115, 116, 97, 116, 105, 99, 32, 49, 32, 50, 10, 115, 116, 97, 116, 105, 99, 32, 50, 32, 50, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::results_and_outputs", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::subroutine_arguments_and_results at 103:3: expect_output: expected [53, 58, 102, 105, 118, 101, 32, 49, 58, 111, 110, 101, 10, 54, 58, 102, 105, 118, 101, 32, 45, 49, 58, 102, 105, 118, 101, 33, 10, 54, 58, 102, 105, 118, 101, 32, 49, 32, 48, 10, 50, 32, 54, 58, 102, 105, 118, 101, 43, 10], got [53, 58, 102, 105, 118, 101, 32, 49, 58, 111, 110, 101, 10, 54, 58, 102, 105, 118, 101, 32, 45, 49, 58, 102, 105, 118, 101, 33, 10, 45, 49, 58, 102, 105, 118, 101, 33, 32, 49, 32, 48, 10, 50, 32, 54, 58, 102, 105, 118, 101, 43, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::subroutine_arguments_and_results", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index b0873058275..a22d1b0a5ce 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -762,6 +762,30 @@ "sv_associative_index_cast": { "title": "An associative index is evaluated at its own width instead of as a cast to the index type", "standard": "IEEE 1800-2023 7.8.4, 6.24.1" + }, + "sv_rest-X80": { + "title": "A conditional operator whose operands are unpacked structures yields the false operand", + "standard": "IEEE 1800-2023 11.4.11, 7.2" + }, + "sv_rest-X81": { + "title": "A structure assignment pattern item that is an unpacked structure value sets the member to its default", + "standard": "IEEE 1800-2023 10.9.2" + }, + "sv_rest-X82": { + "title": "A whole unpacked-structure assignment in always_comb leaves the target members at their defaults", + "standard": "IEEE 1800-2023 7.2, 9.2.2.2" + }, + "sv_rest-X83": { + "title": "An object constructed with `new(s)` in an always procedure keeps an empty string property", + "standard": "IEEE 1800-2023 8.7, 9.2.2.1" + }, + "sv_rest-X85": { + "title": "A structure assignment pattern as the default of a subroutine argument loses its named members", + "standard": "IEEE 1800-2023 13.5.3, 10.9.2" + }, + "sv_rest-X88": { + "title": "An automatic output argument of unpacked structure type that is not written is copied out as X for a 2-state member", + "standard": "IEEE 1800-2023 13.5.2, 6.8" } }, "cases": [ @@ -4547,6 +4571,54 @@ "classification": "xezim_bug", "bug": "sv_associative_index_cast", "note": "With int unsigned x = 32'hffffffff and string wide[bit [63:0]], wide[x + 32'd1] = ... stores key 0 in xezim 0.11.3 (prints 0 1); 7.8.4 evaluates the index as a cast to bit [63:0], so the key is 64'h100000000 (expected 1 0). See verification/repros/sv_associative_index_cast.json." + }, + { + "suite": "sv", + "name": "unpacked_structs::assignment_patterns", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X81", + "note": "o = '{r: b, tag: \"w\"} with a row_t variable b prints \"member 0 w\": xezim stores the default for the structure-valued member instead of b's members (-2, \"typed\"). Reproduced by verification/repros/sv_xezim_unpacked_structs.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::subroutine_arguments_and_results", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X80", + "note": "b = a.level > 5 ? a : b with a.level = 6 keeps b (\"-1:five!\") instead of copying a (\"6:five\"). Reproduced by verification/repros/sv_xezim_unpacked_structs.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::module_variables", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X82", + "note": "always_comb begin q = p; q.b = p.b + 1; end leaves q.a = 0, so c.a = q.a + 1 and next_a read 0 instead of a + 1 (0x11). Reproduced by verification/repros/sv_xezim_unpacked_structs.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::handle_members_survive_heap_collections", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X83", + "note": "node = new(number) in always @(posedge clk) gives an object whose text property is empty, so last.m_type.text prints \"[ ]\" instead of \"[2999]\"; the same happens without the structure. Reproduced by verification/repros/sv_xezim_constructor_argument_in_always.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::initializers_results_and_defaults", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X85", + "note": "f() with the default '{default: 0, s: \"d\"} sees an empty s and returns 0 instead of 1; the same pattern assigned to a variable keeps s. Reproduced by verification/repros/sv_xezim_struct_default_argument.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::results_and_outputs", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X88", + "note": "outz(r) does not write its output formal, so r.a must become the int default 0; xezim prints \"outz x\". Reproduced by verification/repros/sv_xezim_struct_output_default.sv." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs new file mode 100644 index 00000000000..95f1c6b75cb --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs @@ -0,0 +1,207 @@ +//! Unpacked structures (IEEE 1800-2023 7.2). + +use super::*; + +sv_backends! { + fn unpacked_struct_members_whole_copies_and_equality(sim) { + @case "unpacked_structs::members_whole_copies_and_equality"; + } + fn unpacked_struct_assignment_patterns(sim) { + @case "unpacked_structs::assignment_patterns"; + } + fn unpacked_struct_subroutine_arguments_and_results(sim) { + @case "unpacked_structs::subroutine_arguments_and_results"; + } + fn unpacked_struct_initializers_results_and_defaults(sim) { + @case "unpacked_structs::initializers_results_and_defaults"; + } + fn unpacked_struct_results_and_outputs(sim) { + @case "unpacked_structs::results_and_outputs"; + } + + fn constructors_in_structure_patterns(sim) { + @setup { + let source = r#"module Top(output bit ok); + class Node; + string n; + function new(); + n = "made"; + endfunction + endclass + typedef struct { Node n; int k; } handle_t; + initial begin + handle_t h; + h = '{n: new(), k: 1}; + ok = h.n.n == "made" && h.k == 1; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + } + fn static_task_structure_arguments_are_shared(sim) { + @setup { + let source = r#"`timescale 1ns/1ns + module Top(output int first, output int second); + typedef struct { int a; string s; } row_t; + task show(input row_t r, output int seen); + #2 seen = r.a * 10 + r.s.len(); + endtask + initial show('{1, "x"}, first); + initial #1 show('{2, "yy"}, second); + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(4).unwrap(); + let (first, second) = (sim.signal("first"), sim.signal("second")); + assert_eq!(sim.get(first), BigUint::from(22u8)); + assert_eq!(sim.get(second), BigUint::from(22u8)); + } + fn static_nested_string_initializers(sim) { + @setup { + let source = r#"module Top(output int n); + typedef struct { string s; } in_t; + typedef struct { in_t i; } out_t; + initial repeat (2) begin + static out_t o = '{'{"abc"}}; + n = n * 10 + o.i.s.len(); + o.i.s = {o.i.s, "d"}; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let n = sim.signal("n"); + assert_eq!(sim.get(n), BigUint::from(34u8)); + } + fn explicit_static_structures_of_repeating_processes(sim) { + @setup { + let source = r#"`timescale 1ns/1ns + module Top(output int out); + typedef struct { int a; string s; } row_t; + int source = 5; + logic clk = 0; + always #1 clk = ~clk; + always @(posedge clk) begin + static row_t r = '{a: source, s: "x"}; + r.a++; + out = r.a * 10 + r.s.len(); + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(4).unwrap(); + let out = sim.signal("out"); + assert_eq!(sim.get(out), BigUint::from(71u8)); + } + fn unpacked_struct_module_variables(sim) { + @case "unpacked_structs::module_variables"; + } + fn unpacked_struct_handle_members_survive_heap_collections(sim) { + @case "unpacked_structs::handle_members_survive_heap_collections"; + } + fn unpacked_struct_four_state_members(sim) { + @case "unpacked_structs::four_state_members"; + } +} + +#[test] +fn unsupported_and_illegal_uses_are_rejected() { + let types = "typedef struct { int a; bit b; } i_t; typedef struct { int a; string s; } s_t;"; + for (body, want) in [ + ("i_t v; initial v = 5;", "not of its type"), + ("i_t v; int x; initial x = v;", "not of its type"), + ( + "function int f(int x); return x; endfunction i_t v; initial $display(\"%0d\", f(v));", + "not of its type", + ), + ( + "typedef struct { int a; bit b; } j_t; typedef struct { i_t m; } o_t; o_t o; initial o = '{m: j_t'{1, 0}};", + "not of its type", + ), + ("i_t v; s_t w; initial v = w;", "not of its type"), + ( + "class A; endclass class B; endclass typedef struct { A node; } r_t; r_t r; B b; initial r = '{node: b};", + "assignment pattern member", + ), + ( + "typedef struct { int a; bit b; } j_t; i_t v; initial v = j_t'{1, 0};", + "not of its type", + ), + ( + "typedef struct { int a; bit b; } j_t; function int f(i_t r); return r.a; endfunction j_t w; initial $display(\"%0d\", f(w));", + "not of its type", + ), + ( + "function int f(i_t r); return r.a; endfunction initial $display(\"%0d\", f(5));", + "not of its type", + ), + ("function i_t f(); return 5; endfunction", "not of its type"), + ( + "i_t v; int x; initial x = v + 1;", + "applied to an unpacked structure", + ), + ( + "i_t v; initial $display(\"%0d\", v[3]);", + "applied to an unpacked structure", + ), + ( + "i_t v; s_t w; bit x; initial x = v == w;", + "comparing an unpacked structure", + ), + ( + "i_t v; initial v = '{1, 2, 3};", + "3 items for 2 structure members", + ), + ("i_t v; initial v.nope = 1;", "structure member `v.nope`"), + ( + "i_t v; initial v += v;", + "operator `+=` on an unpacked structure", + ), + ( + "parameter i_t P = '{1, 0};", + "parameter of unpacked structure type", + ), + ("i_t q[$];", "dynamic container of unpacked structures"), + ( + "class C; i_t v; endclass", + "class property of unpacked structure type", + ), + ( + "function automatic void f(ref i_t r); r.a++; endfunction i_t v; initial f(v);", + "ref argument of `f` of unpacked structure type", + ), + ("i_t v[2];", "array of unpacked structures"), + ( + "typedef struct packed { i_t x; } p_t; p_t v;", + "unsupported packed struct member", + ), + ( + "typedef union { int a; bit b; } u_t; u_t u;", + "unpacked struct, union", + ), + ( + "function i_t g(); return '{1, 0}; endfunction function void f(); static i_t v = g(); endfunction", + "initializer of a static variable of unpacked structure type", + ), + ] { + let source = format!("module Top; {types} {body} endmodule"); + let Err(error) = Simulator::from_sv_sources(vec![(&source, Path::new("struct.sv"))], "Top") + .build_cranelift() + else { + panic!("`{body}` must be rejected"); + }; + let error = error.to_string(); + assert!(error.contains(want), "`{body}`: {error}"); + } + let source = "module Top(output i_t o); typedef struct { int a; } i_t; endmodule"; + let Err(error) = + Simulator::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top").build_cranelift() + else { + panic!("an unpacked structure port is unsupported"); + }; + let error = error.to_string(); + assert!(error.contains("port of unpacked structure type"), "{error}"); +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index e9875cc9f8c..3063e01184a 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -261,3 +261,5 @@ mod containers; #[path = "frontends/systemverilog/concurrent_assertions.rs"] mod concurrent_assertions; +#[path = "frontends/systemverilog/unpacked_structs.rs"] +mod unpacked_structs; diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index f0d706c6d46..f911290ad0d 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -27,10 +27,10 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs, hard and soft packed untagged unions, enums (with implicit values) and their methods `first`, `last`, `next`, `prev`, `num` and `name` on any enum-typed expression except an element of a packed array of enums ([#2417](https://github.com/celox-sim/celox/issues/2417)), `typedef`, unpacked arrays used as memories, signed and unsigned | +| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs, unpacked structs (see [unpacked structures](#unpacked-structures)), hard and soft packed untagged unions, enums (with implicit values) and their methods `first`, `last`, `next`, `prev`, `num` and `name` on any enum-typed expression except an element of a packed array of enums ([#2417](https://github.com/celox-sim/celox/issues/2417)), `typedef`, unpacked arrays used as memories, signed and unsigned | | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | -| Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | +| Patterns | assignment patterns for packed and unpacked 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; text formatted by `$sformatf` / `$sformat` / `$swrite`. See [strings](#strings) | | Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types up to 64 bits (4-state properties start as X and keep X/Z 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) | @@ -325,6 +325,19 @@ Every construct above is covered by tests that compare the result with a software model. The shared Veryl conformance suite also runs against the SystemVerilog emitted by Veryl. +### Unpacked structures {#unpacked-structures} + +Unpacked structures (IEEE 1800-2023 7.2) may have integral, enumeration, +`string`, class handle, packed structure and nested unpacked structure +members, each keeping its own 2-state or 4-state type. Variables of such a +type may be module variables, procedural locals, and subroutine arguments of +any direction and results. Members are read and written like variables of +their type; a whole structure is assigned and compared with `==`, `!=`, +`===` and `!==` against a value of the same type, chosen with `?:`, or built +from an assignment pattern (`'{a, b}`, `'{m: v, default: d}`, `T'{...}`, with +`default` applied to the members of nested structures). Other operators, +selects and casts of a whole structure are rejected. + ## Unsupported constructs {#what-is-not-supported} Celox reports an `Unsupported` error naming the construct instead of ignoring @@ -348,7 +361,9 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: `bind`. - Declarations: variable declaration initializers of members of an interface array, ANSI port default values, tagged unions, unpacked unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), - unpacked structs and `real`. + `real`, and unpacked structs as ports, nets, parameters, class properties, + array or container elements, or with members that are arrays, `real`, or + have default values. - Sequential processes: `iff` qualifiers in `always_ff` event lists ([#452](https://github.com/celox-sim/celox/issues/452)), and in `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit edge signals, and several edges without an asynchronous reset. diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 1c8b140baac..e3c47109148 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -100,7 +100,7 @@ Common reasons a design needs changes are: and `iff` in `always_ff` event controls ([#452](https://github.com/celox-sim/celox/issues/452)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. - Non-ANSI module ports, wildcard `.*` connections, gate primitives and `bind`. -- `real`, unpacked structs and several interface features. +- `real`, unpacked structs in ports, class properties and containers, and several interface features. The [complete limitations list](./systemverilog-reference#what-is-not-supported) includes narrower restrictions and tracking issues. Unsupported constructs diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 2673da9aaa5..7dbd8f3ead8 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -25,11 +25,11 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard / soft packed untagged union、enum(暗黙値を含む)と enum 型の任意の式(enum の packed 配列の要素を除く、[#2417](https://github.com/celox-sim/celox/issues/2417))に対するメソッド `first`・`last`・`next`・`prev`・`num`・`name`、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | +| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、unpacked 構造体([unpacked 構造体](#unpacked-structures)を参照)、hard / soft packed untagged union、enum(暗黙値を含む)と enum 型の任意の式(enum の packed 配列の要素を除く、[#2417](https://github.com/celox-sim/celox/issues/2417))に対するメソッド `first`・`last`・`next`・`prev`・`num`・`name`、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | -| パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| クラス | モジュール・package・コンパイル単位で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)。[クラス](#classes)を参照 | +| パターン | packed・unpacked 構造体、packed 配列、unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | +| クラス | モジュール・package・コンパイル単位で宣言したクラス。64 ビット以下の 2 値・4 値整数型(4 値のプロパティは X で始まり、X/Z ビットを保持します)・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -204,13 +204,24 @@ seedを使って解を探索し、成功時だけ対象プロパティをまと 上記の各構文は、ソフトウェアモデルと結果を比較するテストで確認しています。Veryl が出力する SystemVerilog に対しても、共有の Veryl 適合性スイートを実行しています。 +### unpacked 構造体 {#unpacked-structures} + +unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列挙型、`string`、 +クラスハンドル、packed 構造体、入れ子の unpacked 構造体を使え、各メンバは自身の +2 値・4 値の型を保ちます。この型の変数は、モジュール変数、手続き内のローカル変数、 +任意の方向のサブルーチン引数と戻り値にできます。メンバはその型の変数と同じように +読み書きできます。構造体全体は、同じ型の値との代入と `==`・`!=`・`===`・`!==` による +比較、`?:` による選択、assignment pattern(`'{a, b}`、`'{m: v, default: d}`、 +`T'{...}`。`default` は入れ子の構造体のメンバにも適用)による構築ができます。 +構造体全体へのその他の演算子、選択、キャストは拒否されます。 + ## 未対応の構文 {#what-is-not-supported} 未対応の構文は、無視せずに、その構文名を示す `Unsupported` エラーを返します。エラーには その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package のクラスをモジュール内クラス型で特殊化する機能、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package のクラスをモジュール内クラス型で特殊化する機能、`real`・配列・64 ビットを超えるプロパティ、4 値プロパティの乱数化と制約。時間待ちを含む task の static ローカル宣言、再帰呼び出し。 - `inout` / `ref` / 式を使う modport、virtual interface など。 ANSI ヘッダーのポートは、クロック入力やパラメータ依存の幅も含めて modport 経由で渡せます。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 @@ -225,7 +236,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート式(`module m({a, b}, c[3:0], .p(d))` など、[#1953](https://github.com/celox-sim/celox/issues/1953))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、`real`、ポート・ネット・パラメータ・クラスプロパティ・配列やコンテナの要素としての unpacked 構造体、配列・`real`・既定値を持つメンバ。 - 順序回路のプロセス:`always_ff` のイベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 非同期リセットを持たない複数のエッジ。 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index cb659051037..401048927ff 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -94,7 +94,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 `always_ff` のイベント制御の `iff`([#452](https://github.com/celox-sim/celox/issues/452))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。 - 非 ANSI モジュールポート、ワイルドカード `.*` 接続、ゲートプリミティブ、`bind`。 -- `real`、unpacked 構造体、interface の一部の機能。 +- `real`、ポート・クラスプロパティ・コンテナの unpacked 構造体、interface の一部の機能。 [制約の一覧](./systemverilog-reference#what-is-not-supported)に、より細かな条件と追跡 issue をまとめています。 未対応の構文は、構文名と追跡 issue を含む診断を返します。 From 23214db48279c86a7e292f9aa84d67f23637777c Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 17:30:26 +0900 Subject: [PATCH 2/5] feat(sv): support class properties of unpacked structure type A class property of an unpacked structure type was rejected. Its leaf members are now laid out as ordinary properties named by their member path (`orig.m_type`), so a `string` or class handle member is a handle property the collector traces, and a 4-state member keeps its X/Z bits. The class records the property and its structure-typed members (`Class::aggregates`) for lookup and hiding. `h.p.m` and an unqualified `p.m` inside a method resolve through the member path to the leaf property, including `h.p.m.q` through a handle member. A whole property `h.p` reads as the concatenation of its leaf loads; assigning it, from a pattern, a variable, another property, a conditional or a call, stores each leaf, evaluating the value once. Declaration initializers run in the constructor in declaration order, and a shallow copy copies the members. Methods returning a structure are now recognised when checking an assignment's type. Static, `rand` and `const` properties of an unpacked structure type stay unsupported with dedicated diagnostics. Icarus 13.0 still lacks unpacked structures; xezim 0.11.3 formats string members of such properties as packed values, which the review retains. Change-Id: I8d7ebe18fdf58ac33c7b1f2f76b7e27bf598b542 --- crates/celox-sv-analyzer/src/ast/classes.rs | 109 +++++++++- .../src/ast/expression_binding.rs | 10 +- .../src/ast/expression_binding/direct.rs | 20 ++ .../src/ast/expression_binding/objects.rs | 203 +++++++++++++++--- crates/celox-sv-analyzer/src/ast/inlining.rs | 88 ++++++++ .../celox-sv-analyzer/src/ast/procedural.rs | 175 ++++++++++++++- .../src/ast/unpacked_structs.rs | 23 +- crates/celox-test-suite/LIMITATIONS.md | 2 +- .../src/sv/cases/unpacked_structs.vtest | 172 +++++++++++++++ .../sv_xezim_unpacked_struct_properties.sv | 23 ++ .../sv/icarus/unpacked_structs.json | 92 ++++++++ .../verification/sv/limitations.json | 4 + .../sv/verilator/unpacked_structs.json | 44 ++++ .../sv/xezim/unpacked_structs.json | 44 ++++ .../verification/xezim-review.json | 32 +++ .../systemverilog/unpacked_structs.rs | 132 +++++++++++- docs/guide/systemverilog-reference.md | 14 +- docs/guide/systemverilog.md | 2 +- docs/ja/guide/systemverilog-reference.md | 8 +- docs/ja/guide/systemverilog.md | 2 +- 20 files changed, 1133 insertions(+), 66 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_xezim_unpacked_struct_properties.sv diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index fd0d179b66b..a7bdf10cb3c 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -58,6 +58,22 @@ impl Property { } } +/// A property of unpacked structure type, or a member of one that is itself +/// an unpacked structure. It is not laid out: its leaf members are +/// properties named by their member path (see `unpacked_structs`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct AggregateProperty { + pub name: String, + pub owner: String, + pub local: bool, + pub protected: bool, + pub r#type: Type, + pub initializer: Option, + /// How many properties precede it: a later declaration of the same + /// name hides an earlier one. + pub position: usize, +} + /// A static property of a class: one variable of the module that declares /// the class, shared by all of its objects (IEEE 1800-2023 8.9). #[derive(Debug, Clone, PartialEq, Eq)] @@ -123,6 +139,8 @@ pub(super) struct Class { pub properties: Vec, /// How many of `properties` the bases declare. pub base_properties: usize, + /// Properties of unpacked structure type of the class and its bases. + pub aggregates: Vec, /// Static properties of the class and its bases. pub statics: Vec, /// Methods visible in the class, overrides replacing inherited ones. @@ -195,10 +213,42 @@ impl Class { /// The property `name`; one the class declares hides one of a base /// (IEEE 1800-2023 8.14). pub fn property(&self, name: &str) -> Option<&Property> { - self.properties + let (index, property) = self + .properties + .iter() + .enumerate() + .rev() + .find(|(_, property)| property.name == name)?; + (!self.hidden(name, index + 1, index)).then_some(property) + } + + /// The property or member of unpacked structure type `name`. + pub fn aggregate(&self, name: &str) -> Option<&AggregateProperty> { + let aggregate = self + .aggregates .iter() .rev() - .find(|property| property.name == name) + .find(|aggregate| aggregate.name == name)?; + (!self.hidden(name, aggregate.position, aggregate.position)).then_some(aggregate) + } + + /// Whether a later declaration hides the property or member `name`: a + /// property from position `properties` on, or a property of unpacked + /// structure type after position `aggregates`, of that name or of a + /// structure that contains it (`p` for `p.a`). + fn hidden(&self, name: &str, properties: usize, aggregates: usize) -> bool { + let paths = name + .match_indices('.') + .map(|(end, _)| &name[..end]) + .chain([name]) + .collect::>(); + self.properties + .iter() + .enumerate() + .any(|(index, property)| index >= properties && paths.contains(&property.name.as_str())) + || self.aggregates.iter().any(|aggregate| { + aggregate.position > aggregates && paths.contains(&aggregate.name.as_str()) + }) } pub fn static_property(&self, name: &str) -> Option<&StaticProperty> { @@ -746,6 +796,10 @@ pub(super) fn class( .map(|base| base.properties.clone()) .unwrap_or_default(); let base_properties = properties.len(); + let mut aggregates = base + .as_ref() + .map(|base| base.aggregates.clone()) + .unwrap_or_default(); let mut statics = base .as_ref() .map(|base| base.statics.clone()) @@ -782,6 +836,55 @@ pub(super) fn class( return Err(unsupported("const dynamic container class property")); } let property_name = instances::normalize_identifier(&variable.name.spelling); + if let Some(aggregate) = ty.unpacked_struct() { + if property.qualifiers.is_static { + return Err(unsupported( + "static class property of unpacked structure type", + )); + } + if property.qualifiers.rand || property.qualifiers.randc { + return Err(unsupported( + "random class property of unpacked structure type", + )); + } + if property.declaration.constant { + return Err(unsupported( + "const class property of unpacked structure type", + )); + } + for (aggregate_name, aggregate_type) in + unpacked_structs::aggregates(&property_name, &ty) + { + aggregates.push(AggregateProperty { + initializer: (aggregate_name == property_name) + .then_some(variable.value) + .flatten(), + name: aggregate_name, + owner: name.to_owned(), + local: property.qualifiers.local, + protected: property.qualifiers.protected, + r#type: aggregate_type, + position: properties.len(), + }); + } + for leaf in aggregate.leaves() { + let field = field(&tree.state, &leaf.r#type, env, size)?; + size = field.offset + field.storage(); + properties.push(Property { + name: leaf.name(&property_name), + owner: name.to_owned(), + constant: false, + local: property.qualifiers.local, + protected: property.qualifiers.protected, + r#type: leaf.r#type, + field, + rand: false, + randc: false, + initializer: None, + }); + } + continue; + } if property.qualifiers.is_static { statics.retain(|known| known.name != property_name); statics.push(StaticProperty { @@ -946,6 +1049,7 @@ pub(super) fn class( is_interface: false, properties, base_properties, + aggregates, statics, methods, declarations: Vec::new(), @@ -1066,6 +1170,7 @@ fn interface_class( constraints: Vec::new(), properties: Vec::new(), base_properties: 0, + aggregates: Vec::new(), statics: Vec::new(), methods, declarations, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 730ee1d4d03..2fb1a538e7c 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -18,12 +18,14 @@ pub(super) use direct::{ }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ - Cast as ObjectCast, Receiver as ObjectReceiver, cast as object_cast, + Cast as ObjectCast, Receiver as ObjectReceiver, + aggregate_property as object_aggregate_property, cast as object_cast, 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, named_class, native_class as object_native_class, - property as object_property, rand_mode_call as object_rand_mode_call, - receiver as object_receiver, static_property as object_static_property, this as object_this, + method as object_method, method_result as object_method_result, named_class, + native_class as object_native_class, property as object_property, + rand_mode_call as object_rand_mode_call, 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, string_value, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 54e4c835587..530288d7e7c 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -485,6 +485,16 @@ pub(in crate::ast) fn bind_value( values.push(value); continue; } + if let Some((aggregate, class, _)) = + objects::aggregate_property(tree, id, native, dimensions)? + { + values.push(objects::aggregate_load( + &aggregate, + &class, + &objects::this(), + )?); + continue; + } if let Some(value) = objects::unqualified_property(tree, dimensions, &name)? { values.push(value); @@ -935,6 +945,16 @@ pub(in crate::ast) fn bind_value( ); continue; } + ExprKind::Member { .. } + if objects::aggregate_property(tree, id, native, dimensions)?.is_some() => + { + let (aggregate, class, receiver) = + objects::aggregate_property(tree, id, native, dimensions)? + .expect("checked by the guard"); + let handle = objects::receiver(tree, receiver, native, dimensions)?; + values.push(objects::aggregate_load(&aggregate, &class, &handle)?); + continue; + } ExprKind::Member { .. } if objects::property(tree, id, native, dimensions)?.is_some() => { 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 f436e4d63e5..dc66344bd04 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -86,8 +86,10 @@ pub(in crate::ast) fn native_class( name, } = &expression.kind && separator == "." + // Otherwise a member of a property of unpacked structure type, found + // as a property below. + && let Some(owner) = native_class(tree, *receiver, native, dimensions) { - let owner = native_class(tree, *receiver, native, dimensions)?; let member = instances::normalize_identifier(&name.spelling); let receiver = (!is_super(*receiver, native)).then_some(*receiver); if let Some((property, _)) = @@ -393,40 +395,10 @@ pub(in crate::ast) fn property( native: &Declarations, dimensions: &PackedDimensions, ) -> Converted)>> { - let (class_name, name, receiver) = match &native.expression(ungroup(id, native)).kind { - ExprKind::Member { - expression, - separator, - name, - } if separator == "." => match native_class(tree, *expression, native, dimensions) { - Some(class) => ( - class, - name, - (!is_super(*expression, native)).then_some(*expression), - ), - None => return Ok(None), - }, - ExprKind::Name(name) => { - if dimensions - .get(&instances::normalize_identifier(&name.spelling)) - .is_some() - { - return Ok(None); - } - match scope_class(dimensions) { - Some(class) => (class, name, None), - None => return Ok(None), - } - } - _ => return Ok(None), + let Some((class, name, receiver)) = member_chain(tree, id, native, dimensions)? else { + return Ok(None); }; - property_in( - tree, - dimensions, - &class_name, - &instances::normalize_identifier(&name.spelling), - receiver, - ) + property_of(tree, dimensions, &class, &name, receiver) } /// The instance property `name` of class `class_name`, read through @@ -442,6 +414,18 @@ fn property_in( return Ok(None); } let class = class(tree, dimensions, class_name)?; + property_of(tree, dimensions, &class, name, receiver) +} + +/// The instance property `name` of `class`, read through `receiver` as +/// [`property`] returns it. +fn property_of( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + class: &Class, + name: &str, + receiver: Option, +) -> Converted)>> { let Some(property) = class.property(name) else { if let Some(property) = class.static_property(name) { check_access( @@ -472,6 +456,122 @@ fn property_in( Ok(Some((property.clone(), receiver))) } +/// The property of unpacked structure type, or member of one, that native +/// expression `id` names, with the receiver as for [`property`]. +pub(in crate::ast) fn aggregate_property( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted, Option)>> { + let Some((class, name, receiver)) = member_chain(tree, id, native, dimensions)? else { + return Ok(None); + }; + let Some(aggregate) = class.aggregate(&name).cloned() else { + return Ok(None); + }; + check_access( + tree, + dimensions, + &aggregate.owner, + &aggregate.name, + aggregate.local, + aggregate.protected, + )?; + if receiver.is_none() && dimensions.get(THIS).is_none() { + return Err(unsupported(format!( + "non-static property `{}` in a static method", + aggregate.name + ))); + } + Ok(Some((aggregate, class, receiver))) +} + +/// The flat value of property `aggregate` of `class` in the object +/// `handle`: the concatenation of its leaf properties. +pub(in crate::ast) fn aggregate_load( + aggregate: &classes::AggregateProperty, + class: &Class, + handle: &Expr, +) -> Converted { + let leaves = aggregate + .r#type + .unpacked_struct() + .expect("an unpacked structure property") + .leaves(); + // Each member is read through the receiver, so it must not change: a + // subroutine call, pop or `$urandom` would be made once per member. + if leaves.len() > 1 && inlining::effectful(handle) { + return Err(unsupported( + "whole unpacked structure property read through a receiver with a side effect", + )); + } + Ok(Expr::Concat( + leaves + .iter() + .map(|leaf| { + let property = class + .property(&leaf.name(&aggregate.name)) + .ok_or_else(|| unsupported("unpacked structure property member"))?; + Ok(load(property, handle.clone())) + }) + .collect::>>()?, + )) +} + +/// The class, property path and receiver of `h.p`, `h.p.m`, or an +/// unqualified `p`/`p.m` inside a method of its class. A path names a +/// member of a property of unpacked structure type. +fn member_chain( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted, String, Option)>> { + let mut names = Vec::new(); + let mut current = ungroup(id, native); + let (class_name, receiver) = loop { + match &native.expression(current).kind { + ExprKind::Member { + expression, + separator, + name, + } if separator == "." => { + names.push(instances::normalize_identifier(&name.spelling)); + if let Some(class) = native_class(tree, *expression, native, dimensions) { + break ( + class, + (!is_super(*expression, native)).then_some(*expression), + ); + } + current = ungroup(*expression, native); + } + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + if dimensions.get(&name).is_some() { + return Ok(None); + } + names.push(name); + match scope_class(dimensions) { + Some(class) => break (class, None), + None => return Ok(None), + } + } + _ => return Ok(None), + } + }; + names.reverse(); + // A process handle has no properties (IEEE 1800-2023 9.7). + if class_name == super::super::processes::CLASS { + return Ok(None); + } + Ok(Some(( + class(tree, dimensions, &class_name)?, + names.join("."), + receiver, + ))) +} + /// The handle of the object that `receiver` of [`property`] refers to. pub(in crate::ast) fn receiver( tree: &AnalysisContext<'_>, @@ -1323,3 +1423,38 @@ pub(super) fn randomize_with( arg_order: Vec::new(), }) } + +/// The declared result type of the method that native callee expression +/// `id` names (`h.m`, `C::m`, or unqualified inside a method), when known. +pub(in crate::ast) fn method_result( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + let (class_name, name) = match &native.expression(ungroup(id, native)).kind { + ExprKind::Member { + expression, + separator, + name, + } => match separator.as_str() { + "." => (native_class(tree, *expression, native, dimensions), name), + "::" => (named_class(tree, *expression, native, dimensions)?, name), + _ => return Ok(None), + }, + ExprKind::Name(name) + if dimensions + .get(&instances::normalize_identifier(&name.spelling)) + .is_none() => + { + (scope_class(dimensions), name) + } + _ => return Ok(None), + }; + let Some(class_name) = class_name.filter(|name| name != super::super::processes::CLASS) else { + return Ok(None); + }; + Ok(class(tree, dimensions, &class_name)? + .method(&instances::normalize_identifier(&name.spelling)) + .and_then(|method| method.result.clone().flatten())) +} diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index da4b901db5a..83296533343 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -145,6 +145,94 @@ pub(super) fn expr_signedness_with_return_types( } } +/// Whether a call of `callee` only reads: a container element, size or +/// membership, an object property, a string operation or an enumeration +/// lookup. +fn reads_only(callee: &Callee) -> bool { + match callee { + Callee::String(_) | Callee::Lookup { .. } => true, + Callee::Object(op) => matches!( + **op, + ObjectOp::Load(_) + | ObjectOp::Container { + op: ContainerOp::Get | ContainerOp::Size | ContainerOp::Exists, + .. + } + ), + _ => false, + } +} + +/// Whether evaluating `expr` calls anything that does not only read (see +/// [`reads_only`]), also in the positions of a select. +pub(super) fn effectful(expr: &Expr) -> bool { + fn constant(expr: &ConstExpr) -> bool { + match expr { + ConstExpr::Function { callee, args, .. } => { + !reads_only(callee) || args.iter().any(constant) + } + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + constant(expr) || constant(msb) || constant(lsb) + } + ConstExpr::Select { expr, bit } => constant(expr) || constant(bit), + ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => constant(expr), + ConstExpr::Binary { left, right, .. } => constant(left) || constant(right), + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => constant(condition) || constant(then_expr) || constant(else_expr), + ConstExpr::Literal(_) | ConstExpr::Ident(_) => false, + } + } + let mut pending = vec![expr]; + while let Some(expr) = pending.pop() { + match expr { + Expr::Call { callee, args, .. } => { + if !reads_only(callee) { + return true; + } + pending.extend(args.iter().flatten()); + } + Expr::Select { expr, msb, lsb, .. } => { + if constant(msb) || constant(lsb) { + return true; + } + pending.push(expr) + } + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => pending.push(expr), + Expr::Concat(parts) | Expr::RepeatConcat { parts, .. } => pending.extend(parts), + Expr::Binary { left, right, .. } => { + pending.push(left); + pending.push(right); + } + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + pending.push(condition); + pending.push(then_expr); + pending.push(else_expr); + } + Expr::Inside { expr, items } => { + pending.push(expr); + for item in items { + match item { + InsideItem::Value(value) => pending.push(value), + InsideItem::Range { low, high } => { + pending.push(low); + pending.push(high); + } + } + } + } + Expr::Ident(_) | Expr::Literal(_) => {} + } + } + false +} + /// Whether `expr` calls a subroutine, which may have side effects. pub(super) fn calls_subroutine(expr: &Expr) -> bool { fn constant(expr: &ConstExpr) -> bool { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index cb235b27221..e194c29f6d3 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -341,8 +341,20 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// it (IEEE 1800-2023 8.9). fn enter_class_scope(&mut self, class: &classes::Class) { self.dims.class_scope = Some(class.name.clone()); - for property in &class.properties { - let entry = self.take_binding(&property.name, None, 0); + // The name of a property of unpacked structure type, whose members + // are properties named by their member paths, is hidden too. + let aggregates = class + .aggregates + .iter() + .filter(|aggregate| !aggregate.name.contains('.')) + .map(|aggregate| aggregate.name.as_str()); + for name in class + .properties + .iter() + .map(|property| property.name.as_str()) + .chain(aggregates) + { + let entry = self.take_binding(name, None, 0); self.scopes .last_mut() .expect("a body always has a scope") @@ -1193,6 +1205,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { "native assignment operator mode disagrees".into(), )); } + if let Some(stmts) = + self.aggregate_property_assignment(operator, *nonblocking, *left, *right)? + { + return Ok(stmts); + } Ok(vec![self.assignment_value( if *nonblocking { "=" } else { operator }, *nonblocking, @@ -2040,7 +2057,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } Some(ForInitialization::Assignments(values)) => { for value in values { - init.push(self.assignment_value("=", false, (value.left, value.right))?); + match self.aggregate_property_assignment("=", false, value.left, value.right)? { + Some(stmts) => init.extend(stmts), + None => init.push(self.assignment_value( + "=", + false, + (value.left, value.right), + )?), + } } } } @@ -2050,6 +2074,18 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .transpose()?; let mut steps = Vec::new(); for step in &header.steps { + if let ForStep::Assignment { + left, + operator, + right, + .. + } = step + && let Some(stmts) = + self.aggregate_property_assignment(operator, false, *left, *right)? + { + steps.extend(stmts); + continue; + } steps.push(match step { ForStep::Assignment { left, operator, right, .. } => self.assignment_value(operator, false, (*left, *right))?, ForStep::Expression(id) => { @@ -3285,7 +3321,9 @@ impl BodyBuilder<'_, '_, '_> { .collect(), }); } - for property in class.own_properties() { + let own = class.base_properties..class.properties.len(); + for (index, property) in own.clone().zip(class.own_properties()) { + body.extend(self.aggregate_initializers(class, this, index)?); let Some(initializer) = property.initializer else { continue; }; @@ -3328,6 +3366,135 @@ impl BodyBuilder<'_, '_, '_> { vec![Expr::Ident(this.to_owned()), value], ))); } + body.extend(self.aggregate_initializers(class, this, own.end)?); + Ok(body) + } + + /// The initializers of the properties of unpacked structure type that + /// `class` declares before its property `position`. + fn aggregate_initializers( + &mut self, + class: &classes::Class, + this: &str, + position: usize, + ) -> Converted> { + let mut body = Vec::new(); + for aggregate in &class.aggregates { + if aggregate.owner != class.name || aggregate.position != position { + continue; + } + if let Some(initializer) = aggregate.initializer { + body.extend(self.aggregate_store( + aggregate, + class, + Expr::Ident(this.to_owned()), + initializer, + )?); + } + } + Ok(body) + } + + /// An assignment to a whole class property of unpacked structure type, + /// `h.p = v`: a store of each of its leaf properties. + fn aggregate_property_assignment( + &mut self, + op: &str, + nonblocking: bool, + left: celox_sv_syntax::ExprId, + right: celox_sv_syntax::ExprId, + ) -> Converted>> { + let native = self.tree.declarations(); + let Some((aggregate, class, receiver)) = + expression_binding::object_aggregate_property(self.tree, left, native, &self.dims)? + else { + return Ok(None); + }; + if nonblocking { + return Err(unsupported("nonblocking assignment to a class property")); + } + if op != "=" { + return Err(unsupported(format!( + "operator `{op}` on an unpacked structure" + ))); + } + let mut handle = + expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + self.rename_expr(&mut handle); + self.aggregate_store(&aggregate, &class, handle, right) + .map(Some) + } + + /// Store the value of native `right` into each leaf property of + /// `aggregate` of the object `handle`. + fn aggregate_store( + &mut self, + aggregate: &classes::AggregateProperty, + class: &classes::Class, + handle: Expr, + right: celox_sv_syntax::ExprId, + ) -> Converted> { + let native = self.tree.declarations(); + let structure = aggregate + .r#type + .unpacked_struct() + .expect("an unpacked structure property") + .clone(); + unpacked_structs::check_value(&structure, right, native, self.tree, &self.dims)?; + let mut value = expression_binding::bind_value( + right, + native, + self.tree, + &self.dims, + Some(&dimensions_from_type(&aggregate.r#type)), + )?; + self.rename_expr(&mut value); + let leaves = structure.leaves(); + let mut body = Vec::new(); + // Evaluate the whole value, which may read the members it replaces, + // and the object it is stored in once, before any member is written. + let mut flat = aggregate.r#type.clone(); + flat.unpacked_struct = None; + let temp = self.declare("$aggregate", flat); + body.push(Stmt::Local { + name: temp.clone(), + init: None, + }); + body.push(Stmt::Assign { + lhs: LValue::Ident(temp.clone()), + rhs: value, + nonblocking: false, + }); + let handle = if inlining::calls_subroutine(&handle) { + let receiver = self.declare("$receiver", classes::handle(&class.name)); + body.push(Stmt::Local { + name: receiver.clone(), + init: None, + }); + body.push(Stmt::Assign { + lhs: LValue::Ident(receiver.clone()), + rhs: handle, + nonblocking: false, + }); + Expr::Ident(receiver) + } else { + handle + }; + let parts = leaves.iter().map(|leaf| Expr::Select { + expr: Box::new(Expr::Ident(temp.clone())), + msb: ConstExpr::Literal((leaf.offset + leaf.width - 1).to_string()), + lsb: ConstExpr::Literal(leaf.offset.to_string()), + signed: false, + }); + for (leaf, part) in leaves.iter().zip(parts) { + let property = class + .property(&leaf.name(&aggregate.name)) + .ok_or_else(|| unsupported("unpacked structure property member"))?; + body.push(Stmt::Eval(classes::object_call( + system_functions::ObjectOp::Store(property.field), + vec![handle.clone(), part], + ))); + } Ok(body) } } diff --git a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs index 0b7bb83d67b..1262333ff4b 100644 --- a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs @@ -239,13 +239,19 @@ pub(in crate::ast) fn native_struct( ) -> Converted>> { let id = expression_binding::ungroup(id, native); Ok(match &native.expression(id).kind { - ExprKind::Name(_) | ExprKind::Member { .. } => member_path(id, native) + ExprKind::Name(_) | ExprKind::Member { .. } => match member_path(id, native) .map(|mut parts| { collapse(&mut parts, dims); parts }) .filter(|parts| parts.len() == 1) - .and_then(|parts| dims.get(&parts[0])?.unpacked_struct.clone()), + .and_then(|parts| dims.get(&parts[0])?.unpacked_struct.clone()) + { + Some(aggregate) => Some(aggregate), + // A class property of unpacked structure type. + None => expression_binding::object_aggregate_property(tree, id, native, dims)? + .and_then(|(aggregate, _, _)| aggregate.r#type.unpacked_struct().cloned()), + }, ExprKind::Conditional { then_expression, else_expression, @@ -265,11 +271,16 @@ pub(in crate::ast) fn native_struct( } if std::ptr::eq(native, tree.declarations()) => { patterns::typed_shape(id, tree, dims)?.and_then(|shape| shape.unpacked_struct) } + // A method of the scope class hides a module function of its name, + // as call binding resolves it. ExprKind::Call { expression, .. } => { - expression_binding::callable_name(&tree.state, *expression, native) - .and_then(|name| dims.functions.get(&name)) - .and_then(|function| function.return_type.as_ref()) - .and_then(|ty| ty.unpacked_struct().cloned()) + match expression_binding::object_method_result(tree, *expression, native, dims)? { + Some(ty) => ty.unpacked_struct().cloned(), + None => expression_binding::callable_name(&tree.state, *expression, native) + .and_then(|name| dims.functions.get(&name)) + .and_then(|function| function.return_type.as_ref()) + .and_then(|ty| ty.unpacked_struct().cloned()), + } } _ => None, }) diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 9255cac7101..70155d7e067 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -627,7 +627,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_integral_format_string` | execute | icarus | 1 | Icarus 13.0 compiles `$sformatf` with a `bit` vector variable as the format, then `vvp` stops: "$sformatf's first argument must be a string or a register." IEEE 1800-2023 21.3.3 reads the content of an integral format expression as the format; Verilator 5.052 gives the expected output, xezim 0.11.3 prints the format as a value (`sv_integral_format_string` in the xezim review). | | `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. | | `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). | -| `sv_icarus_unpacked_structs` | compile | icarus | 8 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | +| `sv_icarus_unpacked_structs` | compile | icarus | 12 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | | `sv_verilator_nested_struct_default` | execute | verilator | 1 | Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 ("5 0000 1" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101. | The `string_format` cases compare `$sformatf`, `$sformat` and `$swrite` with diff --git a/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest index 507b071581e..ebf1175badc 100644 --- a/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest +++ b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest @@ -277,3 +277,175 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "def x xxxx 0 00\ncopy 1z0x x 1\npattern 5 xx11 0 01\ndefault 0 0000 0 00\n")) + +(case class_properties + (source "unpacked_struct_properties.sv" #" +module Top(output bit done); + class Node; + string n; + function new(string n); + this.n = n; + endfunction + endclass + typedef struct { Node m_type; string m_type_name; } pair_t; + typedef struct { time read_time; int unsigned read_count; bit [3:0] l; } access_t; + class Override; + string path; + pair_t orig; + pair_t ovrd = '{null, "init"}; + access_t acc; + function new(string p, string on, Node ot); + path = p; + this.orig.m_type_name = on; + this.orig.m_type = ot; + endfunction + function bit pair_matches(pair_t m, Node t); + return m.m_type == t && m.m_type_name != ""; + endfunction + function void touch(time now); + acc.read_count++; + acc.read_time = now; + endfunction + endclass + initial begin + Node a; + Override o, c; + pair_t tp; + access_t x; + a = new("A"); + o = new("p", "A", a); + $display("%s %s %s [%s]", o.orig.m_type_name, o.orig.m_type.n, o.ovrd.m_type_name, o.path); + tp = o.orig; + tp.m_type_name = "changed"; + $display("%s %s %0d %0d", o.orig.m_type_name, tp.m_type_name, o.pair_matches(o.orig, a), o.orig == tp); + o.ovrd = tp; + o.ovrd.m_type = null; + $display("%s %0d %0d", o.ovrd.m_type_name, o.ovrd.m_type == null, o.orig.m_type == null); + $display("acc %0d %0d %b", o.acc.read_time, o.acc.read_count, o.acc.l); + o.touch(5); + o.acc.l = 4'b1011; + c = new o; + c.acc.read_count = 9; + x = c.acc; + $display("acc %0d %0d %b | %0d %0d %b", o.acc.read_time, o.acc.read_count, o.acc.l, x.read_time, x.read_count, x.l); + o.acc = '{default: 0}; + $display("acc %0d %0d %b", o.acc.read_time, o.acc.read_count, o.acc.l); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "A A init [p]\nA changed 1 0\nchanged 1 0\nacc 0 0 0000\nacc 5 1 1011 | 5 9 1011\nacc 0 0 0000\n")) + +(case class_property_assignment_order + (source "unpacked_struct_property_order.sv" #" +module Top(output bit done); + typedef struct { int a; int b; } pair_t; + class Holder; + pair_t p; + endclass + Holder items[3]; + int i; + function automatic int next_index(); + i++; + return i; + endfunction + initial begin + Holder h; + h = new; + h.p.a = 1; + h.p.b = 2; + h.p = '{h.p.b, h.p.a}; + $display("%0d %0d", h.p.a, h.p.b); + foreach (items[k]) begin + items[k] = new; + items[k].p = '{k, k * 10}; + end + i = 0; + items[next_index()].p = '{7, 8}; + $display("%0d %0d %0d %0d %0d", items[1].p.a, items[1].p.b, items[2].p.a, items[2].p.b, i); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "2 1\n7 8 2 20 1\n")) + +(case class_property_four_state_members + (four_state) + (source "unpacked_struct_property_states.sv" #" +module Top(output bit done); + typedef struct { time t; int i; logic [3:0] l; } access_t; + class Holder; + access_t acc; + endclass + Holder h; + access_t copy; + initial begin + h = new; + $display("%0d %0d %b", h.acc.t, h.acc.i, h.acc.l); + h.acc.l = 4'b1z0x; + copy = h.acc; + $display("%b %0d", copy.l, copy === h.acc); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "x 0 xxxx\n1z0x 1\n")) + +(case class_properties_inheritance_and_collections + (source "unpacked_struct_property_heap.sv" #" +module Top(output int n); + class Node; + string text; + endclass + typedef struct { Node m_type; string m_type_name; } pair_t; + class Base; + pair_t orig; + function pair_t get(); + return orig; + endfunction + function bit same(pair_t p); + return orig == p; + endfunction + function void set(string s); + orig = '{m_type: null, m_type_name: s}; + endfunction + endclass + class Derived extends Base; + pair_t ovrd; + function void swap(); + pair_t t; + t = orig; + orig = ovrd; + ovrd = t; + endfunction + endclass + logic clk = 0; + always #1 clk = ~clk; + Derived d; + string number; + always @(posedge clk) begin + number.itoa(n); + d.set({number, "!"}); + d.ovrd.m_type = new; + d.ovrd.m_type.text = number; + n = n + 1; + end + initial begin + pair_t g; + d = new; + d.set("x"); + g = d.get(); + $display("%s %0d", g.m_type_name, d.same(g)); + d.ovrd.m_type_name = "o"; + d.swap(); + $display("%s %s", d.orig.m_type_name, d.ovrd.m_type_name); + #6000 $display("[%s] [%s] %0d", d.orig.m_type_name, d.ovrd.m_type.text, n); + end +endmodule +"#) + (top Top) + (run_until 6000) + (expect_output "x 1\no x\n[2999!] [2999] 3000\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_xezim_unpacked_struct_properties.sv b/crates/celox-test-suite/verification/repros/sv_xezim_unpacked_struct_properties.sv new file mode 100644 index 00000000000..745b6e0d9e5 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_xezim_unpacked_struct_properties.sv @@ -0,0 +1,23 @@ +// xezim 0.11.3: a string member of a class property of unpacked structure +// type prints with %s as a wide packed value padded with spaces, and a +// property of an object held in a handle member reads empty (IEEE 1800-2023 +// 7.2, 8.4, 21.2.1.7). Expected: "[A] [A]". +module top; + class Node; + string n; + endclass + typedef struct { Node m_type; string m_type_name; } pair_t; + class Holder; + pair_t orig; + endclass + initial begin + Holder h; + Node a; + h = new; + a = new; + a.n = "A"; + h.orig.m_type = a; + h.orig.m_type_name = "A"; + $display("[%s] [%s]", h.orig.m_type_name, h.orig.m_type.n); + end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json index 6b919f07e53..49cfe0947a9 100644 --- a/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json @@ -23,6 +23,98 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::class_properties", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::class_properties_inheritance_and_collections", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::class_property_assignment_order", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::class_property_four_state_members", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 9f1345b58d9..cf96d93d2dd 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2984,6 +2984,10 @@ "cases": { "icarus": [ "unpacked_structs::assignment_patterns", + "unpacked_structs::class_properties", + "unpacked_structs::class_properties_inheritance_and_collections", + "unpacked_structs::class_property_assignment_order", + "unpacked_structs::class_property_four_state_members", "unpacked_structs::four_state_members", "unpacked_structs::handle_members_survive_heap_collections", "unpacked_structs::initializers_results_and_defaults", diff --git a/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json index 1344517bc8f..e2b3c126390 100644 --- a/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json @@ -23,6 +23,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::class_properties", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::class_properties_inheritance_and_collections", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::class_property_assignment_order", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "unpacked_structs::class_property_four_state_members", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "four-state expectations", diff --git a/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json index 736d7342928..9da00089498 100644 --- a/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json @@ -11,6 +11,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "unpacked_structs::class_properties at 338:3: expect_output: expected [65, 32, 65, 32, 105, 110, 105, 116, 32, 91, 112, 93, 10, 65, 32, 99, 104, 97, 110, 103, 101, 100, 32, 49, 32, 48, 10, 99, 104, 97, 110, 103, 101, 100, 32, 49, 32, 48, 10, 97, 99, 99, 32, 48, 32, 48, 32, 48, 48, 48, 48, 10, 97, 99, 99, 32, 53, 32, 49, 32, 49, 48, 49, 49, 32, 124, 32, 53, 32, 57, 32, 49, 48, 49, 49, 10, 97, 99, 99, 32, 48, 32, 48, 32, 48, 48, 48, 48, 10], got [32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 65, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 105, 116, 32, 91, 112, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 65, 32, 99, 104, 97, 110, 103, 101, 100, 32, 49, 32, 48, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 99, 104, 97, 110, 103, 101, 100, 32, 49, 32, 48, 10, 97, 99, 99, 32, 120, 32, 48, 32, 48, 48, 48, 48, 10, 97, 99, 99, 32, 53, 32, 49, 32, 49, 48, 49, 49, 32, 124, 32, 53, 32, 57, 32, 49, 48, 49, 49, 10, 97, 99, 99, 32, 48, 32, 48, 32, 48, 48, 48, 48, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::class_properties", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::class_properties_inheritance_and_collections at 451:3: expect_output: expected [120, 32, 49, 10, 111, 32, 120, 10, 91, 50, 57, 57, 57, 33, 93, 32, 91, 50, 57, 57, 57, 93, 32, 51, 48, 48, 48, 10], got [120, 32, 49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 111, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 120, 10, 91, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 50, 57, 57, 57, 33, 93, 32, 91, 50, 57, 57, 57, 93, 32, 51, 48, 48, 48, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::class_properties_inheritance_and_collections", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::class_property_assignment_order at 372:3: expect_output: expected [50, 32, 49, 10, 55, 32, 56, 32, 50, 32, 50, 48, 32, 49, 10], got [50, 32, 50, 10, 49, 32, 49, 48, 32, 55, 32, 50, 48, 32, 51, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::class_property_assignment_order", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::class_property_four_state_members", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index a22d1b0a5ce..44e8a8d4db5 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -786,6 +786,14 @@ "sv_rest-X88": { "title": "An automatic output argument of unpacked structure type that is not written is copied out as X for a 2-state member", "standard": "IEEE 1800-2023 13.5.2, 6.8" + }, + "sv_rest-X84": { + "title": "A string member of a class property of unpacked structure type prints with %s as a space-padded packed value, and a property of the object in a handle member reads empty", + "standard": "IEEE 1800-2023 7.2, 8.4, 21.2.1.7" + }, + "sv_rest-X89": { + "title": "A whole class property of unpacked structure type is assigned member by member: a pattern reading the property sees members already written, and a receiver with a side-effecting index is evaluated per member", + "standard": "IEEE 1800-2023 7.2, 10.9.2, 11.4.1" } }, "cases": [ @@ -4619,6 +4627,30 @@ "classification": "xezim_bug", "bug": "sv_rest-X88", "note": "outz(r) does not write its output formal, so r.a must become the int default 0; xezim prints \"outz x\". Reproduced by verification/repros/sv_xezim_struct_output_default.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::class_properties", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X84", + "note": "o.orig.m_type_name and o.ovrd.m_type_name print as space-padded wide values and o.orig.m_type.n prints empty; the time member also starts at X in xezim's 4-state run of this 2-state case. Reproduced by verification/repros/sv_xezim_unpacked_struct_properties.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::class_properties_inheritance_and_collections", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X84", + "note": "d.orig.m_type_name and d.ovrd.m_type_name print as space-padded wide values (\"o x\" and \"[2999!]\" expected). Reproduced by verification/repros/sv_xezim_unpacked_struct_properties.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::class_property_assignment_order", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X89", + "note": "h.p = '{h.p.b, h.p.a} prints \"2 2\" instead of \"2 1\", and items[next_index()].p = '{7, 8} calls next_index() once per member, writing items[1].p.a and items[2].p.b, with i = 3 instead of 1." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs index 95f1c6b75cb..99cf93ba158 100644 --- a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs +++ b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs @@ -19,6 +19,64 @@ sv_backends! { @case "unpacked_structs::results_and_outputs"; } + fn structure_properties_hide_module_variables(sim) { + @setup { + let source = r#"module Top(output int value); + typedef struct { int a; int b; } pair_t; + int p; + class C; + pair_t p; + function int first(); + p.a = 7; + return p.a; + endfunction + endclass + initial begin + C c; + c = new; + p = 3; + value = c.first() * 10 + p; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(73u8)); + } + + fn structure_properties_in_for_headers_and_method_precedence(sim) { + @setup { + let source = r#"module Top(output int value); + typedef struct { int a; int b; } pair_t; + function int get(); + return 5; + endfunction + class H; + pair_t p; + function pair_t get(); + return '{4, 2}; + endfunction + function int run(); + int n; + for (p = '{0, 0}; p.a < 3; p = '{p.a + 1, p.b + 2}) n++; + p = get(); + return n * 100 + p.a * 10 + p.b; + endfunction + endclass + initial begin + H h; + h = new; + value = h.run(); + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(342u16)); + } + fn constructors_in_structure_patterns(sim) { @setup { let source = r#"module Top(output bit ok); @@ -96,6 +154,36 @@ sv_backends! { let out = sim.signal("out"); assert_eq!(sim.get(out), BigUint::from(71u8)); } + fn redeclared_structure_properties_hide_their_members(sim) { + @setup { + let source = r#"module Top(output int value); + typedef struct { int a; int b; } pair_t; + typedef struct { int a; } one_t; + class Base; + pair_t p; + endclass + class Derived extends Base; + one_t p; + function int sum(); + return p.a * 100 + super.p.a * 10 + super.p.b; + endfunction + endclass + initial begin + Derived d; + Base b; + d = new; + b = d; + d.p.a = 1; + b.p = '{2, 3}; + value = d.sum() * 10 + d.p.a; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(1231u16)); + } fn unpacked_struct_module_variables(sim) { @case "unpacked_structs::module_variables"; } @@ -105,6 +193,18 @@ sv_backends! { fn unpacked_struct_four_state_members(sim) { @case "unpacked_structs::four_state_members"; } + fn unpacked_struct_class_properties(sim) { + @case "unpacked_structs::class_properties"; + } + fn unpacked_struct_class_property_assignment_order(sim) { + @case "unpacked_structs::class_property_assignment_order"; + } + fn unpacked_struct_class_property_four_state_members(sim) { + @case "unpacked_structs::class_property_four_state_members"; + } + fn unpacked_struct_class_properties_inheritance_and_collections(sim) { + @case "unpacked_structs::class_properties_inheritance_and_collections"; + } } #[test] @@ -166,13 +266,41 @@ fn unsupported_and_illegal_uses_are_rejected() { ), ("i_t q[$];", "dynamic container of unpacked structures"), ( - "class C; i_t v; endclass", - "class property of unpacked structure type", + "class C; static i_t v; endclass", + "static class property of unpacked structure type", + ), + ( + "class C; rand i_t v; endclass", + "random class property of unpacked structure type", + ), + ( + "class C; i_t v; endclass C c; initial begin c = new; c.v += c.v; end", + "operator `+=` on an unpacked structure", + ), + ( + "class C; i_t v; endclass C c; i_t w; initial begin c = new; c.v <= w; end", + "nonblocking assignment to a class property", + ), + ( + "class C; i_t v; endclass C cs[2]; int k; i_t w; function int f(); k = k + 1; return k; endfunction initial w = cs[f()].v;", + "whole unpacked structure property read through a receiver with a side effect", + ), + ( + "class C; i_t v; endclass C cs[$]; int k[$]; i_t w; initial w = cs[k.pop_front()].v;", + "whole unpacked structure property read through a receiver with a side effect", ), ( "function automatic void f(ref i_t r); r.a++; endfunction i_t v; initial f(v);", "ref argument of `f` of unpacked structure type", ), + ( + "class B; i_t p; endclass class D extends B; int p; endclass D d; int x; initial begin d = new; x = d.p.a; end", + "structure member `d.p.a`", + ), + ( + "class B; i_t p; endclass typedef struct { int a; } one_t; class D extends B; one_t p; endclass D d; bit x; initial begin d = new; x = d.p.b; end", + "structure member `d.p.b`", + ), ("i_t v[2];", "array of unpacked structures"), ( "typedef struct packed { i_t x; } p_t; p_t v;", diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index f911290ad0d..96887cf304a 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 and unpacked 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; text formatted by `$sformatf` / `$sformat` / `$swrite`. See [strings](#strings) | -| Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types up to 64 bits (4-state properties start as X and keep X/Z 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) | +| Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types up to 64 bits (4-state properties start as X and keep X/Z bits), `string` and class handle types, unpacked structures of those types (see [unpacked structures](#unpacked-structures)), 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 @@ -330,8 +330,8 @@ SystemVerilog emitted by Veryl. Unpacked structures (IEEE 1800-2023 7.2) may have integral, enumeration, `string`, class handle, packed structure and nested unpacked structure members, each keeping its own 2-state or 4-state type. Variables of such a -type may be module variables, procedural locals, and subroutine arguments of -any direction and results. Members are read and written like variables of +type may be module variables, procedural locals, class properties, and +subroutine arguments of any direction and results. Members are read and written like variables of their type; a whole structure is assigned and compared with `==`, `!=`, `===` and `!==` against a value of the same type, chosen with `?:`, or built from an assignment pattern (`'{a, b}`, `'{m: v, default: d}`, `T'{...}`, with @@ -344,7 +344,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, module-local classes as type arguments to package-class specializations, properties that are `real`, arrays or wider than 64 bits, and randomization or constraints over 4-state properties. Timed tasks with static local declarations and recursive calls remain unsupported. +- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, module-local classes as type arguments to package-class specializations, properties that are `real`, arrays or wider than 64 bits, bit and part selects and packed structure members of a property (also of a member of a property of unpacked structure type), properties as `output` or `inout` arguments, and randomization or constraints over 4-state properties. Timed tasks with static local declarations and recursive calls remain unsupported. - Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `wait fork` / `disable fork`, temporal concurrent assertions beyond the Boolean subset below, `force` / `release`. @@ -361,9 +361,9 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: `bind`. - Declarations: variable declaration initializers of members of an interface array, ANSI port default values, tagged unions, unpacked unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), - `real`, and unpacked structs as ports, nets, parameters, class properties, - array or container elements, or with members that are arrays, `real`, or - have default values. + `real`, and unpacked structs as ports, nets, parameters, static, `rand` or + `const` class properties, array or container elements, or with members that + are arrays, `real`, or have default values. - Sequential processes: `iff` qualifiers in `always_ff` event lists ([#452](https://github.com/celox-sim/celox/issues/452)), and in `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit edge signals, and several edges without an asynchronous reset. diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index e3c47109148..06cf2f87910 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -100,7 +100,7 @@ Common reasons a design needs changes are: and `iff` in `always_ff` event controls ([#452](https://github.com/celox-sim/celox/issues/452)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. - Non-ANSI module ports, wildcard `.*` connections, gate primitives and `bind`. -- `real`, unpacked structs in ports, class properties and containers, and several interface features. +- `real`, unpacked structs in ports and containers, and several interface features. The [complete limitations list](./systemverilog-reference#what-is-not-supported) includes narrower restrictions and tracking issues. Unsupported constructs diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 7dbd8f3ead8..a7db5796460 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -29,7 +29,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed・unpacked 構造体、packed 配列、unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| クラス | モジュール・package・コンパイル単位で宣言したクラス。64 ビット以下の 2 値・4 値整数型(4 値のプロパティは X で始まり、X/Z ビットを保持します)・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)。[クラス](#classes)を参照 | +| クラス | モジュール・package・コンパイル単位で宣言したクラス。64 ビット以下の 2 値・4 値整数型(4 値のプロパティは X で始まり、X/Z ビットを保持します)・`string`・クラスハンドル型と、それらをメンバとする unpacked 構造体([unpacked 構造体](#unpacked-structures)を参照)のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -208,7 +208,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列挙型、`string`、 クラスハンドル、packed 構造体、入れ子の unpacked 構造体を使え、各メンバは自身の -2 値・4 値の型を保ちます。この型の変数は、モジュール変数、手続き内のローカル変数、 +2 値・4 値の型を保ちます。この型の変数は、モジュール変数、手続き内のローカル変数、クラスプロパティ、 任意の方向のサブルーチン引数と戻り値にできます。メンバはその型の変数と同じように 読み書きできます。構造体全体は、同じ型の値との代入と `==`・`!=`・`===`・`!==` による 比較、`?:` による選択、assignment pattern(`'{a, b}`、`'{m: v, default: d}`、 @@ -221,7 +221,7 @@ unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package のクラスをモジュール内クラス型で特殊化する機能、`real`・配列・64 ビットを超えるプロパティ、4 値プロパティの乱数化と制約。時間待ちを含む task の static ローカル宣言、再帰呼び出し。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package のクラスをモジュール内クラス型で特殊化する機能、`real`・配列・64 ビットを超えるプロパティ、プロパティ(unpacked 構造体型のプロパティのメンバを含む)のビット選択・部分選択と packed 構造体メンバ、`output` / `inout` 引数としてのプロパティ、4 値プロパティの乱数化と制約。時間待ちを含む task の static ローカル宣言、再帰呼び出し。 - `inout` / `ref` / 式を使う modport、virtual interface など。 ANSI ヘッダーのポートは、クロック入力やパラメータ依存の幅も含めて modport 経由で渡せます。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 @@ -236,7 +236,7 @@ unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート式(`module m({a, b}, c[3:0], .p(d))` など、[#1953](https://github.com/celox-sim/celox/issues/1953))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、`real`、ポート・ネット・パラメータ・クラスプロパティ・配列やコンテナの要素としての unpacked 構造体、配列・`real`・既定値を持つメンバ。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、`real`、ポート・ネット・パラメータ・static / `rand` / `const` のクラスプロパティ・配列やコンテナの要素としての unpacked 構造体、配列・`real`・既定値を持つメンバ。 - 順序回路のプロセス:`always_ff` のイベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 非同期リセットを持たない複数のエッジ。 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 401048927ff..62648c54789 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -94,7 +94,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 `always_ff` のイベント制御の `iff`([#452](https://github.com/celox-sim/celox/issues/452))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。 - 非 ANSI モジュールポート、ワイルドカード `.*` 接続、ゲートプリミティブ、`bind`。 -- `real`、ポート・クラスプロパティ・コンテナの unpacked 構造体、interface の一部の機能。 +- `real`、ポート・コンテナの unpacked 構造体、interface の一部の機能。 [制約の一覧](./systemverilog-reference#what-is-not-supported)に、より細かな条件と追跡 issue をまとめています。 未対応の構文は、構文名と追跡 issue を含む診断を返します。 From a37c612c38eb05957294eea77c92a411ea2e8d9c Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 19:01:53 +0900 Subject: [PATCH 3/5] feat(sv): support unpacked structures as dynamic container elements Queues, dynamic arrays and associative arrays of an unpacked structure type were rejected. A structure of at most 64 bits whose members are all 2-state or all 4-state and hold no handle is kept as its flat value, so the container's default element is the structure's default. Any other structure is held as an immutable heap record: `ObjectOp::Box` builds a record from the flat value on `push`, `insert` or an assignment, and `ObjectOp::Unbox` reads it back. Each leaf is a record field, so the collector traces string and handle members through the record's handle list, and 4-state members keep their X/Z bits. Record fields are `nullable`: the new `OBJECT_LOAD_NULLABLE` heap operation reads a null record as zeros without a fault, which is the default structure for a missing associative entry or a new dynamic array element. Records are not seeded, so they do not draw from the process RNG. `e.m` reads a member of an element `q[i]`, `aa[k]` or a popped element directly from the record or the flat value, including a handle member's properties (`q[0].orig.m_type.n`). Patterns, typed patterns and values of the structure type initialize elements. Comparing containers of records and sorting structures without `with` are rejected, as is writing a member of an element. Assignment patterns passed to a method argument now receive the formal's shape, which method calls taking a structure need. Change-Id: Iac820f46cbee8d792f4b0fbde28baccdd54ecf31 --- crates/celox-frontend-sv/src/lowering/ff.rs | 11 +- .../src/lowering/ff/objects.rs | 148 +++++++-- crates/celox-heap/src/lib.rs | 6 + crates/celox-heap/src/objects.rs | 51 ++++ crates/celox-heap/src/ops.rs | 9 + crates/celox-sv-analyzer/src/ast.rs | 3 + crates/celox-sv-analyzer/src/ast/case.rs | 20 +- crates/celox-sv-analyzer/src/ast/classes.rs | 3 +- .../celox-sv-analyzer/src/ast/containers.rs | 287 ++++++++++++++++-- .../src/ast/expression_binding/direct.rs | 53 +++- .../src/ast/expression_binding/enums.rs | 11 + .../src/ast/expression_binding/objects.rs | 4 + .../src/ast/expression_binding/strings.rs | 12 + crates/celox-sv-analyzer/src/ast/inlining.rs | 1 + .../celox-sv-analyzer/src/ast/procedural.rs | 13 + .../src/ast/unpacked_structs.rs | 67 ++++ crates/celox-sv-analyzer/src/ir.rs | 2 +- .../celox-sv-analyzer/src/system_functions.rs | 33 +- crates/celox-test-suite/LIMITATIONS.md | 2 +- .../src/sv/cases/unpacked_structs.vtest | 129 ++++++++ .../sv/icarus/unpacked_structs.json | 92 ++++++ .../verification/sv/limitations.json | 4 + .../sv/verilator/unpacked_structs.json | 44 +++ .../sv/xezim/unpacked_structs.json | 44 +++ .../systemverilog/unpacked_structs.rs | 158 +++++++++- docs/guide/systemverilog-reference.md | 14 +- docs/guide/systemverilog.md | 2 +- docs/ja/guide/systemverilog-reference.md | 3 +- docs/ja/guide/systemverilog.md | 2 +- 29 files changed, 1163 insertions(+), 65 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index fb0cf6b38c3..1616a675ef9 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -3622,9 +3622,11 @@ impl<'p, 'a> Ff<'p, 'a> { let mut arena = SLTNodeArena::new(); let node = self.expr_slt(rhs, Some((total, signed)), &mut arena)?; let node = coerce_node_width(&mut arena, node, Some(total), signed).map_err(slt_error)?; - // Capture the value before any part is written. - let (temp, temp_name) = self.m.temp("concat", total, false, true); + // Capture the value before any part is written, in a temporary of + // the value's state kind. let value = self.lower_slt(&arena, node)?; + let four_state = matches!(self.b.register(&value), RegisterType::Logic { .. }); + let (temp, temp_name) = self.m.temp("concat", total, false, four_state); self.store(temp, SIROffset::Static(0), total, value); let mut lsb = total; for (part, width) in parts.iter().zip(widths) { @@ -7838,14 +7840,15 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { // Container contents are immutable: reading an element is a // value of the container handle and index, unlike a class // property that can change without its handle changing. + // A record of a structure element is immutable as well. sv::ir::Callee::Object(op) if matches!( *op, sv::ir::ObjectOp::Container { op: sv::ir::ContainerOp::Get, .. - } - ) => + } | sv::ir::ObjectOp::Unbox(_) + ) || matches!(*op, sv::ir::ObjectOp::Load(field) if field.nullable) => { continue; } diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index 8f4a36cc2d4..46908086f68 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -25,6 +25,11 @@ impl Ff<'_, '_> { .collect::, _>>()?; if args.iter().any(|arg| self.m.calls(arg)) { for (index, arg) in args.iter_mut().enumerate() { + // A record is built from a flat structure value, not a handle. + if let ObjectOp::Box(record) = op { + *arg = self.heap_operand(arg, Some((record.width(), false)), None)?; + continue; + } let (width, signed) = if index == 0 { (32, false) } else { @@ -118,36 +123,87 @@ impl Ff<'_, '_> { } ObjectOp::Load(field) if field.four_state && self.m.four_state => { let object = self.handle(&args[0])?; - let [value, mask] = [0, field.bytes()].map(|plane| { - let offset = self.constant64(u64::from(field.offset + plane)); - let count = self.constant64(u64::from(field.bytes())); - let stored = self.heap_call(ops::OBJECT_LOAD, &[object, offset, count]); - self.complement(stored) - }); + let result = self.load_field(object, *field); let width = field.width as usize; - let result = self.container_join(value, mask, width, true); let (temp, name) = self.m.temp("object", width, field.signed, true); self.store(temp, SIROffset::Static(0), width, result); return Ok(sv::ir::Expr::Ident(name)); } ObjectOp::Load(field) => { let object = self.handle(&args[0])?; - let offset = self.constant64(u64::from(field.offset)); - let count = self.constant64(u64::from(field.bytes())); - self.heap_call(ops::OBJECT_LOAD, &[object, offset, count]) + self.load_field(object, *field) + } + ObjectOp::Unbox(record) => { + let object = self.handle(&args[0])?; + let parts = record + .fields + .iter() + .map(|field| self.load_field(object, *field)) + .collect::>(); + let width = record.width(); + let four_state = self.m.four_state && record.fields.iter().any(|f| f.four_state); + let value = if four_state { + self.b.alloc_logic(width) + } else { + self.b.alloc_bit(width, false) + }; + self.b.emit(SIRInstruction::Concat(value, parts)); + let (temp, name) = self.m.temp("record", width, false, four_state); + self.store(temp, SIROffset::Static(0), width, value); + return Ok(sv::ir::Expr::Ident(name)); + } + ObjectOp::Box(record) => { + // Evaluate the value first: its calls may end the block, so + // the record's handle is only used after them. + let expr = self.hoist(&args[0])?; + let width = record.width(); + let mut arena = SLTNodeArena::new(); + let node = self.expr_slt(&expr, Some((width, false)), &mut arena)?; + let node = + coerce_node_width(&mut arena, node, Some(width), false).map_err(slt_error)?; + let value = self.lower_slt(&arena, node)?; + // A record is not seeded: it has no random state, and seeding + // would draw from the creating process's RNG. + let size = self.constant64(u64::from(record.size)); + let object = self.heap_call( + ops::encode(ops::OBJECT_NEW, u64::from(sv::ir::Record::CLASS)), + &[size], + ); + for field in &record.fields { + if let Some(kind) = field.handle { + let offset = self.constant64(u64::from(field.offset)); + let kind = self.constant64(match kind { + HandleProperty::String => 0, + HandleProperty::Object => 1, + }); + self.heap_call(ops::OBJECT_HANDLE, &[object, offset, kind]); + } + } + let mut lsb = width; + for field in &record.fields { + lsb -= field.width as usize; + let part = if matches!(self.b.register(&value), RegisterType::Logic { .. }) { + self.b.alloc_logic(field.width as usize) + } else { + self.b.alloc_bit(field.width as usize, false) + }; + self.b.emit(SIRInstruction::Slice( + part, + value, + lsb, + field.width as usize, + )); + self.store_field(object, *field, part); + } + // An equal value keeps the handle it already has, so that + // storing it again leaves a container unchanged. + self.heap_call(ops::OBJECT_FINISH_RECORD, &[object]) } ObjectOp::Store(field) if field.four_state && self.m.four_state => { let object = self.handle(&args[0])?; let expr = self.hoist(&args[1])?; let value = self.eval(&expr, Some((field.width as usize, field.signed)))?; - let (value, mask) = self.container_split(value); - for (plane, bits) in [(0, value), (field.bytes(), mask)] { - let place = self.constant64( - u64::from(field.offset + plane) | u64::from(field.bytes()) << 32, - ); - let stored = self.complement(bits); - self.heap_call(ops::OBJECT_STORE, &[object, place, stored]); - } + self.store_field(object, *field, value); self.constant64(0) } ObjectOp::Store(field) => { @@ -223,7 +279,10 @@ impl Ff<'_, '_> { let (temp, name) = self.m.temp("object", width, signed, false); let kind = match op { ObjectOp::Container { .. } => unreachable!("handled by container_call"), - ObjectOp::New { .. } | ObjectOp::Copy => Some(celox_design::ValueKind::ObjRef), + ObjectOp::New { .. } | ObjectOp::Copy | ObjectOp::Box(_) => { + Some(celox_design::ValueKind::ObjRef) + } + ObjectOp::Unbox(_) => unreachable!("lowered to its own temporary"), ObjectOp::Load(field) => field.handle.map(|handle| match handle { HandleProperty::String => celox_design::ValueKind::StrRef, HandleProperty::Object => celox_design::ValueKind::ObjRef, @@ -251,6 +310,57 @@ impl Ff<'_, '_> { Ok(sv::ir::Expr::Ident(name)) } + /// The value of `field` of the object in 64-bit `object`: a register of + /// the field's width, 4-state for a 4-state field in 4-state simulation. + fn load_field(&mut self, object: RegisterId, field: sv::ir::ObjectField) -> RegisterId { + let opcode = if field.nullable { + ops::OBJECT_LOAD_NULLABLE + } else { + ops::OBJECT_LOAD + }; + let width = field.width as usize; + if field.four_state && self.m.four_state { + let [value, mask] = [0, field.bytes()].map(|plane| { + let offset = self.constant64(u64::from(field.offset + plane)); + let count = self.constant64(u64::from(field.bytes())); + let stored = self.heap_call(opcode, &[object, offset, count]); + self.complement(stored) + }); + return self.container_join(value, mask, width, true); + } + let offset = self.constant64(u64::from(field.offset)); + let count = self.constant64(u64::from(field.bytes())); + let loaded = self.heap_call(opcode, &[object, offset, count]); + let value = self.b.alloc_bit(width, field.signed); + self.b.emit(SIRInstruction::Slice(value, loaded, 0, width)); + value + } + + /// Store register `value` of `field`'s width into `field` of the object in + /// 64-bit `object`. + fn store_field(&mut self, object: RegisterId, field: sv::ir::ObjectField, value: RegisterId) { + let planes = if field.four_state && self.m.four_state { + let (value, mask) = self.container_split(value); + vec![ + (0, self.complement(value)), + (field.bytes(), self.complement(mask)), + ] + } else { + let known = self.b.alloc_bit(field.width as usize, false); + self.b + .emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, value)); + let wide = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Unary(wide, UnaryOp::Ident, known)); + vec![(0, wide)] + }; + for (plane, bits) in planes { + let place = + self.constant64(u64::from(field.offset + plane) | u64::from(field.bytes()) << 32); + self.heap_call(ops::OBJECT_STORE, &[object, place, bits]); + } + } + /// A 4-state property holds the complement of its value and mask planes, /// so the zeroed bytes of a new object read as X (IEEE 1800-2023 6.8). fn complement(&mut self, plane: RegisterId) -> RegisterId { diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index 0e0c65aa918..93d8e9cb3a5 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -81,6 +81,9 @@ pub struct Heap { next_object: Handle, containers: HashMap>, container_lookup: HashMap, Handle>, + /// Structure records by their contents, see [`ops::OBJECT_FINISH_RECORD`]. + #[serde(default)] + record_lookup: HashMap, /// The first heap operation error since the runtime last checked. fault: Option, /// Entries below this handle are never collected. @@ -112,6 +115,7 @@ impl Heap { next_object: NULL + 1, containers: HashMap::default(), container_lookup: HashMap::default(), + record_lookup: HashMap::default(), fault: None, pinned: 1, created: 0, @@ -241,6 +245,8 @@ impl Heap { self.containers.retain(|handle, _| objects.contains(handle)); self.container_lookup .retain(|_, handle| objects.contains(handle)); + self.record_lookup + .retain(|_, handle| objects.contains(handle)); // No buffer outlives the kernel that built it. self.buffers.clear(); self.free_buffers.clear(); diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index f42213cff1e..f094190c86a 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -79,7 +79,36 @@ impl std::fmt::Display for Fault { } } +/// The contents of a structure record: its bytes and handle fields. +pub(crate) type RecordContents = (Box<[u8]>, Vec<(u32, HandleKind)>); + impl Heap { + /// The handle of the record with the contents of the finished `record`, + /// so that equal values of an unpacked structure have one handle, as + /// equal strings and containers do: `null` for the default value, whose + /// bytes are all zero (a `null` record reads as its members' defaults). + /// A record is never written after it is finished. + pub fn finish_record(&mut self, record: Handle) -> Handle { + let Some(object) = self.objects.get(&record) else { + return record; + }; + if object.bytes.iter().all(|&byte| byte == 0) { + self.objects.remove(&record); + return NULL; + } + let contents = (object.bytes.clone(), object.handles.clone()); + match self.record_lookup.get(&contents) { + Some(&canonical) if canonical != record && self.objects.contains_key(&canonical) => { + self.objects.remove(&record); + canonical + } + _ => { + self.record_lookup.insert(contents, record); + record + } + } + } + /// A new object of `class` with `size` zeroed bytes. pub fn new_object(&mut self, class: u32, size: usize) -> Handle { let handle = self.next_object; @@ -335,6 +364,28 @@ mod tests { assert_eq!(heap.take_fault(), None); } + #[test] + fn equal_records_share_one_handle_until_collected() { + let mut heap = Heap::new(); + let record = |heap: &mut Heap, value: u64| { + let record = heap.new_object(u32::MAX, 8); + heap.declare_handle(record, 0, HandleKind::String); + heap.store(record, 4, 4, value); + heap.finish_record(record) + }; + let first = record(&mut heap, 1); + let second = record(&mut heap, 1); + let other = record(&mut heap, 2); + assert_eq!(first, second); + assert_ne!(first, other); + assert_eq!(heap.objects.len(), 2); + assert_eq!(record(&mut heap, 0), NULL); + assert_eq!(heap.objects.len(), 2); + heap.collect([Root::object(other)]); + assert_eq!(heap.record_lookup.len(), 1); + assert_ne!(record(&mut heap, 1), first); + } + #[test] fn null_dereferences_are_faults_that_read_zero() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index 333b3cc25cb..f1bc8b4cbe4 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -91,6 +91,12 @@ pub const OBJECT_RANDOMIZE_INPUTS: u64 = 65; /// Constraint index is encoded in the parameter; set-all uses u32::MAX. pub const OBJECT_CONSTRAINT_MODE_GET: u64 = 66; pub const OBJECT_CONSTRAINT_MODE_SET: u64 = 67; +/// `load(record, offset, count)` of a structure record: `null` reads as +/// zero bytes without a fault. +pub const OBJECT_LOAD_NULLABLE: u64 = 68; +/// `finish(record)` of a structure record whose fields are all stored: the +/// handle of the one record with its contents, which may replace `record`. +pub const OBJECT_FINISH_RECORD: u64 = 69; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -196,6 +202,9 @@ impl Heap { 0 } OBJECT_LOAD => self.load(a as Handle, b as usize, c as usize), + OBJECT_LOAD_NULLABLE if a as Handle == crate::objects::NULL => 0, + OBJECT_LOAD_NULLABLE => self.load(a as Handle, b as usize, c as usize), + OBJECT_FINISH_RECORD => self.finish_record(a as Handle).into(), OBJECT_STORE => { self.store(a as Handle, b as u32 as usize, (b >> 32) as usize, c); 0 diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 8ea57e2326b..654368947f6 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2291,6 +2291,9 @@ struct ContainerType { key: Option, layout: system_functions::ContainerLayout, element: Type, + /// The record that holds an element of unpacked structure type which is + /// not kept as a flat value. + record: Option, } impl Type { diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index 2fbcb574320..e5db4c9ded0 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -87,9 +87,23 @@ pub(super) fn expr_is_two_state( Expr::Call { callee: Callee::Object(op), .. - } => { - !matches!(**op, ObjectOp::Container { op, layout } if !layout.two_state && (op.reduction().is_some() || matches!(op, ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal))) - } + } => match **op { + // A 4-state property or member of a record may hold X or Z. + ObjectOp::Load(field) => !field.four_state, + ObjectOp::Unbox(ref record) => !record.fields.iter().any(|field| field.four_state), + ObjectOp::Container { op, layout } => { + layout.two_state + || !(op.reduction().is_some() + || matches!( + op, + ContainerOp::Get + | ContainerOp::PopFront + | ContainerOp::PopBack + | ContainerOp::Equal + )) + } + _ => true, + }, Expr::Call { callee: Callee::Subroutine(name), .. diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index a7bdf10cb3c..72e88c35b85 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -1266,7 +1266,7 @@ fn out_of_block_definition( /// The layout of a property of type `ty` at the first aligned offset at or /// after `offset`. -fn field( +pub(super) fn field( state: &AnalysisState, ty: &Type, env: &HashMap, @@ -1303,6 +1303,7 @@ fn field( ty.kind(), TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit ), + nullable: false, }) } diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index 5c7aadc5856..8bea51bc93f 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -79,23 +79,30 @@ pub(super) fn with_dimensions( if matches!(base.kind(), TypeKind::Real | TypeKind::Shortreal) { return Err(unsupported("real dynamic container elements")); } - if base.unpacked_struct().is_some() { - return Err(unsupported("dynamic container of unpacked structures")); - } + let record = match base.unpacked_struct() { + Some(aggregate) => unpacked_structs::record(&tree.state, aggregate, &context.const_env)?, + None => None, + }; let shape = casts::expr_type_from_type(&tree.state, &base, &context.const_env) .ok_or_else(|| unsupported("dynamic container element type"))?; - if shape.width == 0 || shape.width > 64 { + if record.is_none() && (shape.width == 0 || shape.width > 64) { return Err(unsupported("dynamic container elements wider than 64 bits")); } let handle = match base.kind() { + // An element in a record is the record's handle. + _ if record.is_some() => Some(HandleProperty::Object), TypeKind::String => Some(HandleProperty::String), TypeKind::Object => Some(HandleProperty::Object), _ => None, }; let layout = ContainerLayout { kind, - width: shape.width as u32, - signed: shape.signed, + width: if record.is_some() { + classes::HANDLE_WIDTH as u32 + } else { + shape.width as u32 + }, + signed: shape.signed && record.is_none(), two_state: matches!(base.kind(), TypeKind::Bit | TypeKind::Process) || handle.is_some(), handle, }; @@ -108,6 +115,7 @@ pub(super) fn with_dimensions( key: index_type, layout, element: base, + record, })); Ok(ty) } @@ -251,8 +259,17 @@ fn element_value( "container element assignment".into() })?; } + if let Some(aggregate) = target.element.unpacked_struct() { + unpacked_structs::check_value(aggregate, id, native, tree, dims)?; + } let shape = procedural::dimensions_from_type(&target.element); let value = expression_binding::bind_value(id, native, tree, dims, Some(&shape))?; + if let Some(record) = &target.record { + return Ok(classes::object_call( + ObjectOp::Box(record.clone()), + vec![value], + )); + } Ok(if target.layout.handle == Some(HandleProperty::String) { expression_binding::string_operand(value, dims) } else { @@ -353,6 +370,11 @@ pub(super) fn value( )); } + if target.record.is_some() { + return Err(unsupported( + "comparison of dynamic containers of unpacked structures", + )); + } let op = match operator.as_str() { "==" | "!=" => ContainerOp::Equal, "===" | "!==" => ContainerOp::CaseEqual, @@ -391,24 +413,32 @@ pub(super) fn value( } _ => return Err(unsupported("dynamic container slice")), }; - Ok(Some(call( - ContainerOp::Get, - target.layout, - vec![ - expression_binding::value(*expression, native, tree, dims)?, - match index { - Some(index) => index_value(index, *expression, tree, dims, &target)?, - None => Expr::Binary { - left: Box::new(call( - ContainerOp::Size, - target.layout, - vec![expression_binding::value(*expression, native, tree, dims)?], - )), - op: BinaryOp::Sub, - right: Box::new(Expr::Literal("1".into())), + Ok(Some(element_read( + &target, + call( + ContainerOp::Get, + target.layout, + vec![ + expression_binding::value(*expression, native, tree, dims)?, + match index { + Some(index) => index_value(index, *expression, tree, dims, &target)?, + None => Expr::Binary { + left: Box::new(call( + ContainerOp::Size, + target.layout, + vec![expression_binding::value( + *expression, + native, + tree, + dims, + )?], + )), + op: BinaryOp::Sub, + right: Box::new(Expr::Literal("1".into())), + }, }, - }, - ], + ], + ), ))) } ExprKind::Call { .. } | ExprKind::Member { .. } => { @@ -444,6 +474,11 @@ pub(super) fn value( "sort" => ContainerOp::Sort, _ => ContainerOp::Rsort, }; + if op != ContainerOp::Reverse && target.element.unpacked_struct().is_some() { + return Err(unsupported( + "sorting unpacked structures requires a with expression", + )); + } if op != ContainerOp::Reverse && target.layout.handle == Some(HandleProperty::Object) { @@ -550,7 +585,14 @@ pub(super) fn value( args.push(index_value(id, *base, tree, dims, &target)?); } } - Ok(Some(call(op, target.layout, args))) + let value = call(op, target.layout, args); + Ok(Some( + if matches!(op, ContainerOp::PopFront | ContainerOp::PopBack) { + element_read(&target, value) + } else { + value + }, + )) } _ => Ok(None), } @@ -885,3 +927,200 @@ mod method_call_tests { } } } + +/// An element that `get` reads, as a whole value: the flat structure value +/// of a record element. +fn element_read(target: &ContainerType, get: Expr) -> Expr { + match &target.record { + Some(record) => classes::object_call(ObjectOp::Unbox(record.clone()), vec![get]), + None => get, + } +} + +/// The container and the element read of native expression `id` when it +/// reads an element of unpacked structure type (`q[i]`, `q.pop_front()`), +/// before a record element is unboxed. +fn struct_element( + id: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted, Expr)>> { + let id = expression_binding::ungroup(id, native); + let base = match &native.expression(id).kind { + ExprKind::Select { expression, .. } => *expression, + ExprKind::Call { .. } | ExprKind::Member { .. } => { + let callee = match &native.expression(id).kind { + ExprKind::Call { expression, .. } => *expression, + _ => id, + }; + match &native.expression(callee).kind { + ExprKind::Member { + expression, name, .. + } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") => *expression, + _ => return Ok(None), + } + } + _ => return Ok(None), + }; + let Some(target) = native_type(base, native, tree, dims)? else { + return Ok(None); + }; + if target.element.unpacked_struct().is_none() { + return Ok(None); + } + let Some(value) = value(id, native, tree, dims, false)? else { + return Ok(None); + }; + let raw = match value { + Expr::Call { + callee: Callee::Object(op), + mut args, + .. + } if matches!(*op, ObjectOp::Unbox(_)) => args + .pop() + .flatten() + .ok_or_else(|| unsupported("structure record read"))?, + value => value, + }; + Ok(Some((target, raw))) +} + +/// The unpacked structure type of native expression `id` when it reads a +/// container element of such a type. +pub(super) fn native_struct_element( + id: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted>> { + let id = expression_binding::ungroup(id, native); + let base = match &native.expression(id).kind { + ExprKind::Select { expression, .. } => *expression, + ExprKind::Call { expression, .. } => match &native.expression(*expression).kind { + ExprKind::Member { + expression, name, .. + } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") => *expression, + _ => return Ok(None), + }, + ExprKind::Member { + expression, name, .. + } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") => *expression, + _ => return Ok(None), + }; + Ok(native_type(base, native, tree, dims)? + .and_then(|target| target.element.unpacked_struct().cloned())) +} + +/// A member `e.m` (or `e.m.n`) of a container element `e` of unpacked +/// structure type: its type and its value. +pub(super) fn element_member( + id: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted> { + let mut names = Vec::new(); + let mut current = expression_binding::ungroup(id, native); + let element = loop { + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(current).kind + else { + return Ok(None); + }; + if separator != "." { + return Ok(None); + } + names.push(instances::normalize_identifier(&name.spelling)); + current = expression_binding::ungroup(*expression, native); + if native_struct_element(current, native, tree, dims)?.is_some() { + break current; + } + }; + names.reverse(); + let Some((target, raw)) = struct_element(element, native, tree, dims)? else { + return Ok(None); + }; + let aggregate = target + .element + .unpacked_struct() + .expect("a structure element") + .clone(); + // A path into a packed structure member selects its bits; a path + // through a class handle member continues as a property access. + let mut packed = Vec::new(); + let (member_type, leaves) = loop { + if let Some(found) = unpacked_structs::member_leaves(&aggregate, &names) { + break found; + } + let Some(name) = names.pop() else { + return Ok(None); + }; + packed.insert(0, name); + }; + if !packed.is_empty() && member_type.members.is_empty() { + return Ok(None); + } + let leaves_in_order = aggregate.leaves(); + let parts = leaves + .iter() + .map(|leaf| { + let index = leaves_in_order + .iter() + .position(|candidate| candidate.path == leaf.path) + .expect("a leaf of the structure"); + match &target.record { + Some(record) => { + classes::object_call(ObjectOp::Load(record.fields[index]), vec![raw.clone()]) + } + None => Expr::Select { + expr: Box::new(raw.clone()), + msb: ConstExpr::Literal((leaf.offset + leaf.width - 1).to_string()), + lsb: ConstExpr::Literal(leaf.offset.to_string()), + signed: leaf.r#type.is_signed, + }, + } + }) + .collect::>(); + // Each leaf is read from the element, which a pop or any other call + // with an effect (a subroutine, `$urandom`) would change. + if parts.len() > 1 && inlining::effectful(&raw) { + return Err(unsupported( + "structure member with several members of an element read with a side effect", + )); + } + let value = if member_type.unpacked_struct().is_some() { + Expr::Concat(parts) + } else { + parts.into_iter().next().expect("one leaf") + }; + let mut member_type = member_type; + let mut value = value; + for name in packed { + let Some(member) = member_type + .members + .iter() + .find(|member| member.name() == name) + .cloned() + else { + return Err(unsupported(format!("structure member `{name}`"))); + }; + if member.is_tagged() { + return Err(unsupported("tagged union member of a container element")); + } + let width = casts::expr_type_from_type(&tree.state, member.r#type(), &dims.const_env) + .ok_or_else(|| unsupported("structure member width"))? + .width; + value = Expr::Select { + expr: Box::new(value), + msb: ConstExpr::Literal((member.offset() + width - 1).to_string()), + lsb: ConstExpr::Literal(member.offset().to_string()), + signed: member.r#type().is_signed(), + }; + member_type = member.r#type().clone(); + } + Ok(Some((member_type, value))) +} diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 530288d7e7c..5829c89dd6d 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -579,7 +579,10 @@ pub(in crate::ast) fn bind_value( if let objects::Receiver::Handle(handle) = receiver { children.push((handle, None)); } + // The shapes of the formals, after `this` of a method + // that is not static, receive assignment patterns. let first = usize::from(receiver != objects::Receiver::Static); + let shapes = dimensions.subroutine_param_shapes.get(&name); for (position, arg) in args.iter().filter(|_| selection.is_none()).enumerate() { @@ -596,7 +599,12 @@ pub(in crate::ast) fn bind_value( tree, dimensions, )?; - children.push((value, None)); + let shape = shapes + .and_then(|shapes| shapes.get(first + position)) + .filter(|shape| shape.unpacked_struct.is_some()) + .cloned() + .map(Rc::new); + children.push((value, shape)); } ( Finish::MethodCall { @@ -945,6 +953,14 @@ pub(in crate::ast) fn bind_value( ); continue; } + ExprKind::Member { .. } + if containers::element_member(id, native, tree, dimensions)?.is_some() => + { + let (_, value) = containers::element_member(id, native, tree, dimensions)? + .expect("checked by the guard"); + values.push(value); + continue; + } ExprKind::Member { .. } if objects::aggregate_property(tree, id, native, dimensions)?.is_some() => { @@ -1680,9 +1696,40 @@ fn selected_value( { return Err(unsupported("bit-select or part-select of a real variable")); } - if let ExprKind::Concatenation(_) | ExprKind::Replication { .. } = native.expression(base).kind + // A select of a member of a container element reads the member first. + let element_member = if suffix.is_empty() { + None + } else { + containers::element_member(base, native, tree, dimensions)? + }; + if element_member.is_some() + || matches!( + native.expression(base).kind, + ExprKind::Concatenation(_) | ExprKind::Replication { .. } + ) { - let expr = bind_value(base, native, tree, dimensions, None)?; + let expr = match element_member { + Some((ty, value)) => { + // The select indices are offsets from bit 0, which only a + // `[N-1:0]` range declares. + let zero_based = match ty.packed_ranges() { + [range] => { + eval_ast_const_expr(&tree.state, range.right(), &dimensions.const_env) + == Some(0) + && eval_ast_const_expr(&tree.state, range.left(), &dimensions.const_env) + .is_some_and(|left| left >= 0) + } + _ => false, + }; + if !zero_based || ty.unpacked_struct().is_some() || !ty.members.is_empty() { + return Err(unsupported( + "select of a container element member that is not declared [N-1:0]", + )); + } + value + } + None => bind_value(base, native, tree, dimensions, None)?, + }; if suffix.len() != 1 { return Err(unsupported("concatenation select")); } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs index 0771dd19d61..ebe79bea067 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs @@ -119,6 +119,17 @@ pub(super) fn domain( } None => match objects::property(tree, id, native, dimensions)? { Some((property, _)) => scalar(&property.r#type), + // A member of a container element of unpacked structure + // type. + None if let Some((ty, _)) = containers::element_member( + ungroup(id, native), + native, + tree, + dimensions, + )? => + { + scalar(&ty) + } // A member of a packed struct. None => dimensions::operand_shape(id, tree, dimensions) .ok() 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 dc66344bd04..cbde300a9a2 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -46,6 +46,10 @@ pub(in crate::ast) fn native_class( if let Some(name) = unpacked_structs::native_member(ungroup(id, native), native, dimensions) { return dimensions.get(&name)?.class.clone(); } + // A class handle member of a container element of unpacked structure type. + if let Ok(Some((ty, _))) = containers::element_member(id, native, tree, dimensions) { + return ty.class().map(str::to_owned); + } let expression = native.expression(ungroup(id, native)); if let ExprKind::Select { expression, 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 0fadf8370fa..f740f2c6adc 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -179,6 +179,18 @@ pub(in crate::ast) fn native_string( } // `e.name` without parentheses (6.19.5.6, 6.19.5.7). ExprKind::Member { .. } if enum_name(tree, id, native, dimensions) => true, + // A string member of a container element of unpacked structure type. + ExprKind::Member { .. } + if containers::element_member(ungroup(id, native), native, tree, dimensions) + .ok() + .flatten() + .is_some() => + { + containers::element_member(ungroup(id, native), native, tree, dimensions) + .ok() + .flatten() + .is_some_and(|(ty, _)| ty.kind() == TypeKind::String) + } // A string member of an unpacked structure variable. ExprKind::Member { .. } if unpacked_structs::native_member(ungroup(id, native), native, dimensions) diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index 83296533343..c02141d6831 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -154,6 +154,7 @@ fn reads_only(callee: &Callee) -> bool { Callee::Object(op) => matches!( **op, ObjectOp::Load(_) + | ObjectOp::Unbox(_) | ObjectOp::Container { op: ContainerOp::Get | ContainerOp::Size | ContainerOp::Exists, .. diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index e194c29f6d3..b03fb5067f0 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -582,6 +582,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { native: (celox_sv_syntax::ExprId, celox_sv_syntax::ExprId), ) -> Result { let (left, right) = native; + if containers::element_member(left, self.tree.declarations(), self.tree, &self.dims)? + .is_some() + { + return Err(unsupported( + "assignment to a member of a dynamic container element", + )); + } if let Some(mut stmt) = containers::set(left, right, op, nonblocking, self.tree, &self.dims)? { @@ -1151,6 +1158,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { _ => return Err(unsupported("increment or decrement operator")), }; let native = self.tree.declarations(); + if containers::element_member(*expression, native, self.tree, &self.dims)?.is_some() { + return Err(unsupported( + "assignment to a member of a dynamic container element", + )); + } if let Some((property, receiver)) = expression_binding::object_property(self.tree, *expression, native, &self.dims)? { @@ -3214,6 +3226,7 @@ fn dispatch_body( signed: false, handle: None, four_state: false, + nullable: false, }), vec![this.clone()], ); diff --git a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs index 1262333ff4b..19536904eae 100644 --- a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs @@ -248,6 +248,9 @@ pub(in crate::ast) fn native_struct( .and_then(|parts| dims.get(&parts[0])?.unpacked_struct.clone()) { Some(aggregate) => Some(aggregate), + None if let Some((ty, _)) = containers::element_member(id, native, tree, dims)? => { + ty.unpacked_struct().cloned() + } // A class property of unpacked structure type. None => expression_binding::object_aggregate_property(tree, id, native, dims)? .and_then(|(aggregate, _, _)| aggregate.r#type.unpacked_struct().cloned()), @@ -271,6 +274,9 @@ pub(in crate::ast) fn native_struct( } if std::ptr::eq(native, tree.declarations()) => { patterns::typed_shape(id, tree, dims)?.and_then(|shape| shape.unpacked_struct) } + _ if containers::native_struct_element(id, native, tree, dims)?.is_some() => { + containers::native_struct_element(id, native, tree, dims)? + } // A method of the scope class hides a module function of its name, // as call binding resolves it. ExprKind::Call { expression, .. } => { @@ -448,3 +454,64 @@ pub(in crate::ast) fn leaf_parts(aggregate: &UnpackedStruct, value: &Expr) -> Op // A whole variable is one part per leaf. (parts.len() == aggregate.leaves().len()).then(|| parts.clone()) } + +/// The record that holds a container element of type `aggregate`, or `None` +/// when the element is kept as its flat value: at most 64 bits, with no +/// handle member and members that are all 2-state or all 4-state, so the +/// container's default element is the structure's default. +pub(in crate::ast) fn record( + state: &AnalysisState, + aggregate: &UnpackedStruct, + env: &HashMap, +) -> Converted> { + let leaves = aggregate.leaves(); + let two_state = |leaf: &Leaf| { + matches!( + leaf.r#type.kind, + TypeKind::Bit | TypeKind::String | TypeKind::Object | TypeKind::Process + ) + }; + let handles = leaves + .iter() + .any(|leaf| matches!(leaf.r#type.kind, TypeKind::String | TypeKind::Object)); + let uniform = leaves.iter().all(two_state) || !leaves.iter().any(two_state); + if aggregate.width() <= 64 && !handles && uniform { + return Ok(None); + } + let mut size = 0; + let mut fields = Vec::new(); + for leaf in &leaves { + let mut field = classes::field(state, &leaf.r#type, env, size)?; + field.nullable = true; + size = field.offset + field.storage(); + fields.push(field); + } + Ok(Some(crate::system_functions::Record { + size: size.max(1), + fields, + })) +} + +/// The member at `path` of `aggregate`, with its type and the leaves it +/// covers. +pub(in crate::ast) fn member_leaves( + aggregate: &UnpackedStruct, + path: &[String], +) -> Option<(Type, Vec)> { + let mut ty = None::<&Type>; + let mut current = aggregate; + for (index, name) in path.iter().enumerate() { + let member = current.member(name)?; + ty = Some(&member.r#type); + if index + 1 < path.len() { + current = member.r#type.unpacked_struct()?; + } + } + let ty = ty?.clone(); + let leaves = aggregate + .leaves() + .into_iter() + .filter(|leaf| leaf.path.starts_with(path)) + .collect(); + Some((ty, leaves)) +} diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index a0638827e7b..981586eb202 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -9,7 +9,7 @@ pub use crate::procedural::{ }; pub use crate::system_functions::{ ArrayQuery, Callee, ContainerKind, ContainerLayout, ContainerOp, HandleProperty, MemoryFormat, - ObjectField, ObjectOp, Radix, Severity, StringOp, SystemFunction, SystemTask, VcdTask, + ObjectField, ObjectOp, Radix, Record, Severity, StringOp, SystemFunction, SystemTask, VcdTask, }; /// A procedural statement of the analyzed IR. diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index d1c53dc514d..2502e6b3ad3 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -839,6 +839,27 @@ pub struct ObjectField { pub handle: Option, /// A 4-state value: its unknown-bit mask follows the value bytes. pub four_state: bool, + /// A member of a [`Record`]: `null` reads as the member's default. + pub nullable: bool, +} + +/// The layout of an immutable heap record that holds the value of an +/// unpacked structure (IEEE 1800-2023 7.2) as a container element: one +/// field per leaf member, first declared first. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Record { + pub size: u32, + pub fields: Vec, +} + +impl Record { + /// The run-time class of a record, which no class shares. + pub const CLASS: u32 = u32::MAX; + + /// Bits of the flat structure value. + pub fn width(&self) -> usize { + self.fields.iter().map(|field| field.width as usize).sum() + } } /// What a handle property refers to. @@ -1011,6 +1032,11 @@ pub enum ObjectOp { /// A new object of the class of the object in the argument, with a copy /// of its properties (IEEE 1800-2023 8.12). Copy, + /// A new record holding the flat structure value in the argument. + Box(Record), + /// The flat structure value of the record in the argument; `null` is + /// the default value. + Unbox(Record), } impl ObjectOp { @@ -1042,7 +1068,10 @@ impl ObjectOp { | Self::ModeSelected(_) => (32, false), Self::ModeGet(..) | Self::ConstraintModeGet(_) => (32, true), Self::Load(field) => (field.width as usize, field.signed), - Self::New { .. } | Self::ClassOf | Self::Store(_) | Self::Copy => (32, false), + Self::Unbox(record) => (record.width(), false), + Self::New { .. } | Self::ClassOf | Self::Store(_) | Self::Copy | Self::Box(_) => { + (32, false) + } } } } @@ -1069,6 +1098,8 @@ impl fmt::Display for ObjectOp { Self::ModeSelect(..) => "select random property", Self::ModeSelected(_) => "selected random property query", Self::Copy => "shallow copy", + Self::Box(_) => "structure record", + Self::Unbox(_) => "structure record read", }) } } diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 70155d7e067..5ea627f90fd 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -627,7 +627,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_integral_format_string` | execute | icarus | 1 | Icarus 13.0 compiles `$sformatf` with a `bit` vector variable as the format, then `vvp` stops: "$sformatf's first argument must be a string or a register." IEEE 1800-2023 21.3.3 reads the content of an integral format expression as the format; Verilator 5.052 gives the expected output, xezim 0.11.3 prints the format as a value (`sv_integral_format_string` in the xezim review). | | `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. | | `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). | -| `sv_icarus_unpacked_structs` | compile | icarus | 12 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | +| `sv_icarus_unpacked_structs` | compile | icarus | 16 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | | `sv_verilator_nested_struct_default` | execute | verilator | 1 | Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 ("5 0000 1" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101. | The `string_format` cases compare `$sformatf`, `$sformat` and `$swrite` with diff --git a/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest index ebf1175badc..096581f0eaa 100644 --- a/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest +++ b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest @@ -449,3 +449,132 @@ endmodule (top Top) (run_until 6000) (expect_output "x 1\no x\n[2999!] [2999] 3000\n")) + +(case container_elements + (source "unpacked_struct_containers.sv" #" +module Top(output bit done); + class Node; + string n; + function new(string n); + this.n = n; + endfunction + endclass + typedef struct { string name; string regex; } acs_t; + typedef struct { Node m_type; string m_type_name; } pair_t; + typedef struct { pair_t orig; string alias_name; } alias_t; + typedef struct { int read_time; int write_time; int unsigned read_count; } access_t; + typedef enum { NEVER, STARTED, FINISHED } state_e; + typedef struct { state_e state; bit ret_val; } info_t; + initial begin + acs_t q[$]; + acs_t s, t; + alias_t aliases[$]; + access_t access[string]; + access_t ar; + info_t states[int]; + info_t da[]; + Node a; + s.name = "foo"; + s.regex = ""; + q.push_back(s); + q.push_back('{name: "", regex: "b.*"}); + s.name = "changed"; + $display("size %0d %s|%s %s", q.size(), q[0].name, q[1].regex, q[$].regex); + while (q.size()) begin + t = q.pop_front(); + $display("acs %s|%s", t.name, t.regex); + end + a = new("A"); + aliases.push_back('{orig: '{a, "A"}, alias_name: "al"}); + $display("alias %s %s %s", aliases[0].orig.m_type.n, aliases[0].orig.m_type_name, + aliases[0].alias_name); + ar = access["x"]; + $display("miss %0d %0d %0d", ar.read_time, ar.read_count, access.exists("x")); + ar.read_count++; + ar.read_time = 5; + access["x"] = ar; + ar.read_count = 99; + $display("hit %0d %0d %0d", access["x"].read_count, access["x"].read_time, access.num()); + states[3] = '{STARTED, 1}; + $display("info %0d %0d %0d", states[3].state, states[3].ret_val, states[4].state); + da = new[2]; + da[1] = '{FINISHED, 1}; + $display("da %0d %0d %0d", da[0].state, da[1].state, da[1] == info_t'{FINISHED, 1}); + foreach (access[k]) $display("key %s %0d", k, access[k].read_count); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "size 2 foo|b.* b.*\nacs foo|\nacs |b.*\nalias A A al\nmiss 0 0 0\nhit 1 5 1\ninfo 1 1 0\nda 0 2 1\nkey x 1\n")) + +(case container_element_member_selects + (source "unpacked_struct_element_selects.sv" #" +module Top(output bit done); + typedef struct { int x, y; } inner_t; + typedef struct { inner_t inner; bit [7:0] data; string s; } element_t; + initial begin + element_t q[$]; + inner_t i; + int k; + q.push_back('{'{1, 2}, 8'hA5, "a"}); + q.push_back('{'{3, 4}, 8'h3C, "b"}); + k = 1; + $display("%h %h %b %0d", q[0].data[3:0], q[k].data[7:4], q[1].data[0], q[0].inner.y); + i = q[1].inner; + $display("%0d %0d %0d", i.x, i.y, q.size()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "5 3 0 2\n3 4 2\n")) + +(case container_element_four_state_defaults + (four_state) + (source "unpacked_struct_container_states.sv" #" +module Top(output bit done); + typedef struct { time t; int unsigned n; logic [3:0] l; } access_t; + typedef struct { logic [3:0] a; logic [3:0] b; } nibbles_t; + initial begin + access_t access[string]; + nibbles_t q[]; + access_t x; + x = access["missing"]; + $display("%0d %0d %b", x.t, x.n, x.l); + x.l = 4'b1z0x; + access["k"] = x; + $display("%0d %b", access["k"].t, access["k"].l); + q = new[2]; + q[0] = '{4'bx01z, 4'b0011}; + $display("%b %b %b", q[0].a, q[0].b, q[1].a); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "x 0 xxxx\nx 1z0x\nx01z 0011 xxxx\n")) + +(case container_records_survive_heap_collections + (source "unpacked_struct_container_heap.sv" #" +module Top(output int n); + typedef struct { string name; string regex; } acs_t; + logic clk = 0; + always #1 clk = ~clk; + acs_t names[$]; + acs_t byname[string]; + string number; + always @(posedge clk) begin + number.itoa(n); + names.push_back('{name: number, regex: {number, "*"}}); + if (names.size() > 3) void'(names.pop_front()); + byname[number] = '{name: {"n", number}, regex: ""}; + n = n + 1; + end + initial #6000 $display("%0d [%s] [%s] [%s] %0d", names.size(), names[0].name, names[$].regex, + byname["2999"].name, byname.num()); +endmodule +"#) + (top Top) + (run_until 6000) + (expect_output "3 [2997] [2999*] [n2999] 3000\n")) diff --git a/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json index 49cfe0947a9..f0921a6595b 100644 --- a/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json @@ -115,6 +115,98 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::container_element_four_state_defaults", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::container_element_member_selects", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::container_elements", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::container_records_survive_heap_collections", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index cf96d93d2dd..b4e804a0208 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2988,6 +2988,10 @@ "unpacked_structs::class_properties_inheritance_and_collections", "unpacked_structs::class_property_assignment_order", "unpacked_structs::class_property_four_state_members", + "unpacked_structs::container_element_four_state_defaults", + "unpacked_structs::container_element_member_selects", + "unpacked_structs::container_elements", + "unpacked_structs::container_records_survive_heap_collections", "unpacked_structs::four_state_members", "unpacked_structs::handle_members_survive_heap_collections", "unpacked_structs::initializers_results_and_defaults", diff --git a/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json index e2b3c126390..037e6d81c89 100644 --- a/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json @@ -67,6 +67,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "unpacked_structs::container_element_four_state_defaults", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::container_element_member_selects", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::container_elements", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::container_records_survive_heap_collections", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "four-state expectations", diff --git a/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json index 9da00089498..e368bcbaa51 100644 --- a/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json @@ -55,6 +55,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::container_element_four_state_defaults", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::container_element_member_selects", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::container_elements", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::container_records_survive_heap_collections", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs index 99cf93ba158..00b23d1619c 100644 --- a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs +++ b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs @@ -77,6 +77,42 @@ sv_backends! { assert_eq!(sim.get(value), BigUint::from(342u16)); } + fn container_elements_with_packed_and_process_members(sim) { + @setup { + let source = r#"module Top(output bit [3:0] code, output bit [7:0] header, + output bit null_process, output int changes); + timeunit 1ps / 1ps; + typedef struct packed { bit [3:0] code; bit [3:0] kind; } header_t; + typedef struct { header_t header; string s; } element_t; + typedef struct { process p; logic flag; } waiter_t; + typedef struct { string name; bit flag; } entry_t; + entry_t q[$]; + initial begin + element_t r[$]; + waiter_t w[]; + r.push_back('{8'hA5, "a"}); + code = r[0].header.code; + header = r[0].header; + w = new[1]; + null_process = w[0].p == null; + q.push_back('{"x", 0}); + #1 q[0] = '{"x", 1}; + end + initial begin + @(q[0].flag); + changes = 1; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top") + .four_state(true); + sim.run_until(5).unwrap(); + for (name, value) in [("code", 0xau8), ("header", 0xa5), ("null_process", 1), ("changes", 1)] { + let signal = sim.signal(name); + assert_eq!(sim.get(signal), BigUint::from(value), "{name}"); + } + } + fn constructors_in_structure_patterns(sim) { @setup { let source = r#"module Top(output bit ok); @@ -117,6 +153,65 @@ sv_backends! { assert_eq!(sim.get(first), BigUint::from(22u8)); assert_eq!(sim.get(second), BigUint::from(22u8)); } + fn unknown_record_members_and_properties_are_not_folded(sim) { + @setup { + let source = r#"module Top(output int value); + typedef struct { string name; logic flag; } row_t; + class H; + logic f; + endclass + initial begin + row_t q[$]; + row_t d[]; + H h; + h = new; + q.push_back('{name: "a", flag: 'x}); + value = 0; + if (q[0].flag || !q[0].flag) value += 1; + else value += 10; + if (h.f || !h.f) value += 100; + else value += 1000; + d = new[2]; + if ((d[0] == d[1]) || (d[0] != d[1])) value += 10000; + else value += 100000; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top") + .four_state(true); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(101010u32)); + } + fn equal_record_updates_preserve_event_waits(sim) { + @setup { + let source = r#"`timescale 1ns/1ns + module Top(output bit done, output int changes); + typedef struct { string name; int value; } row_t; + row_t q[$], d[]; + int count, before_count; + initial begin + q.push_back('{"a", 1}); + d = new[1]; + #1 before_count = count; + d[0] = d[0]; + d[0] = '{default: 0, name: ""}; + q[0] = q[0]; + q[0] = '{{"a"}, 1}; + #1 q = '{'{"a", 1}}; + #1 done = count == before_count; + q[0] = '{"b", 1}; + #1 changes = count - before_count; + end + always @(q or d) count = count + 1; + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(4).unwrap(); + let (done, changes) = (sim.signal("done"), sim.signal("changes")); + assert_eq!(sim.get(done), BigUint::from(1u8)); + assert_eq!(sim.get(changes), BigUint::from(1u8)); + } fn static_nested_string_initializers(sim) { @setup { let source = r#"module Top(output int n); @@ -154,6 +249,28 @@ sv_backends! { let out = sim.signal("out"); assert_eq!(sim.get(out), BigUint::from(71u8)); } + fn enumeration_methods_of_container_element_members(sim) { + @setup { + let source = r#"module Top(output bit done); + typedef enum { STARTED, FINISHED } state_e; + typedef struct { state_e state; string tag; } rec_t; + typedef struct { state_e state; int n; } flat_t; + initial begin + rec_t m[int]; + flat_t q[$]; + string s; + m[2] = '{STARTED, "x"}; + q.push_back('{FINISHED, 3}); + s = {m[2].state.name(), " ", q[0].state.name, " ", m[2].state.next().name()}; + done = s == "STARTED FINISHED FINISHED" && q[0].state.prev() == STARTED; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let done = sim.signal("done"); + assert_eq!(sim.get(done), BigUint::from(1u8)); + } fn redeclared_structure_properties_hide_their_members(sim) { @setup { let source = r#"module Top(output int value); @@ -205,6 +322,18 @@ sv_backends! { fn unpacked_struct_class_properties_inheritance_and_collections(sim) { @case "unpacked_structs::class_properties_inheritance_and_collections"; } + fn unpacked_struct_container_elements(sim) { + @case "unpacked_structs::container_elements"; + } + fn unpacked_struct_container_element_member_selects(sim) { + @case "unpacked_structs::container_element_member_selects"; + } + fn unpacked_struct_container_element_four_state_defaults(sim) { + @case "unpacked_structs::container_element_four_state_defaults"; + } + fn unpacked_struct_container_records_survive_heap_collections(sim) { + @case "unpacked_structs::container_records_survive_heap_collections"; + } } #[test] @@ -264,7 +393,34 @@ fn unsupported_and_illegal_uses_are_rejected() { "parameter i_t P = '{1, 0};", "parameter of unpacked structure type", ), - ("i_t q[$];", "dynamic container of unpacked structures"), + ( + "s_t q[$], r[$]; bit x; initial x = q == r;", + "comparison of dynamic containers of unpacked structures", + ), + ( + "i_t q[$]; initial q.sort();", + "sorting unpacked structures requires a with expression", + ), + ( + "s_t q[$]; initial begin q.push_back('{1, \"x\"}); q[0].a = 5; end", + "assignment to a member of a dynamic container element", + ), + ( + "s_t q[$]; initial begin q.push_back('{1, \"x\"}); q[0].a++; end", + "assignment to a member of a dynamic container element", + ), + ( + "typedef struct { bit [15:8] hi; string s; } h_t; h_t q[$]; bit x; initial x = q[0].hi[8];", + "select of a container element member that is not declared [N-1:0]", + ), + ( + "typedef struct { s_t inner; } n_t; n_t q[$]; s_t i; initial i = q.pop_front().inner;", + "structure member with several members of an element read with a side effect", + ), + ( + "typedef struct { s_t inner; } n_t; n_t q[$]; s_t i; initial i = q[$urandom_range(0, 1)].inner;", + "structure member with several members of an element read with a side effect", + ), ( "class C; static i_t v; endclass", "static class property of unpacked structure type", diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 96887cf304a..5c603abfd30 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -330,7 +330,8 @@ SystemVerilog emitted by Veryl. Unpacked structures (IEEE 1800-2023 7.2) may have integral, enumeration, `string`, class handle, packed structure and nested unpacked structure members, each keeping its own 2-state or 4-state type. Variables of such a -type may be module variables, procedural locals, class properties, and +type may be module variables, procedural locals, class properties, queue, +dynamic and associative array elements (`q[i].m` reads a member), and subroutine arguments of any direction and results. Members are read and written like variables of their type; a whole structure is assigned and compared with `==`, `!=`, `===` and `!==` against a value of the same type, chosen with `?:`, or built @@ -362,7 +363,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - Declarations: variable declaration initializers of members of an interface array, ANSI port default values, tagged unions, unpacked unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), `real`, and unpacked structs as ports, nets, parameters, static, `rand` or - `const` class properties, array or container elements, or with members that + `const` class properties, fixed-size array elements, or with members that are arrays, `real`, or have default values. - Sequential processes: `iff` qualifiers in `always_ff` event lists ([#452](https://github.com/celox-sim/celox/issues/452)), and in `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit @@ -484,8 +485,13 @@ including changes caused by ordering methods (9.4.2). Associative arrays cannot use ordering methods. Fixed-array ordering, `shuffle`, `with` expressions and iterator arguments remain unsupported. -Elements may be packed integral values up to 64 bits, strings or class -handles. Positional assignment patterns and element concatenations construct +Elements may be packed integral values up to 64 bits, strings, class +handles or [unpacked structures](#unpacked-structures); a missing +associative entry or a new dynamic array element of structure type has the +structure's default members. Containers of unpacked structures with a string +or handle member, or wider than 64 bits, are not compared with `==` or sorted +without `with`; a member of such an element is read, not written (assign +the whole element). Positional assignment patterns and element concatenations construct sequences; assignments between dynamic arrays and queues copy values and respect the destination queue's bound. Associative assignment requires the same key type. Equality (`==`, `!=`, `===`, `!==`) between equivalent container types compares contents, diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 06cf2f87910..a3c7d54a783 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -100,7 +100,7 @@ Common reasons a design needs changes are: and `iff` in `always_ff` event controls ([#452](https://github.com/celox-sim/celox/issues/452)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. - Non-ANSI module ports, wildcard `.*` connections, gate primitives and `bind`. -- `real`, unpacked structs in ports and containers, and several interface features. +- `real`, unpacked structs in ports and fixed-size arrays, and several interface features. The [complete limitations list](./systemverilog-reference#what-is-not-supported) includes narrower restrictions and tracking issues. Unsupported constructs diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index a7db5796460..6ae5d465d85 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -209,6 +209,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列挙型、`string`、 クラスハンドル、packed 構造体、入れ子の unpacked 構造体を使え、各メンバは自身の 2 値・4 値の型を保ちます。この型の変数は、モジュール変数、手続き内のローカル変数、クラスプロパティ、 +キュー・動的配列・連想配列の要素(`q[i].m` でメンバを読めます)、 任意の方向のサブルーチン引数と戻り値にできます。メンバはその型の変数と同じように 読み書きできます。構造体全体は、同じ型の値との代入と `==`・`!=`・`===`・`!==` による 比較、`?:` による選択、assignment pattern(`'{a, b}`、`'{m: v, default: d}`、 @@ -236,7 +237,7 @@ unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート式(`module m({a, b}, c[3:0], .p(d))` など、[#1953](https://github.com/celox-sim/celox/issues/1953))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、`real`、ポート・ネット・パラメータ・static / `rand` / `const` のクラスプロパティ・配列やコンテナの要素としての unpacked 構造体、配列・`real`・既定値を持つメンバ。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、`real`、ポート・ネット・パラメータ・static / `rand` / `const` のクラスプロパティ・固定長配列の要素としての unpacked 構造体、配列・`real`・既定値を持つメンバ。 - 順序回路のプロセス:`always_ff` のイベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 非同期リセットを持たない複数のエッジ。 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 62648c54789..b8bd36cd88b 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -94,7 +94,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 `always_ff` のイベント制御の `iff`([#452](https://github.com/celox-sim/celox/issues/452))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。 - 非 ANSI モジュールポート、ワイルドカード `.*` 接続、ゲートプリミティブ、`bind`。 -- `real`、ポート・コンテナの unpacked 構造体、interface の一部の機能。 +- `real`、ポート・固定長配列の unpacked 構造体、interface の一部の機能。 [制約の一覧](./systemverilog-reference#what-is-not-supported)に、より細かな条件と追跡 issue をまとめています。 未対応の構文は、構文名と追跡 issue を含む診断を返します。 From 9fd32cc71a055ea76670ed8d71e8602f89dfe0e3 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 19:36:37 +0900 Subject: [PATCH 4/5] feat(sv): support nested dynamic containers and class handle keys A dynamic container with several dynamic dimensions (`int m[string][$]`, `T m[C][C][E]`, `int grid[][]`) was rejected, as was an associative array indexed by a class (IEEE 1800-2023 7.4.5, 7.8.5), which UVM uses for its comparer, copier and recorder recursion state. An element of a container of containers is the inner container's handle. Containers are immutable heap values, so `m[a]` reads the inner container, an absent one being empty, and an update of an element's element, such as `m[a][b] = v`, `m[a].push_back(x)` or `m[a].delete(b)`, writes the updated inner container back into `m[a]`, and so on outwards. An element of container type takes a container value, so `grid[1] = new[3]` works. A class index is a handle; associative keys of object handles are traced by the heap collector (container parameter bit 46), so an object referred to only as a key stays alive. `foreach` and traversal methods take an index variable of the class type. sv-tests chapter-7/arrays/associative/class now passes in both state modes. Containers of fixed-size unpacked arrays stay unsupported. Icarus 13.0 rejects type-name indices; xezim 0.11.3 misreads two of the new cases, which the review retains. Change-Id: I54576c9fc206a0a46ff5a3e7a4782eaf5be449d3 --- conformance/sv-tests/expected.tsv | 4 +- .../src/lowering/ff/containers.rs | 115 +++++++++++++-- crates/celox-heap/src/containers.rs | 36 +++-- .../celox-sv-analyzer/src/ast/containers.rs | 139 +++++++++++++++--- .../src/ast/procedural/foreach.rs | 5 +- .../celox-sv-analyzer/src/system_functions.rs | 2 + crates/celox-test-suite/LIMITATIONS.md | 1 + .../src/sv/cases/containers.vtest | 130 ++++++++++++++++ .../repros/sv_icarus_nested_containers.sv | 16 ++ .../repros/sv_xezim_nested_containers.sv | 26 ++++ .../verification/sv/icarus.json | 1 + .../verification/sv/icarus/containers.json | 96 ++++++++++++ .../verification/sv/limitations.json | 20 +++ .../verification/sv/xezim.json | 1 + .../verification/sv/xezim/containers.json | 37 +++++ .../verification/xezim-review.json | 36 +++++ .../frontends/systemverilog/containers.rs | 27 ++++ docs/guide/systemverilog-reference.md | 13 +- 18 files changed, 658 insertions(+), 47 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_icarus_nested_containers.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_xezim_nested_containers.sv create mode 100644 crates/celox-test-suite/verification/sv/icarus/containers.json create mode 100644 crates/celox-test-suite/verification/sv/xezim/containers.json diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 6dbe602fca6..f845ed80d19 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1261,8 +1261,8 @@ chapter-7/arrays/associative/arguments.sv 2state fail chapter-7/arrays/associative/arguments.sv 4state fail chapter-7/arrays/associative/assignment.sv 2state pass chapter-7/arrays/associative/assignment.sv 4state pass -chapter-7/arrays/associative/class.sv 2state fail -chapter-7/arrays/associative/class.sv 4state fail +chapter-7/arrays/associative/class.sv 2state pass +chapter-7/arrays/associative/class.sv 4state pass chapter-7/arrays/associative/integral.sv 2state pass chapter-7/arrays/associative/integral.sv 4state pass chapter-7/arrays/associative/literals.sv 2state fail diff --git a/crates/celox-frontend-sv/src/lowering/ff/containers.rs b/crates/celox-frontend-sv/src/lowering/ff/containers.rs index b37f1933487..f186dd2b127 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/containers.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/containers.rs @@ -18,6 +18,13 @@ impl Ff<'_, '_> { .ok_or_else(|| unsupported("omitted container operand")) }) .collect::, _>>()?; + // An update of an element of an outer container reads that element + // and writes it back: evaluate the indices on the way once. + if op.mutates() + && let Some(receiver) = args.first_mut() + { + *receiver = self.freeze_receiver(receiver)?; + } let original_key_width = args .get(1) .and_then(|key| self.m.comparison_width(key, key)); @@ -41,9 +48,11 @@ impl Ff<'_, '_> { )?; } } + // An element of an outer container is written back through its + // read, whose indices `freeze_receiver` has evaluated. if !value_receiver && self.m.calls(&args[0]) - && !matches!(&args[0], sv::ir::Expr::Call { callee: sv::ir::Callee::Object(op), .. } if matches!(**op, sv::ir::ObjectOp::Load(_))) + && !matches!(&args[0], sv::ir::Expr::Call { callee: sv::ir::Callee::Object(op), .. } if matches!(**op, sv::ir::ObjectOp::Load(_) | sv::ir::ObjectOp::Container { op: Get, .. })) { args[0] = self.heap_operand( &args[0], @@ -85,10 +94,15 @@ impl Ff<'_, '_> { *arg = self.heap_operand(arg, context, kind)?; } } - let (kind, capacity, signed_key, string_key) = match layout.kind { - ContainerKind::Dynamic => (0, 0, false, false), - ContainerKind::Queue { capacity } => (1, capacity, false, false), - ContainerKind::Associative { signed, string, .. } => (2, 0, signed, string), + let (kind, capacity, signed_key, string_key, object_key) = match layout.kind { + ContainerKind::Dynamic => (0, 0, false, false, false), + ContainerKind::Queue { capacity } => (1, capacity, false, false, false), + ContainerKind::Associative { + signed, + string, + object, + .. + } => (2, 0, signed, string, object), }; let parameter = heap::parameter( layout.width, @@ -102,6 +116,7 @@ impl Ff<'_, '_> { capacity, signed_key, string_key, + object_key, ); let code = |opcode| encode(opcode, parameter); if op.reduction().is_some() { @@ -381,13 +396,7 @@ impl Ff<'_, '_> { let narrow = this.b.alloc_bit(32, false); this.b.emit(SIRInstruction::Slice(narrow, updated, 0, 32)); this.store(id, SIROffset::Static(0), 32, narrow); - let sv::ir::Expr::Ident(receiver) = receiver else { - return Err(unsupported("container receiver must be a variable")); - }; - this.assign( - &sv::ir::LValue::Ident(receiver), - &sv::ir::Expr::Ident(updated_name), - ) + this.container_write_back(&receiver, sv::ir::Expr::Ident(updated_name)) })?; } zero @@ -402,6 +411,88 @@ impl Ff<'_, '_> { Ok(sv::ir::Expr::Ident(name)) } + /// `receiver` with the indices of the outer containers it reads, and the + /// objects of their properties, evaluated into temporaries. + fn freeze_receiver( + &mut self, + receiver: &sv::ir::Expr, + ) -> Result { + let sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(op), + args, + arg_order, + } = receiver + else { + return Ok(receiver.clone()); + }; + let frozen = match **op { + sv::ir::ObjectOp::Container { + op: ContainerOp::Get, + .. + } => { + let [Some(outer), Some(index)] = args.as_slice() else { + return Ok(receiver.clone()); + }; + let outer = self.freeze_receiver(outer)?; + let index = self.hoist(index)?; + vec![Some(outer), Some(index)] + } + sv::ir::ObjectOp::Load(_) => { + let [Some(owner)] = args.as_slice() else { + return Ok(receiver.clone()); + }; + vec![Some(self.hoist(owner)?)] + } + _ => return Ok(receiver.clone()), + }; + Ok(sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(op.clone()), + args: frozen, + arg_order: arg_order.clone(), + }) + } + + /// Store the updated container `updated` where `receiver` read it: a + /// variable, or an element of an outer container (`m[a]` of `m[a][b]`), + /// which is set in turn (IEEE 1800-2023 7.4.5). + fn container_write_back( + &mut self, + receiver: &sv::ir::Expr, + updated: sv::ir::Expr, + ) -> Result<(), sv::AnalyzerError> { + match receiver { + sv::ir::Expr::Ident(name) => { + self.assign(&sv::ir::LValue::Ident(name.clone()), &updated) + } + sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(op), + args, + .. + } if matches!( + **op, + sv::ir::ObjectOp::Container { + op: ContainerOp::Get, + .. + } + ) => + { + let sv::ir::ObjectOp::Container { layout, .. } = **op else { + unreachable!("matched a container read") + }; + let [Some(outer), Some(index)] = args.as_slice() else { + return Err(unsupported("container element receiver")); + }; + self.container_call( + ContainerOp::Set, + layout, + &[Some(outer.clone()), Some(index.clone()), Some(updated)], + )?; + Ok(()) + } + _ => Err(unsupported("container receiver must be a variable")), + } + } + fn container_reduction( &mut self, op: ContainerOp, diff --git a/crates/celox-heap/src/containers.rs b/crates/celox-heap/src/containers.rs index 127528da42a..5ab65599b27 100644 --- a/crates/celox-heap/src/containers.rs +++ b/crates/celox-heap/src/containers.rs @@ -35,7 +35,9 @@ pub const RSORT: u64 = 99; /// The operation parameter encodes the element width (bits 0..6), whether /// it is two-state (7), its handle kind (8..9: none/string/object), container /// kind (10..11: dynamic/queue/associative), queue capacity (12..43, 0 means -/// unbounded), and associative key ordering (44 signed, 45 string). +/// unbounded), associative key ordering (44 signed, 45 string), and whether +/// associative keys are object handles that the collector traces (46). +#[allow(clippy::too_many_arguments)] pub const fn parameter( width: u32, two_state: bool, @@ -44,6 +46,7 @@ pub const fn parameter( capacity: u32, signed_key: bool, string_key: bool, + object_key: bool, ) -> u64 { width as u64 | (two_state as u64) << 7 @@ -52,6 +55,7 @@ pub const fn parameter( | (capacity as u64) << 12 | (signed_key as u64) << 44 | (string_key as u64) << 45 + | (object_key as u64) << 46 } #[derive(Clone, Copy)] @@ -171,19 +175,33 @@ impl Heap { let Some(container) = self.containers.get(&handle) else { return Vec::new(); }; + let mut roots = Vec::new(); + // Object keys of an associative array keep their objects alive. + if container.layout & (1 << 46) != 0 + && let Contents::Associative(v) = &container.contents + { + roots.extend(v.keys().filter_map(|key| match key { + Key::Integer(handle) => Some(Root { + kind: crate::HandleKind::Object, + handle: *handle as Handle, + }), + Key::String(_) => None, + })); + } let kind = match (container.layout >> 8) & 3 { 1 => crate::HandleKind::String, 2 => crate::HandleKind::Object, - _ => return Vec::new(), + _ => return roots, }; let root = |element: &Element| Root { kind, handle: element.value as Handle, }; match &container.contents { - Contents::Sequence(v) => v.iter().map(root).collect(), - Contents::Associative(v) => v.values().map(root).collect(), + Contents::Sequence(v) => roots.extend(v.iter().map(root)), + Contents::Associative(v) => roots.extend(v.values().map(root)), } + roots } /// Execute a container helper. Indices have already undergone language /// conversion; invalid four-state indices use an out-of-range sentinel. @@ -435,7 +453,7 @@ mod tests { #[test] fn completed_updates_intern_values_and_collection_releases_lookup_entries() { let mut heap = Heap::new(); - let p = parameter(8, true, 0, 0, 0, false, false); + let p = parameter(8, true, 0, 0, 0, false, false, false); let a = call(&mut heap, NEW, p, 2, 0, 0); let b = call(&mut heap, SET, p, a, 0, 7); let b = call(&mut heap, SET_MASK, p, b, 0, 0); @@ -454,7 +472,7 @@ mod tests { #[test] fn resize_copy_delete_and_four_state_defaults() { let mut heap = Heap::new(); - let p = parameter(32, false, 0, 0, 0, false, false); + let p = parameter(32, false, 0, 0, 0, false, false, false); let a = call(&mut heap, NEW, p, 2, 0, 0); assert_eq!(call(&mut heap, GET_MASK, p, a, 0, 0), u32::MAX as u64); let b = call(&mut heap, SET, p, a, 0, 42); @@ -470,7 +488,7 @@ mod tests { #[test] fn bounded_queue_insert_and_value_copies() { let mut heap = Heap::new(); - let p = parameter(8, true, 0, 1, 2, false, false); + let p = parameter(8, true, 0, 1, 2, false, false, false); let a = call(&mut heap, INSERT, p, 0, 0, 10); let b = call(&mut heap, INSERT, p, a, 0, 20); let c = call(&mut heap, INSERT, p, b, 0, 30); @@ -484,7 +502,7 @@ mod tests { #[test] fn ordering_interns_unchanged_values_and_retains_nested_string_roots() { let mut heap = Heap::new(); - let p = parameter(32, true, 1, 1, 0, false, false); + let p = parameter(32, true, 1, 1, 0, false, false, false); let z = heap.intern(b"z") as u64; let a = heap.intern(b"a") as u64; let first = call(&mut heap, INSERT, p, 0, 0, z); @@ -509,7 +527,7 @@ mod tests { #[test] fn associative_order_and_gc_follow_element_handles() { let mut heap = Heap::new(); - let p = parameter(32, true, 1, 2, 0, true, false); + let p = parameter(32, true, 1, 2, 0, true, false, false); let string = heap.intern(b"live"); let a = call(&mut heap, SET, p, 0, 3, string as u64); let b = call(&mut heap, SET, p, a, (-2i64) as u64, string as u64); diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index 8bea51bc93f..6d4844a95a9 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -34,10 +34,17 @@ pub(super) fn with_dimensions( DimensionKind::Index(id) => { let key_type = match &tree.declarations().expression(id).kind { ExprKind::Type(id) => type_binding::bind(*id, tree, context)?, - ExprKind::Name(name) => context - .type_aliases - .get(&instances::normalize_identifier(&name.spelling)) - .cloned(), + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + match context.type_aliases.get(&name) { + Some(ty) => Some(ty.clone()), + // A class: the index is an object handle (IEEE + // 1800-2023 7.8.5). + None if context.get(&name).is_none() => classes::resolve(tree, &name) + .and_then(|class| classes::handle_type(tree, &class)), + None => None, + } + } _ => None, }; match key_type { @@ -45,21 +52,24 @@ pub(super) fn with_dimensions( Some(ty) => { index_type = Some(ty.clone()); let string = ty.kind() == TypeKind::String; + let object = ty.kind() == TypeKind::Object && ty.container.is_none(); let shape = casts::expr_type_from_type(&tree.state, &ty, &context.const_env) .ok_or_else(|| unsupported("associative index type"))?; if !string + && !object && (!matches!(ty.kind(), TypeKind::Bit | TypeKind::Logic | TypeKind::Reg) || shape.width > 64 || !ty.unpacked_ranges.is_empty()) { return Err(unsupported( - "associative indices require strings or integral types up to 64 bits", + "associative indices require strings, class handles or integral types up to 64 bits", )); } Some(ContainerKind::Associative { key_width: shape.width as u32, - signed: shape.signed, + signed: shape.signed && !object, string, + object, }) } } @@ -73,8 +83,17 @@ pub(super) fn with_dimensions( constant_binding::bind_unpacked_ranges(dims, tree, context)?, )); }; - if dims.len() != 1 || base.container.is_some() || !base.unpacked_ranges.is_empty() { - return Err(unsupported("multidimensional dynamic container")); + // `T a[x][y]`: each element of `a` is a container `T [y]` (IEEE + // 1800-2023 7.4.5, 7.8), held by its handle like any container value. + let base = if dims.len() > 1 { + with_dimensions(base, &dims[1..], tree, context)? + } else { + base + }; + if base.container.is_none() && dims.len() > 1 || !base.unpacked_ranges.is_empty() { + return Err(unsupported( + "dynamic container of fixed-size unpacked arrays", + )); } if matches!(base.kind(), TypeKind::Real | TypeKind::Shortreal) { return Err(unsupported("real dynamic container elements")); @@ -89,8 +108,8 @@ pub(super) fn with_dimensions( return Err(unsupported("dynamic container elements wider than 64 bits")); } let handle = match base.kind() { - // An element in a record is the record's handle. - _ if record.is_some() => Some(HandleProperty::Object), + // An element in a record, or a nested container, is a handle. + _ if record.is_some() || base.container.is_some() => Some(HandleProperty::Object), TypeKind::String => Some(HandleProperty::String), TypeKind::Object => Some(HandleProperty::Object), _ => None, @@ -141,6 +160,40 @@ pub(super) fn native_type( { return Ok(shape.container.clone()); } + // An element popped from a queue of containers. + let callee = match &native + .expression(expression_binding::ungroup(id, native)) + .kind + { + ExprKind::Call { expression, .. } => Some(*expression), + ExprKind::Member { .. } => Some(expression_binding::ungroup(id, native)), + _ => None, + }; + if let Some(callee) = callee + && let ExprKind::Member { + expression, name, .. + } = &native.expression(callee).kind + && matches!(name.spelling.as_str(), "pop_front" | "pop_back") + && let Some(outer) = native_type(*expression, native, tree, dims)? + && let Some(inner) = outer.element.container.clone() + { + return Ok(Some(inner)); + } + // An element of a container of containers, `m[a]` of `m[a][b]`. + if let ExprKind::Select { + expression, + dimension, + } = &native + .expression(expression_binding::ungroup(id, native)) + .kind + && matches!( + dimension.kind, + DimensionKind::Index(_) | DimensionKind::Queue(None) + ) + && let Some(outer) = native_type(*expression, native, tree, dims)? + { + return Ok(outer.element.container.clone()); + } Ok(None) } @@ -248,6 +301,11 @@ fn element_value( target: &ContainerType, ) -> Converted { let native = tree.declarations(); + // An element that is itself a container takes a container value, as an + // assignment to a container variable does. + if let Some(inner) = target.element.container.as_deref() { + return assignment(id, tree, dims, inner); + } if native_type(id, native, tree, dims)?.is_some() { return Err(unsupported("container used as an element")); } @@ -284,6 +342,17 @@ fn index_value( target: &ContainerType, ) -> Converted { let native = tree.declarations(); + // A class index takes handles of its class or a derived one. + if let Some(class) = target.key.as_ref().and_then(|key| key.class()).filter(|_| { + matches!( + target.layout.kind, + ContainerKind::Associative { object: true, .. } + ) + }) { + expression_binding::check_handle_assignment(tree, id, native, dims, class, || { + "associative array index".into() + })?; + } if matches!( target.layout.kind, ContainerKind::Associative { string: true, .. } @@ -375,6 +444,10 @@ pub(super) fn value( "comparison of dynamic containers of unpacked structures", )); } + // The elements are inner containers' handles, not their values. + if target.element.container.is_some() { + return Err(unsupported("comparison of nested dynamic containers")); + } let op = match operator.as_str() { "==" | "!=" => ContainerOp::Equal, "===" | "!==" => ContainerOp::CaseEqual, @@ -567,10 +640,15 @@ pub(super) fn value( let shape = dims .get(&instances::normalize_identifier(&name.spelling)) .ok_or_else(|| unsupported("associative traversal index variable"))?; - if let ContainerKind::Associative { string, .. } = target.layout.kind + // The index variable of a class index is passed by + // reference, so it has the index's class (IEEE 1800-2023 + // 7.9.4). + let key_class = target.key.as_ref().and_then(|key| key.class()); + if let ContainerKind::Associative { string, object, .. } = target.layout.kind && (shape.string != string || shape.container.is_some() - || !shape.unpacked.is_empty()) + || !shape.unpacked.is_empty() + || object && shape.class.as_deref() != key_class) { return Err(unsupported( "incompatible associative traversal index variable", @@ -647,15 +725,23 @@ fn query( if arguments.len() != 1 { return Err(unsupported("dynamic array query arguments")); } + // A container of containers has one unpacked dimension per level. + let mut innermost = target.clone(); + let mut unpacked = 1; + while let Some(inner) = innermost.element.container.clone() { + innermost = inner; + unpacked += 1; + } return Ok(Some(Expr::Literal( if name.spelling == "$unpacked_dimensions" { - 1 + unpacked } else { - 1 + if target.layout.handle.is_some() { - 0 - } else { - target.element.packed_ranges.len() - } + unpacked + + if innermost.layout.handle.is_some() { + 0 + } else { + innermost.element.packed_ranges.len() + } } .to_string(), ))); @@ -797,7 +883,22 @@ mod tests { fn unsupported_container_forms_fail_before_lowering() { for (source, expected) in [ ("module Top; bit[127:0] a[]; endmodule", "wider than 64"), - ("module Top; int a[][]; endmodule", "multidimensional"), + ( + "module Top; int a[][2]; endmodule", + "dynamic container of fixed-size unpacked arrays", + ), + ( + "module Top; int a[][], b[][]; bit x; initial x = a == b; endmodule", + "comparison of nested dynamic containers", + ), + ( + "module Top; class A; endclass class B; endclass int m[A]; B b; initial begin b = new; m[b] = 1; end endmodule", + "associative array index", + ), + ( + "module Top; class A; endclass class B; endclass int m[A]; B k; initial void'(m.first(k)); endmodule", + "incompatible associative traversal index variable", + ), ("module Top; int a[*]; endmodule", "wildcard"), ( "module Top; int a[string]; initial a[123] = 7; endmodule", diff --git a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs index 4a780198d6b..89f7e64e879 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs @@ -47,9 +47,12 @@ impl BodyBuilder<'_, '_, '_> { key_width, signed, string, + object, } = container.layout.kind { - index_type = if string { + index_type = if object { + container.key.clone().expect("a class index type") + } else if string { type_binding::builtin_type("string", None).expect("string is a builtin type") } else { let mut ty = int_type(); diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 2502e6b3ad3..41acaf58a43 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -901,6 +901,8 @@ pub enum ContainerKind { key_width: u32, signed: bool, string: bool, + /// Keys are class handles, which keep their objects alive. + object: bool, }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 5ea627f90fd..106251a144e 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -628,6 +628,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. | | `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). | | `sv_icarus_unpacked_structs` | compile | icarus | 16 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | +| `sv_icarus_nested_containers` | compile | icarus | 4 | Icarus 13.0 rejects an associative array whose index type is a type name ("Type names are not valid expressions here."), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays ("Sorry: Dynamic array of type `dynamic array of ...` is not yet supported."), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases. | | `sv_verilator_nested_struct_default` | execute | verilator | 1 | Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 ("5 0000 1" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101. | The `string_format` cases compare `$sformatf`, `$sformat` and `$swrite` with diff --git a/crates/celox-test-suite/src/sv/cases/containers.vtest b/crates/celox-test-suite/src/sv/cases/containers.vtest index 52d1985d914..869b0a22384 100644 --- a/crates/celox-test-suite/src/sv/cases/containers.vtest +++ b/crates/celox-test-suite/src/sv/cases/containers.vtest @@ -957,3 +957,133 @@ endmodule "#) (four_state) (top Top) (run_until 0) (assert_eq flags 255)) + +(case nested_containers_and_class_keys + (source "nested_containers.sv" #" +module Top(output bit done); + class Obj; + string n; + function new(string n); + this.n = n; + endfunction + endclass + typedef enum { NEVER, STARTED, FINISHED } state_e; + typedef enum { DEEP, SHALLOW } policy_e; + typedef struct { state_e state; bit ret_val; } info_t; + class Comparer; + info_t m[Obj][Obj][policy_e]; + state_e s[Obj][Obj]; + function void start(Obj l, Obj r); + m[l][r][DEEP] = '{STARTED, 0}; + endfunction + endclass + initial begin + Comparer c; + Obj a, b, k; + int grid[][]; + c = new; + a = new("a"); + b = new("b"); + c.start(a, b); + $display("%0d %0d %0d", c.m[a][b][DEEP].state, c.m[a][b][DEEP].ret_val, c.m.exists(a)); + c.m[a][b][DEEP] = '{FINISHED, 1}; + c.m[b][a][SHALLOW] = '{STARTED, 1}; + $display("%0d %0d %0d %0d", c.m[a][b][DEEP].state, c.m[a][b][DEEP].ret_val, c.m.num(), + c.m[b][a][SHALLOW].ret_val); + c.s[a][b] = FINISHED; + $display("%0d %0d", c.s[a][b], c.s[b][a]); + if (c.m.first(k)) $display("first %s", k.n); + foreach (c.m[x]) $display("key %s", x.n); + c.m.delete(); + grid = new[2]; + grid[1] = new[3]; + grid[1][2] = 7; + $display("%0d %0d", c.m.num(), grid[1][2]); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "1 0 1\n2 1 2 1\n2 0\nfirst a\nkey a\nkey b\n0 7\n")) + +(case methods_of_nested_container_elements + (source "nested_container_methods.sv" #" +module Top(output bit done); + initial begin + int m[string][int]; + int counts[string][$]; + int grid[][]; + m["a"][1] = 10; + m["a"][2] = 20; + m["b"][3] = 30; + $display("%0d %0d %0d %0d", m.num(), m["a"].num(), m["a"].exists(2), m["b"].exists(2)); + m["a"].delete(1); + $display("%0d %0d", m["a"].num(), m.num()); + counts["x"].push_back(3); + counts["x"].push_back(4); + counts["y"].push_back(5); + $display("%0d %0d %0d %0d", counts["x"].size(), counts["x"][1], counts["y"][0], + counts["z"].size()); + grid = new[2]; + grid[1] = new[3]; + $display("%0d %0d %0d", grid.size(), grid[0].size(), grid[1].size()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "2 2 1 0\n1 2\n2 4 5 0\n2 0 3\n")) + +(case nested_updates_evaluate_indices_once + (source "nested_updates.sv" #" +module Top(output bit done); + int i; + function automatic int next_index(); + i++; + return i; + endfunction + initial begin + int m[int][$]; + int grid[][]; + m[next_index()].push_back(7); + m[next_index()].push_back(8); + $display("%0d %0d %0d %0d %0d", m.num(), m[1].size(), m[1][0], m[2][0], i); + grid = new[2]; + grid[1] = new[2]; + $display("%0d %0d", $unpacked_dimensions(grid), $dimensions(grid)); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "2 1 7 8 2\n2 3\n")) + +(case class_keys_survive_heap_collections + (source "class_keys.sv" #" +module Top(output int n); + class Obj; + string n; + endclass + logic clk = 0; + always #1 clk = ~clk; + int seen[Obj]; + Obj last; + string number; + always @(posedge clk) begin + Obj o; + o = new; + number.itoa(n); + o.n = number; + seen[o] = n; + n = n + 1; + end + initial begin + #6000; + foreach (seen[k]) if (seen[k] == 2999) last = k; + $display("%0d [%s] %0d", seen.num(), last.n, seen[last]); + end +endmodule +"#) + (top Top) + (run_until 6000) + (expect_output "3000 [2999] 2999\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_icarus_nested_containers.sv b/crates/celox-test-suite/verification/repros/sv_icarus_nested_containers.sv new file mode 100644 index 00000000000..7b08e4e1ef6 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_icarus_nested_containers.sv @@ -0,0 +1,16 @@ +// Icarus 13.0 rejects an associative array whose index type is a type name, +// a class or a typedef ("Type names are not valid expressions here."), which +// IEEE 1800-2023 7.8 and 7.8.5 permit. +module top; + class Obj; + endclass + initial begin + int seen[Obj]; + int m[string][int]; + Obj a; + a = new; + seen[a] = 1; + m["a"][1] = 2; + $display("%0d %0d", seen[a], m["a"][1]); + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_xezim_nested_containers.sv b/crates/celox-test-suite/verification/repros/sv_xezim_nested_containers.sv new file mode 100644 index 00000000000..79c95022f20 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_xezim_nested_containers.sv @@ -0,0 +1,26 @@ +// xezim 0.11.3: first() of a class property that is an associative array of +// associative arrays indexed by class handles reports an empty array, and +// new[] assigned to an element of a dynamic array of dynamic arrays is lost +// (IEEE 1800-2023 7.8.5, 7.9.5, 7.5.1). Expected: "first 1 a" and "3 7". +module top; + class Obj; + string n; + endclass + class Holder; + int m[Obj][Obj]; + endclass + initial begin + Holder h; + int grid[][]; + Obj a, k; + h = new; + a = new; + a.n = "a"; + h.m[a][a] = 1; + $display("first %0d %s", h.m.first(k), k == null ? "-" : k.n); + grid = new[2]; + grid[1] = new[3]; + grid[1][2] = 7; + $display("%0d %0d", grid[1].size(), grid[1][2]); + end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index c10f9fe0aeb..b8f59525689 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -4,6 +4,7 @@ "icarus/always_comb.json", "icarus/class.json", "icarus/concurrent_assertions.json", + "icarus/containers.json", "icarus/fork.json", "icarus/fork_control.json", "icarus/fork_deferred.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/containers.json b/crates/celox-test-suite/verification/sv/icarus/containers.json new file mode 100644 index 00000000000..1cd085b2de7 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/containers.json @@ -0,0 +1,96 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_nested_containers.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_nested_containers", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "upstream": [] + }, + "name": "containers::class_keys_survive_heap_collections", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_nested_containers.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_nested_containers", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "upstream": [] + }, + "name": "containers::methods_of_nested_container_elements", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_nested_containers.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_nested_containers", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "upstream": [] + }, + "name": "containers::nested_containers_and_class_keys", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_nested_containers.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_nested_containers", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "upstream": [] + }, + "name": "containers::nested_updates_evaluate_indices_once", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index b4e804a0208..623ea0723a1 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -3018,5 +3018,25 @@ "unpacked_structs::assignment_patterns" ] } + }, + { + "id": "sv_icarus_nested_containers", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects an associative array whose index type is a type name (\"Type names are not valid expressions here.\"), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays (\"Sorry: Dynamic array of type `dynamic array of ...` is not yet supported.\"), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/repros/sv_icarus_nested_containers.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "containers::class_keys_survive_heap_collections", + "containers::methods_of_nested_container_elements", + "containers::nested_containers_and_class_keys", + "containers::nested_updates_evaluate_indices_once" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/xezim.json b/crates/celox-test-suite/verification/sv/xezim.json index ff2b063c499..f3f67567030 100644 --- a/crates/celox-test-suite/verification/sv/xezim.json +++ b/crates/celox-test-suite/verification/sv/xezim.json @@ -5,6 +5,7 @@ "xezim/binary_file_io.json", "xezim/class.json", "xezim/concurrent_assertions.json", + "xezim/containers.json", "xezim/distributions.json", "xezim/edges.json", "xezim/file_core.json", diff --git a/crates/celox-test-suite/verification/sv/xezim/containers.json b/crates/celox-test-suite/verification/sv/xezim/containers.json new file mode 100644 index 00000000000..e24ae9fb382 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/xezim/containers.json @@ -0,0 +1,37 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "containers::methods_of_nested_container_elements at 1035:3: expect_output: expected [50, 32, 50, 32, 49, 32, 48, 10, 49, 32, 50, 10, 50, 32, 52, 32, 53, 32, 48, 10, 50, 32, 48, 32, 51, 10], got [50, 32, 50, 32, 49, 32, 48, 10, 49, 32, 50, 10, 50, 32, 52, 32, 53, 32, 48, 10, 50, 32, 48, 32, 48, 10]", + "expectation": "Simulation", + "name": "containers::methods_of_nested_container_elements", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "containers::nested_containers_and_class_keys at 1007:3: expect_output: expected [49, 32, 48, 32, 49, 10, 50, 32, 49, 32, 50, 32, 49, 10, 50, 32, 48, 10, 102, 105, 114, 115, 116, 32, 97, 10, 107, 101, 121, 32, 97, 10, 107, 101, 121, 32, 98, 10, 48, 32, 55, 10], got [49, 32, 48, 32, 49, 10, 50, 32, 49, 32, 50, 32, 49, 10, 50, 32, 48, 10, 107, 101, 121, 32, 97, 10, 107, 101, 121, 32, 98, 10, 48, 32, 49, 10]", + "expectation": "Simulation", + "name": "containers::nested_containers_and_class_keys", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "containers::nested_updates_evaluate_indices_once at 1059:3: expect_output: expected [50, 32, 49, 32, 55, 32, 56, 32, 50, 10, 50, 32, 51, 10], got [50, 32, 48, 32, 48, 32, 48, 32, 54, 10, 49, 32, 50, 10]", + "expectation": "Simulation", + "name": "containers::nested_updates_evaluate_indices_once", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index 44e8a8d4db5..39f718bd0c6 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -794,6 +794,18 @@ "sv_rest-X89": { "title": "A whole class property of unpacked structure type is assigned member by member: a pattern reading the property sees members already written, and a receiver with a side-effecting index is evaluated per member", "standard": "IEEE 1800-2023 7.2, 10.9.2, 11.4.1" + }, + "sv_rest-X86": { + "title": "first() of a class property that is an associative array of associative arrays indexed by class handles reports an empty array", + "standard": "IEEE 1800-2023 7.8.5, 7.9.5" + }, + "sv_rest-X87": { + "title": "new[] assigned to an element of a dynamic array of dynamic arrays is lost", + "standard": "IEEE 1800-2023 7.5.1, 7.4.5" + }, + "sv_rest-X90": { + "title": "An update of an element of a nested container evaluates the outer index expression again, and $unpacked_dimensions/$dimensions of a dynamic array of dynamic arrays count one level", + "standard": "IEEE 1800-2023 7.4.5, 11.4.1, 20.7" } }, "cases": [ @@ -4651,6 +4663,30 @@ "classification": "xezim_bug", "bug": "sv_rest-X89", "note": "h.p = '{h.p.b, h.p.a} prints \"2 2\" instead of \"2 1\", and items[next_index()].p = '{7, 8} calls next_index() once per member, writing items[1].p.a and items[2].p.b, with i = 3 instead of 1." + }, + { + "suite": "sv", + "name": "containers::nested_containers_and_class_keys", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X86", + "note": "c.m.first(k) on the Obj-indexed property returns 0, so \"first a\" is missing; grid[1] = new[3] is also lost (sv_rest-X87), so grid[1][2] reads 1 instead of 7. Reproduced by verification/repros/sv_xezim_nested_containers.sv." + }, + { + "suite": "sv", + "name": "containers::methods_of_nested_container_elements", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X87", + "note": "grid[1] = new[3] leaves grid[1] empty, so grid[1].size() prints 0 instead of 3. Reproduced by verification/repros/sv_xezim_nested_containers.sv." + }, + { + "suite": "sv", + "name": "containers::nested_updates_evaluate_indices_once", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X90", + "note": "m[next_index()].push_back(7) calls next_index() three times per statement (i = 6 after two statements, elements lost), and $unpacked_dimensions(grid)/$dimensions(grid) of int grid[][] print 1 2 instead of 2 3." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/containers.rs b/crates/celox/tests/frontends/systemverilog/containers.rs index b9c99830c6d..343428e4ace 100644 --- a/crates/celox/tests/frontends/systemverilog/containers.rs +++ b/crates/celox/tests/frontends/systemverilog/containers.rs @@ -2,6 +2,10 @@ use super::*; sv_backends! { fn class_container_inheritance_static(sim) { @case "containers::class_container_inheritance_static"; } + fn nested_containers_and_class_keys(sim) { @case "containers::nested_containers_and_class_keys"; } + fn methods_of_nested_container_elements(sim) { @case "containers::methods_of_nested_container_elements"; } + fn nested_updates_evaluate_indices_once(sim) { @case "containers::nested_updates_evaluate_indices_once"; } + fn class_keys_survive_heap_collections(sim) { @case "containers::class_keys_survive_heap_collections"; } 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"; } @@ -41,6 +45,29 @@ sv_backends! { fn declaration_initializers_and_locals(sim) { @case "containers::declaration_initializers_and_locals"; } } +sv_backends! { + fn popped_nested_queue_elements_are_containers(sim) { + @setup { + let source = r#"module Top(output int value); + initial begin + int q[$][$]; + int row[$]; + row.push_back(4); + row.push_back(2); + q.push_back(row); + row = '{}; + row = q.pop_front(); + value = row.size() * 100 + row[0] * 10 + q.size(); + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("nested.sv"))], "Top"); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(240u8)); + } +} + sv_backends! { fn container_checkpoints_restore_all_three_kinds(sim) { @setup { diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 5c603abfd30..9f7812ef13b 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -31,7 +31,7 @@ synthesis and is tested at the design level. | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed and unpacked 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) | +| Dynamic containers | dynamic arrays, queues (including bounded queues), and associative arrays with integral, string or class handle keys, also nested (`int m[string][$]`, `T m[C][C][E]`); 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; text formatted by `$sformatf` / `$sformat` / `$swrite`. See [strings](#strings) | | Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types up to 64 bits (4-state properties start as X and keep X/Z bits), `string` and class handle types, unpacked structures of those types (see [unpacked structures](#unpacked-structures)), 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 | @@ -462,9 +462,14 @@ Dynamic arrays (`T a[]`) support `new[n]`, `new[n](a)`, `size()` and `delete()` (IEEE 1800-2023 7.5). Queues (`T q[$]`, `T q[$:N]`) support `size`, `insert`, `delete`, `push_front`, `push_back`, `pop_front` and `pop_back`. Queue indices may use `$` and `$+1`. -Associative arrays support integral keys up to 64 bits or `string` keys, -`num` / `size`, `exists`, `delete`, and `first` / `last` / `next` / `prev` -(7.8–7.10). Traversal leaves its index unchanged when no key is found. +Associative arrays support integral keys up to 64 bits, `string` keys or +class handle keys (7.8.5), which keep their objects alive; `num` / `size`, +`exists`, `delete`, and `first` / `last` / `next` / `prev` (7.8–7.10). +Traversal leaves its index unchanged when no key is found. A container +declared with several dynamic dimensions, `T m[a][b]`, holds containers as +elements: `m[a][b] = v` updates the inner container of `m[a]`, which reads as +empty when absent, and methods apply to an element (`m[a].exists(b)`). +`foreach` iterates one dimension at a time. The empty parentheses on zero-argument container methods are optional: `a.size`, `q.pop_front`, `map.num` and `map.delete` have the same behavior as From e0c060f866babd3cf1607a2a5577d04a6eda4cb1 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 01:59:43 +0900 Subject: [PATCH 5/5] feat(sv): pass unpacked structures by reference A `ref` or `const ref` formal of unpacked structure type was rejected, which blocks UVM: `uvm_reg_adapter::reg2bus(const ref uvm_reg_bus_op rw)` and `bus2reg(..., ref uvm_reg_bus_op rw)` are elaborated with every `uvm_pkg`. A structure is a set of member variables, so its reference formal is now one reference per member, bound to the matching member of the actual (IEEE 1800-2023 13.5.2): writes through the formal are seen at once in both directions, also across task suspensions. - The analyzer records the members of a structure formal in `SubroutineParam::leaves`. A reference formal gets no copy-in or copy-out. The body that dispatches a virtual method forwards the members, so a call through a pure virtual method binds the override's members to the caller's. - Actuals: structure variables, members that are structures, class properties of structure type and their members. A scalar member of a structure is now also an ordinary reference actual (`bump(x.a)`). - Type equivalence (6.22.2) compares structure types by identity, also for containers of structures (`ref s_t q[$]`). - `const ref` writes, nonblocking writes and fork uses are checked per member. - The frontend binds each member like a scalar reference. A concatenation assignment to members bound to class properties writes temporaries in their place, so every destination position is taken before any write, then stores each property. A formal bound to a property and passed on to an `output` or `inout` structure argument copies each member back. - A receiver with a side effect (a pop, `$urandom`, a call) is rejected for a structure property actual, as for its whole reads, since each member would evaluate it again. Tests cover callee whole assignment, patterns, comparisons and passing on by reference or value; enumeration, string, class handle and 4-state members; handle members across heap collections; pure virtual `reg2bus`/`bus2reg`; and a task holding the reference across delays. Verilator 5.052 rejects two cases that bind a class property in a function that constructs an object (`%Error-IMPURE`, also with a scalar `ref`). xezim 0.11.3 shows its known copy semantics and padded string properties. Icarus does not support unpacked structures. The docs state that structure members may not be dynamic containers. Change-Id: I41a3098eb3b4359ca618580fb4de6bff25676be4 --- crates/celox-frontend-sv/src/lowering/comb.rs | 25 ++ crates/celox-frontend-sv/src/lowering/ff.rs | 167 +++++++++++-- .../src/ast/const_functions.rs | 1 + .../src/ast/expression_binding/direct.rs | 2 +- .../src/ast/expression_binding/references.rs | 52 ++-- .../celox-sv-analyzer/src/ast/procedural.rs | 87 ++++--- .../src/ast/procedural/randomization.rs | 3 + .../src/ast/procedural/references.rs | 13 +- crates/celox-sv-analyzer/src/ast/scope.rs | 1 + crates/celox-sv-analyzer/src/procedural.rs | 7 + crates/celox-test-suite/LIMITATIONS.md | 14 +- .../src/sv/cases/unpacked_structs.vtest | 228 ++++++++++++++++++ .../tests/retained_reports.rs | 4 +- ...erilator_property_reference_constructor.sv | 23 ++ .../sv_xezim_struct_reference_copies.sv | 23 ++ .../sv/icarus/unpacked_structs.json | 115 +++++++++ .../verification/sv/limitations.json | 5 + .../sv/verilator/unpacked_structs.json | 55 +++++ .../sv/xezim/unpacked_structs.json | 55 +++++ .../verification/xezim-review.json | 16 ++ .../systemverilog/unpacked_structs.rs | 83 ++++++- docs/guide/systemverilog-reference.md | 16 +- docs/ja/guide/systemverilog-reference.md | 9 +- scripts/check-external-suite-report.test.mjs | 2 + 24 files changed, 922 insertions(+), 84 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_verilator_property_reference_constructor.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_xezim_struct_reference_copies.sv diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index cc62339d02d..34d1634119f 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3446,6 +3446,31 @@ impl<'p, 'a> Comb<'p, 'a> { .cloned() .flatten() .or_else(|| param.default.clone()); + if param.direction.is_reference() && !param.leaves.is_empty() { + // Each member of a formal of unpacked structure type names + // the matching member variable of the actual. + let targets = match &actual { + Some(sv::ir::Expr::Concat(parts)) if parts.len() == param.leaves.len() => parts + .iter() + .map(|part| match part { + sv::ir::Expr::Ident(actual) => self.m.id(actual), + _ => None, + }) + .collect::>>(), + _ => None, + } + .ok_or_else(|| { + unsupported(format!("ref argument `{}` of `{name}`", param.source_name)) + })?; + for (leaf, target) in param.leaves.iter().zip(targets) { + let id = self + .m + .id(leaf) + .ok_or_else(|| unsupported(format!("argument `{}`", param.source_name)))?; + references.push((leaf.clone(), id, target)); + } + continue; + } if param.direction.is_reference() { // A reference formal names the actual variable itself // (IEEE 1800-2023 13.5.2); other actuals fall back to Ff. diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 1616a675ef9..efefd064c83 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4628,12 +4628,12 @@ impl<'p, 'a> Ff<'p, 'a> { let mut activation = Vec::new(); if self.kernel.is_some() && (subroutine.is_task || self.forked) { for name in &subroutine.automatic_locals { - // A reference formal has no storage of its own. - if subroutine - .params - .iter() - .any(|param| ¶m.name == name && param.direction.is_reference()) - { + // A reference formal, or a member of one, has no storage of + // its own. + if subroutine.params.iter().any(|param| { + param.direction.is_reference() + && (¶m.name == name || param.leaves.contains(name)) + }) { continue; } let original = self @@ -4701,11 +4701,42 @@ impl<'p, 'a> Ff<'p, 'a> { .cloned() .flatten() .or_else(|| param.default.clone()); - match self.reference(name, param, actual)? { - Reference::Variable(target) => { - references.push((param.name.clone(), id, target)); + if param.leaves.is_empty() { + match self.reference(name, param, actual)? { + Reference::Variable(target) => { + references.push((param.name.clone(), id, target)); + } + Reference::Alias(alias) => aliases.push(*alias), + } + continue; + } + // Each member of a formal of unpacked structure type refers to + // the matching member of the actual, which the analyzer binds as + // the concatenation of its members. + let parts = match actual { + Some(sv::ir::Expr::Concat(parts)) if parts.len() == param.leaves.len() => parts, + _ => { + return Err(unsupported(format!( + "ref argument `{}` of `{name}`", + param.source_name + ))); + } + }; + for (leaf, part) in param.leaves.iter().zip(parts) { + let id = self + .m + .id(leaf) + .ok_or_else(|| unsupported(format!("argument `{}`", param.source_name)))?; + let member = sv::ir::SubroutineParam { + name: leaf.clone(), + leaves: Vec::new(), + default: None, + ..param.clone() + }; + match self.reference(name, &member, Some(part))? { + Reference::Variable(target) => references.push((leaf.clone(), id, target)), + Reference::Alias(alias) => aliases.push(*alias), } - Reference::Alias(alias) => aliases.push(*alias), } } // An input evaluates into a register, which a host request in a later @@ -4748,8 +4779,12 @@ impl<'p, 'a> Ff<'p, 'a> { .ok_or_else(|| unsupported("missing output argument"))?; // A reference formal bound to a class property, forwarded: // its object was evaluated when the reference was made. - if let Some(store) = forwarded_property(reference, ¶m.name) { + if let Some(store) = + forwarded_property(reference, sv::ir::Expr::Ident(param.name.clone())) + { property_outputs.push(store); + } else if let Some(stores) = forwarded_members(reference, ¶m.name) { + property_outputs.extend(stores); } else { let lvalues = lvalue_from_expr(reference).ok_or_else(|| { unsupported(format!( @@ -4859,6 +4894,7 @@ impl<'p, 'a> Ff<'p, 'a> { let constant = |position: &sv::ir::ConstExpr| { sv::typecheck::eval_const_expr_with_types(position, constants, parameter_types) }; + self.split_property_concats(&mut body, &aliases); for alias in &aliases { body = alias.rewrite(body, &constant)?; } @@ -4902,6 +4938,67 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// Rewrite each assignment in `body` to a concatenation that has members + /// of a structure reference formal bound to a class property, which + /// [`references::Alias::rewrite`] stores one property at a time: the + /// concatenation writes temporaries in their place, so every position + /// of its other parts is taken before any write, and each property is + /// then stored from its temporary. + fn split_property_concats(&mut self, body: &mut [sv::ir::Stmt], aliases: &[references::Alias]) { + let properties: HashSet<&str> = aliases + .iter() + .filter(|alias| matches!(alias.target, references::Target::Property { .. })) + .map(|alias| alias.formal.as_str()) + .collect(); + if properties.is_empty() { + return; + } + for stmt in body { + stmt.walk_mut(&mut |stmt| { + let sv::ir::Stmt::AssignConcat { + parts, + nonblocking, + .. + } = stmt + else { + return; + }; + if !parts.iter().any(|part| properties.contains(part.name())) { + return; + } + let nonblocking = *nonblocking; + let mut stores = Vec::new(); + for part in parts.iter_mut() { + if !matches!(part, sv::ir::LValue::Ident(name) if properties.contains(name.as_str())) + { + continue; + } + // A select of a member is left to the rewrite to reject. + let Ok(width) = self.lvalue_width(part) else { + continue; + }; + let (_, temp) = self.m.temp("ref_member", width, false, self.m.four_state); + let member = std::mem::replace(part, sv::ir::LValue::Ident(temp.clone())); + stores.push(sv::ir::Stmt::Assign { + lhs: member, + rhs: sv::ir::Expr::Ident(temp), + nonblocking, + }); + } + if stores.is_empty() { + return; + } + let assignment = std::mem::replace(stmt, sv::ir::Stmt::Break); + stores.insert(0, assignment); + *stmt = sv::ir::Stmt::If { + condition: sv::ir::Expr::Literal("1'b1".into()), + then_body: stores, + else_body: Vec::new(), + }; + }); + } + } + /// What reference formal `param` of `name` refers to for a call with /// `actual`. The object of a property is evaluated here, at the call. fn reference( @@ -8380,10 +8477,10 @@ enum Reference { Alias(Box), } -/// The store that copies formal `formal` back into the class property that -/// `actual` reads through the object of a reference formal (see +/// The store that copies `value` back into the class property that `actual` +/// reads through the object of a reference formal (see /// [`references::Alias`]), when it is such a read. -fn forwarded_property(actual: &sv::ir::Expr, formal: &str) -> Option { +fn forwarded_property(actual: &sv::ir::Expr, value: sv::ir::Expr) -> Option { let sv::ir::Expr::Call { callee: sv::ir::Callee::Object(op), args, @@ -8400,11 +8497,45 @@ fn forwarded_property(actual: &sv::ir::Expr, formal: &str) -> Option Option> { + let sv::ir::Expr::Concat(parts) = actual else { + return None; + }; + let widths = parts + .iter() + .map(|part| match part { + sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(op), + .. + } => match **op { + sv::ir::ObjectOp::Load(field) => Some(field.width as usize), + _ => None, + }, + _ => None, + }) + .collect::>>()?; + let mut lsb = widths.iter().sum::(); + parts + .iter() + .zip(widths) + .map(|(part, width)| { + lsb -= width; + let bits = sv::ir::Expr::Select { + expr: Box::new(sv::ir::Expr::Ident(formal.to_owned())), + msb: sv::ir::ConstExpr::Literal((lsb + width - 1).to_string()), + lsb: sv::ir::ConstExpr::Literal(lsb.to_string()), + signed: false, + }; + forwarded_property(part, bits) + }) + .collect() +} diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 22a41a5f0ba..e0a21c2a96b 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -342,6 +342,7 @@ impl ConstantFunctions { direction: crate::procedural::ParamDirection::Input, r#type: ty.clone(), default: function.argument_defaults[position].clone().map(Into::into), + leaves: Vec::new(), }) .collect(), body: function diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 5829c89dd6d..d6eab346513 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1594,7 +1594,7 @@ fn read_index_value( Ok(value) } -fn path( +pub(super) fn path( mut root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs index 6c419491854..ba27eb45c81 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs @@ -48,12 +48,20 @@ pub(super) fn check_actual( "a constant is not a variable (IEEE 1800-2023 13.5.2)", )); } - None => objects::property(tree, actual, native, dimensions)? - .map(|(property, _)| procedural::dimensions_from_type(&property.r#type)), + None => property_shape(tree, actual, native, dimensions)?, } } - ExprKind::Member { .. } => match objects::property(tree, actual, native, dimensions)? { - Some((property, _)) => Some(procedural::dimensions_from_type(&property.r#type)), + ExprKind::Member { .. } => match property_shape(tree, actual, native, dimensions)? { + Some(shape) => Some(shape), + // A member of a variable of unpacked structure type is a + // variable of its own (see `unpacked_structs`). + None if let (parts, None) = direct::path(actual, native, tree, dimensions)? + && let [variable] = parts.as_slice() + && let Some(shape) = dimensions.get(variable) + && !dimensions.const_env.contains_key(variable) => + { + Some(shape.clone()) + } // A static property is a variable of its class's scope. None if let Some(variable) = objects::static_property(tree, actual, native, dimensions)? => @@ -134,15 +142,6 @@ pub(super) fn check_actual( .subroutine_param_shapes .get(name) .and_then(|shapes| shapes.get(position)); - // The members of a structure are separate variables, which one reference - // cannot alias. - if formal.is_some_and(|formal| formal.unpacked_struct.is_some()) - || shape.unpacked_struct.is_some() - { - return Err(unsupported(format!( - "ref argument of `{name}` of unpacked structure type" - ))); - } // Bounded and unbounded queues are equivalent (6.22.2), but a formal's // operations would apply its own bound to the actual. if let (Some(formal), Some(actual)) = ( @@ -167,9 +166,29 @@ pub(super) fn check_actual( Ok(()) } +/// The shape of class property `actual`, also of unpacked structure type. +fn property_shape( + tree: &AnalysisContext<'_>, + actual: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + if let Some((property, _)) = objects::property(tree, actual, native, dimensions)? { + return Ok(Some(procedural::dimensions_from_type(&property.r#type))); + } + // `objects::aggregate_load` rejects a receiver that calls a subroutine, + // which each member would evaluate again. + let Some((aggregate, _, _)) = objects::aggregate_property(tree, actual, native, dimensions)? + else { + return Ok(None); + }; + Ok(Some(procedural::dimensions_from_type(&aggregate.r#type))) +} + /// Whether variables of shapes `a` and `b` have equivalent types (IEEE /// 1800-2023 6.22.2). Integral types compare by total width, signedness and -/// state count; an enumeration only by its members. +/// state count; an enumeration only by its members; an unpacked structure +/// only with the same structure type. fn equivalent( state: &AnalysisState, a: &VariableDimensions, @@ -219,6 +238,11 @@ fn equivalent( if a.real != b.real || a.string != b.string || a.class != b.class { return false; } + match (&a.unpacked_struct, &b.unpacked_struct) { + (None, None) => {} + (Some(a), Some(b)) if a.same_type(b) => {} + _ => return false, + } if (a.enum_domain.is_some() || b.enum_domain.is_some()) && a.enum_domain != b.enum_domain { return false; } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index b03fb5067f0..8d360c66a55 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -2888,6 +2888,7 @@ pub(super) fn lower_subroutine( }, ), default, + leaves: Vec::new(), }); } let return_var = return_type @@ -2927,39 +2928,46 @@ pub(super) fn lower_subroutine( } result_leaves = Some((result.clone(), leaves)); } - if dispatch.is_none() { - for (index, r#type) in &aggregate_formals { - let param = &lowered_params[*index]; - let (name, source, direction) = ( - param.name.clone(), - param.source_name.clone(), - param.direction, - ); - let leaves = builder - .declare_aggregate(&source, r#type)? - .into_iter() - .map(|(leaf, _)| leaf) - .collect::>(); - if direction.is_read() { - aggregate_prologue.push(Stmt::AssignConcat { - parts: leaves.iter().cloned().map(LValue::Ident).collect(), - rhs: Expr::Ident(name.clone()), - nonblocking: false, - }); - } else if builder.automatic { - // An automatic output starts each call at its default. - aggregate_prologue.extend(leaves.iter().map(|leaf| Stmt::Local { - name: leaf.clone(), - init: None, - })); - } - if direction.is_written() { - aggregate_epilogue.push(Stmt::Assign { - lhs: LValue::Ident(name), - rhs: Expr::Concat(leaves.into_iter().map(Expr::Ident).collect()), - nonblocking: false, - }); - } + for (index, r#type) in &aggregate_formals { + let param = &lowered_params[*index]; + let (name, source, direction) = ( + param.name.clone(), + param.source_name.clone(), + param.direction, + ); + // The members of a reference formal are bound to the members of the + // actual, also in the body that dispatches a virtual method. + if dispatch.is_some() && !direction.is_reference() { + continue; + } + let leaves = builder + .declare_aggregate(&source, r#type)? + .into_iter() + .map(|(leaf, _)| leaf) + .collect::>(); + lowered_params[*index].leaves = leaves.clone(); + if direction.is_reference() { + continue; + } + if direction.is_read() { + aggregate_prologue.push(Stmt::AssignConcat { + parts: leaves.iter().cloned().map(LValue::Ident).collect(), + rhs: Expr::Ident(name.clone()), + nonblocking: false, + }); + } else if builder.automatic { + // An automatic output starts each call at its default. + aggregate_prologue.extend(leaves.iter().map(|leaf| Stmt::Local { + name: leaf.clone(), + init: None, + })); + } + if direction.is_written() { + aggregate_epilogue.push(Stmt::Assign { + lhs: LValue::Ident(name), + rhs: Expr::Concat(leaves.into_iter().map(Expr::Ident).collect()), + nonblocking: false, + }); } } // The members of formals and of the result have the subroutine's @@ -3189,7 +3197,15 @@ fn dispatch_body( let this = Expr::Ident(params[0].name.clone()); let args = params .iter() - .map(|param| Some(Expr::Ident(param.name.clone()))) + .map(|param| { + Some( + if param.direction.is_reference() && !param.leaves.is_empty() { + Expr::Concat(param.leaves.iter().cloned().map(Expr::Ident).collect()) + } else { + Expr::Ident(param.name.clone()) + }, + ) + }) .collect::>(); let items = targets .iter() @@ -3619,6 +3635,7 @@ fn lower_class( direction: ParamDirection::Input, r#type: ir_type, default: None, + leaves: Vec::new(), }], return_var: Some(result), body, @@ -3717,6 +3734,7 @@ fn lower_cast( direction: ParamDirection::Inout, r#type: ir_handle.clone(), default: None, + leaves: Vec::new(), }, SubroutineParam { name: source.clone(), @@ -3724,6 +3742,7 @@ fn lower_cast( direction: ParamDirection::Input, r#type: ir_handle, default: None, + leaves: Vec::new(), }, ], return_var: Some(result.clone()), diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 1b0503e0a00..ae8ef1d1485 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -78,6 +78,7 @@ fn lower_methods( direction: ParamDirection::Input, r#type: convert_type(handle.clone()), default: None, + leaves: Vec::new(), }, SubroutineParam { name: argument.clone(), @@ -85,6 +86,7 @@ fn lower_methods( direction: ParamDirection::Input, r#type: convert_type(argument_type), default: None, + leaves: Vec::new(), }, ]; let mut input_values = Vec::new(); @@ -97,6 +99,7 @@ fn lower_methods( direction: ParamDirection::Input, r#type: convert_type(ty.clone()), default: None, + leaves: Vec::new(), }); input_values.push(Expr::Ident(name)); } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/references.rs b/crates/celox-sv-analyzer/src/ast/procedural/references.rs index 62d4d1406b4..d3398066219 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/references.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/references.rs @@ -147,10 +147,17 @@ pub(in crate::ast) fn validate<'a>( .iter() .filter(|param| param.direction.is_reference()) { - let formal = param.name.as_str(); + // A formal of unpacked structure type is used through its members. + let formals = if param.leaves.is_empty() { + std::slice::from_ref(¶m.name) + } else { + param.leaves.as_slice() + }; let mut error = None; - for stmt in &subroutine.body { - check_formal(stmt, formal, param.direction, directions, &mut error); + for formal in formals { + for stmt in &subroutine.body { + check_formal(stmt, formal, param.direction, directions, &mut error); + } } if let Some(detail) = error { return Err(invalid(&subroutine.name, ¶m.source_name, detail)); diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 90bf23bc45b..222fa6f97b1 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -1065,6 +1065,7 @@ impl Renamer<'_> { .map(|param| crate::procedural::SubroutineParamBase { name: self.name(¶m.name), default: param.default.map(|default| self.expr(default)), + leaves: param.leaves.iter().map(|leaf| self.name(leaf)).collect(), ..param }) .collect(), diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index 9117e78ae3a..18d1e32321b 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -670,6 +670,12 @@ pub struct SubroutineParamBase { pub direction: ParamDirection, pub r#type: T, pub default: Option, + /// The local names of the members of a formal of unpacked structure + /// type, in the order of its flat value; empty for other formals and, in + /// the body that dispatches a virtual method, for formals passed by + /// value. A reference formal binds each to the matching member of its + /// actual. + pub leaves: Vec, } impl SubroutineBase { @@ -694,6 +700,7 @@ impl SubroutineBase { direction: param.direction, r#type: ft(param.r#type), default: param.default.map(&mut *fe), + leaves: param.leaves, }) .collect(), return_var: self.return_var, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 106251a144e..4571b041648 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -627,7 +627,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_integral_format_string` | execute | icarus | 1 | Icarus 13.0 compiles `$sformatf` with a `bit` vector variable as the format, then `vvp` stops: "$sformatf's first argument must be a string or a register." IEEE 1800-2023 21.3.3 reads the content of an integral format expression as the format; Verilator 5.052 gives the expected output, xezim 0.11.3 prints the format as a value (`sv_integral_format_string` in the xezim review). | | `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. | | `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). | -| `sv_icarus_unpacked_structs` | compile | icarus | 16 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | +| `sv_icarus_unpacked_structs` | compile | icarus | 21 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | | `sv_icarus_nested_containers` | compile | icarus | 4 | Icarus 13.0 rejects an associative array whose index type is a type name ("Type names are not valid expressions here."), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays ("Sorry: Dynamic array of type `dynamic array of ...` is not yet supported."), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases. | | `sv_verilator_nested_struct_default` | execute | verilator | 1 | Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 ("5 0000 1" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101. | @@ -1266,3 +1266,15 @@ executed mismatches in [the report](verification/sv/xezim/references.json). The [its observations](verification/repros/ref_arguments.json) reproduce the same values without the suite adapters; the observations are from the installed build, not a current-pin validation. + +The five `unpacked_structs::reference_*` cases pass `ref` and `const ref` formals +of unpacked structure type (13.5.2): variables, nested members, class properties +and their members, through virtual methods, across task suspensions, and with +handle and string members across heap collections. Celox passes all of them on +every backend. Verilator 5.052 rejects the two that bind a class property in a +function that also constructs an object with `%Error-IMPURE` "External variable +referenced by non-inlined function/task", also for a `ref` class-handle formal; +the [standalone source](verification/repros/sv_verilator_property_reference_constructor.sv) +reproduces it. These are executed compile failures. xezim 0.11.3 gives copy +semantics in the suspended-task case (`sv_ref_copy_semantics`) and the padded +string members of class properties (`sv_rest-X84`) in the heap case. diff --git a/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest index 096581f0eaa..88cdfc2893c 100644 --- a/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest +++ b/crates/celox-test-suite/src/sv/cases/unpacked_structs.vtest @@ -578,3 +578,231 @@ endmodule (top Top) (run_until 6000) (expect_output "3 [2997] [2999*] [n2999] 3000\n")) + +(case reference_formals + (source "unpacked_struct_references.sv" #" +module Top(output bit done); + class Node; + string n; + function new(string n); + this.n = n; + endfunction + endclass + typedef enum { READ, WRITE } kind_e; + typedef struct { kind_e kind; bit [63:0] addr; string tag; Node node; int n; } op_t; + typedef struct { op_t op; int count; } outer_t; + function automatic void fill(ref op_t r, input string tag); + r = '{kind: WRITE, addr: 64'h10, tag: tag, node: null, n: 0}; + r.node = new({tag, "!"}); + r.n = 7; + r.addr++; + endfunction + function automatic bit same(const ref op_t a, const ref op_t b); + return a.kind == b.kind && a.addr == b.addr && a.tag == b.tag; + endfunction + function automatic int sum(op_t r); + return int'(r.addr) + r.n; + endfunction + function automatic void forward(ref op_t r); + op_t copy; + fill(r, {r.tag, "f"}); + r.n = sum(r); + copy = r; + copy.tag = "copy"; + endfunction + function automatic void bump(ref int i); + i++; + endfunction + function automatic void bump64(ref bit [63:0] i); + i++; + endfunction + function automatic void show(const ref op_t r); + $display("%s %0d %s %s %0d", r.kind == WRITE ? "W" : "R", r.addr, r.tag, r.node.n, r.n); + endfunction + class Holder; + op_t p; + function void touch(); + forward(p); + endfunction + endclass + initial begin + op_t a, b; + outer_t o; + Holder h; + h = new; + fill(a, "a"); + show(a); + b = a; + $display("same %0d", same(a, b)); + b.tag = "b"; + $display("same %0d", same(a, b)); + o.op.tag = "o"; + forward(o.op); + bump(o.count); + show(o.op); + $display("nested %0d %0d", o.op.n, o.count); + h.p.tag = "h"; + h.touch(); + forward(h.p); + bump64(h.p.addr); + show(h.p); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "W 17 a a! 7\nsame 1\nsame 0\nW 17 of of! 24\nnested 24 1\nW 18 hff hff! 24\n")) + +(case reference_formals_of_virtual_methods + (source "unpacked_struct_virtual_references.sv" #" +module Top(output bit done); + typedef enum { UVM_READ, UVM_WRITE } uvm_access_e; + typedef enum { UVM_IS_OK, UVM_NOT_OK } uvm_status_e; + typedef struct { + uvm_access_e kind; + bit [63:0] addr; + bit [63:0] data; + int n_bits; + bit [7:0] byte_en; + uvm_status_e status; + } bus_op_t; + class item; + bit [31:0] addr, data; + bit write; + endclass + virtual class adapter; + pure virtual function item reg2bus(const ref bus_op_t rw); + pure virtual function void bus2reg(item bus_item, ref bus_op_t rw); + endclass + class my_adapter extends adapter; + virtual function item reg2bus(const ref bus_op_t rw); + item i = new; + i.addr = rw.addr; + i.data = rw.data; + i.write = rw.kind == UVM_WRITE; + return i; + endfunction + virtual function void bus2reg(item bus_item, ref bus_op_t rw); + rw.kind = bus_item.write ? UVM_WRITE : UVM_READ; + rw.addr = bus_item.addr; + rw.data = bus_item.data + 1; + rw.n_bits = 32; + rw.byte_en = 8'hf; + rw.status = UVM_IS_OK; + endfunction + endclass + initial begin + adapter a; + my_adapter m; + bus_op_t op, back; + item i; + m = new; + a = m; + op = '{kind: UVM_WRITE, addr: 'h40, data: 'h1234, n_bits: 32, byte_en: 'hf, status: UVM_NOT_OK}; + i = a.reg2bus(op); + $display("reg2bus %h %h %0d", i.addr, i.data, i.write); + back.status = UVM_NOT_OK; + a.bus2reg(i, back); + $display("bus2reg %0d %h %h %0d %h %0d", back.kind, back.addr, back.data, back.n_bits, back.byte_en, back.status); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "reg2bus 00000040 00001234 1\nbus2reg 1 0000000000000040 0000000000001235 32 0f 0\n")) + +(case reference_formals_across_time + (source "unpacked_struct_timed_references.sv" #" +module Top(output bit done); + typedef struct { int a; string s; } row_t; + row_t shared; + task automatic watch(ref row_t r, output int seen); + #2 seen = r.a; + r.s = {r.s, "+"}; + #2 r.a = r.a * 10; + endtask + initial begin + int seen; + shared = '{1, "x"}; + fork + watch(shared, seen); + begin + #1 shared.a = 5; + #2 $display("mid %0d %s", shared.a, shared.s); + end + join + $display("end %0d %s %0d %0d", shared.a, shared.s, seen, $time); + done = 1; + end +endmodule +"#) + (top Top) (run_until 10) (assert_eq done 1) + (expect_output "mid 5 x+\nend 50 x+ 5 4\n")) + +(case reference_formals_four_state + (four_state) + (source "unpacked_struct_four_state_references.sv" #" +module Top(output bit done); + typedef struct { logic [3:0] l; int i; bit [1:0] b; } access_t; + class Holder; + access_t p; + endclass + function automatic void mark(ref access_t r); + r.l = 4'b1z0x; + r = '{l: {r.l[3:1], 1'bx}, i: 'x, b: 2'b1x}; + endfunction + function automatic bit unknown(const ref access_t r); + return $isunknown(r.l); + endfunction + initial begin + access_t a; + Holder h; + h = new; + $display("def %b %0d", a.l, unknown(a)); + mark(a); + $display("mark %b %0d %b %0d", a.l, a.i, a.b, unknown(a)); + mark(h.p); + $display("prop %b %0d %b", h.p.l, h.p.i, h.p.b); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "def xxxx 1\nmark 1z0x 0 10 1\nprop 1z0x 0 10\n")) + +(case reference_formal_handles_survive_heap_collections + (source "unpacked_struct_reference_handles.sv" #" +module Top(output int n); + class Node; + string text; + function new(string text); + this.text = text; + endfunction + endclass + typedef struct { Node m_type; string m_type_name; } pair_t; + class Holder; + pair_t p; + endclass + logic clk = 0; + always #1 clk = ~clk; + pair_t last; + Holder h = new; + string number; + function automatic void set(ref pair_t r, input string text); + r = '{m_type: null, m_type_name: {text, "!"}}; + r.m_type = new(text); + endfunction + initial forever begin + @(posedge clk); + number.itoa(n); + set(last, number); + set(h.p, {"h", number}); + n = n + 1; + end + initial #6000 $display("[%s] [%s] [%s] [%s] %0d", last.m_type.text, last.m_type_name, + h.p.m_type.text, h.p.m_type_name, n); +endmodule +"#) + (top Top) + (run_until 6000) + (expect_output "[2999] [2999!] [h2999] [h2999!] 3000\n")) diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index 89559fdc2a3..3b7b9b5be14 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -479,7 +479,9 @@ fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { ( "verilator", "references::ref_array_element_index_is_fixed_at_the_call" - | "references::ref_class_property_names_the_object_of_the_call", + | "references::ref_class_property_names_the_object_of_the_call" + | "unpacked_structs::reference_formal_handles_survive_heap_collections" + | "unpacked_structs::reference_formals", ) => ( "compile_error", "compile", diff --git a/crates/celox-test-suite/verification/repros/sv_verilator_property_reference_constructor.sv b/crates/celox-test-suite/verification/repros/sv_verilator_property_reference_constructor.sv new file mode 100644 index 00000000000..9a541c38d26 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_verilator_property_reference_constructor.sv @@ -0,0 +1,23 @@ +// Verilator 5.052 rejects this with %Error-IMPURE "External variable referenced by +// non-inlined function/task: 'set'" (also with a ref Node formal); IEEE 1800-2023 +// 13.5.2 permits a class property actual. Celox prints "h". +module Top; + class Node; + string text; + function new(string text); + this.text = text; + endfunction + endclass + typedef struct { Node m_type; } pair_t; + class Holder; + pair_t p; + endclass + Holder h = new; + function automatic void set(ref pair_t r, input string text); + r.m_type = new(text); + endfunction + initial begin + set(h.p, "h"); + $display("%s", h.p.m_type.text); + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_xezim_struct_reference_copies.sv b/crates/celox-test-suite/verification/repros/sv_xezim_struct_reference_copies.sv new file mode 100644 index 00000000000..35101b40298 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_xezim_struct_reference_copies.sv @@ -0,0 +1,23 @@ +// xezim 0.11.3 prints "mid 5 x" and "end 10 x+ 1": the task's ref formal +// is a copy of shared (IEEE 1800-2023 13.5.2 gives "mid 5 x+" and "end 50 x+ 5"). +module top; + typedef struct { int a; string s; } row_t; + row_t shared; + task automatic watch(ref row_t r, output int seen); + #2 seen = r.a; + r.s = {r.s, "+"}; + #2 r.a = r.a * 10; + endtask + initial begin + int seen; + shared = '{1, "x"}; + fork + watch(shared, seen); + begin + #1 shared.a = 5; + #2 $display("mid %0d %s", shared.a, shared.s); + end + join + $display("end %0d %s %0d", shared.a, shared.s, seen); + end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json index f0921a6595b..4e30b6a3d99 100644 --- a/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/icarus/unpacked_structs.json @@ -322,6 +322,121 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::reference_formal_handles_survive_heap_collections", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::reference_formals", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::reference_formals_across_time", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::reference_formals_four_state", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_icarus_unpacked_structs.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_structs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", + "upstream": [] + }, + "name": "unpacked_structs::reference_formals_of_virtual_methods", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 does not support unpacked structures (\"sorry: Unpacked structs not supported.\"), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 623ea0723a1..678cda31ec5 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2997,6 +2997,11 @@ "unpacked_structs::initializers_results_and_defaults", "unpacked_structs::members_whole_copies_and_equality", "unpacked_structs::module_variables", + "unpacked_structs::reference_formal_handles_survive_heap_collections", + "unpacked_structs::reference_formals", + "unpacked_structs::reference_formals_across_time", + "unpacked_structs::reference_formals_four_state", + "unpacked_structs::reference_formals_of_virtual_methods", "unpacked_structs::results_and_outputs", "unpacked_structs::subroutine_arguments_and_results" ] diff --git a/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json index 037e6d81c89..abcad6c2f42 100644 --- a/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/verilator/unpacked_structs.json @@ -166,6 +166,61 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-IMPURE: /source_0.sv:18:29: Unsupported: External variable referenced by non-inlined function/task: 'set'\n : ... note: In instance 'celox_suite_tb.dut'\n 18 | function automatic void set(ref pair_t r, input string text);\n | ^~~\n /source_0.sv:6:18: ... Location of the external reference: 'text'\n 6 | this.text = text;\n | ^~~~\n ... For error description see https://verilator.org/warn/IMPURE?v=5.052\n%Warning-ZERODLY: /testbench.sv:103:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 103 | if (t1 > $time) #(t1 - $time);\n | ^\n ... For warning description see https://verilator.org/warn/ZERODLY?v=5.052\n ... Use \"/* verilator lint_off ZERODLY */\" and lint_on around source to disable this message.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formal_handles_survive_heap_collections", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-IMPURE: /source_0.sv:24:29: Unsupported: External variable referenced by non-inlined function/task: 'forward'\n : ... note: In instance 'celox_suite_tb.dut'\n 24 | function automatic void forward(ref op_t r);\n | ^~~~~~~\n /source_0.sv:6:18: ... Location of the external reference: 'n'\n 6 | this.n = n;\n | ^\n ... For error description see https://verilator.org/warn/IMPURE?v=5.052\n%Warning-ZERODLY: /testbench.sv:103:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 103 | if (t1 > $time) #(t1 - $time);\n | ^\n ... For warning description see https://verilator.org/warn/ZERODLY?v=5.052\n ... Use \"/* verilator lint_off ZERODLY */\" and lint_on around source to disable this message.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals_across_time", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals_four_state", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals_of_virtual_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json index e368bcbaa51..d71d341f19e 100644 --- a/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json +++ b/crates/celox-test-suite/verification/sv/xezim/unpacked_structs.json @@ -154,6 +154,61 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "unpacked_structs::reference_formal_handles_survive_heap_collections at 808:3: expect_output: expected [91, 50, 57, 57, 57, 93, 32, 91, 50, 57, 57, 57, 33, 93, 32, 91, 104, 50, 57, 57, 57, 93, 32, 91, 104, 50, 57, 57, 57, 33, 93, 32, 51, 48, 48, 48, 10], got [91, 50, 57, 57, 57, 93, 32, 91, 50, 57, 57, 57, 33, 93, 32, 91, 32, 93, 32, 91, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 104, 50, 57, 57, 57, 33, 93, 32, 51, 48, 48, 48, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formal_handles_survive_heap_collections", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "unpacked_structs::reference_formals_across_time at 740:3: expect_output: expected [109, 105, 100, 32, 53, 32, 120, 43, 10, 101, 110, 100, 32, 53, 48, 32, 120, 43, 32, 53, 32, 52, 10], got [109, 105, 100, 32, 53, 32, 120, 10, 101, 110, 100, 32, 49, 48, 32, 120, 43, 32, 49, 32, 52, 10]", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals_across_time", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals_four_state", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unpacked_structs::reference_formals_of_virtual_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "unpacked_structs::results_and_outputs at 186:3: expect_output: expected [109, 97, 107, 101, 32, 48, 10, 111, 117, 116, 115, 32, 97, 98, 99, 10, 111, 117, 116, 122, 32, 48, 10, 115, 116, 97, 116, 105, 99, 32, 49, 32, 50, 10, 115, 116, 97, 116, 105, 99, 32, 50, 32, 50, 10], got [109, 97, 107, 101, 32, 48, 10, 111, 117, 116, 115, 32, 97, 98, 99, 10, 111, 117, 116, 122, 32, 120, 10, 115, 116, 97, 116, 105, 99, 32, 49, 32, 50, 10, 115, 116, 97, 116, 105, 99, 32, 50, 32, 50, 10]", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index 39f718bd0c6..6e78d1ff9d7 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -4687,6 +4687,22 @@ "classification": "xezim_bug", "bug": "sv_rest-X90", "note": "m[next_index()].push_back(7) calls next_index() three times per statement (i = 6 after two statements, elements lost), and $unpacked_dimensions(grid)/$dimensions(grid) of int grid[][] print 1 2 instead of 2 3." + }, + { + "suite": "sv", + "name": "unpacked_structs::reference_formals_across_time", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "A suspended task's ref formal of unpacked structure type neither sees the caller's write (shared.a = 5) nor writes shared until it returns: xezim prints \"mid 5 x\" and \"end 10 x+ 1\" where 13.5.2 gives \"mid 5 x+\" and \"end 50 x+ 5\". Reproduced by verification/repros/sv_xezim_struct_reference_copies.sv." + }, + { + "suite": "sv", + "name": "unpacked_structs::reference_formal_handles_survive_heap_collections", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X84", + "note": "h.p.m_type_name, the string member of a class property written through a ref formal, prints as a space-padded wide value and h.p.m_type.text prints empty; xezim does the same for a direct write of the property (h.p = '{...}). Reproduced by verification/repros/sv_xezim_unpacked_struct_properties.sv." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs index 00b23d1619c..dfd2fee522c 100644 --- a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs +++ b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs @@ -271,6 +271,46 @@ sv_backends! { let done = sim.signal("done"); assert_eq!(sim.get(done), BigUint::from(1u8)); } + fn property_bound_structure_references_forward_and_capture(sim) { + @setup { + let source = r#"module Top(output int value); + typedef struct { int a; string s; } pair_t; + class H; + pair_t p; + endclass + int arr[2]; + function automatic void set_pair(output pair_t p); + p = '{7, "s"}; + endfunction + function automatic void bump_pair(inout pair_t p); + p.a++; + p.s = {p.s, "!"}; + endfunction + function automatic void forward(ref pair_t r); + set_pair(r); + bump_pair(r); + endfunction + function automatic void place(ref pair_t r); + {r.a, arr[r.a]} = {32'd1, 32'd7}; + endfunction + initial begin + H h; + pair_t v; + h = new; + forward(h.p); + forward(v); + value = h.p.a * 1000 + v.a * 100 + h.p.s.len() * 10 + v.s.len(); + h.p.a = 0; + place(h.p); + value = value * 100 + h.p.a * 10 + arr[0] + arr[1]; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(882217u32)); + } fn redeclared_structure_properties_hide_their_members(sim) { @setup { let source = r#"module Top(output int value); @@ -310,6 +350,21 @@ sv_backends! { fn unpacked_struct_four_state_members(sim) { @case "unpacked_structs::four_state_members"; } + fn unpacked_struct_reference_formals(sim) { + @case "unpacked_structs::reference_formals"; + } + fn unpacked_struct_reference_formals_of_virtual_methods(sim) { + @case "unpacked_structs::reference_formals_of_virtual_methods"; + } + fn unpacked_struct_reference_formals_across_time(sim) { + @case "unpacked_structs::reference_formals_across_time"; + } + fn unpacked_struct_reference_formals_four_state(sim) { + @case "unpacked_structs::reference_formals_four_state"; + } + fn unpacked_struct_reference_formal_handles_survive_heap_collections(sim) { + @case "unpacked_structs::reference_formal_handles_survive_heap_collections"; + } fn unpacked_struct_class_properties(sim) { @case "unpacked_structs::class_properties"; } @@ -446,8 +501,32 @@ fn unsupported_and_illegal_uses_are_rejected() { "whole unpacked structure property read through a receiver with a side effect", ), ( - "function automatic void f(ref i_t r); r.a++; endfunction i_t v; initial f(v);", - "ref argument of `f` of unpacked structure type", + "typedef struct { int a; bit b; } j_t; function automatic void f(ref i_t r); r.a++; endfunction j_t v; initial f(v);", + "not equivalent", + ), + ( + "typedef struct { int a; bit b; } j_t; function automatic void f(ref i_t q[$]); endfunction j_t v[$]; initial f(v);", + "not equivalent", + ), + ( + "function automatic void f(const ref i_t r); r = '{1, 0}; endfunction i_t v; initial f(v);", + "const ref argument cannot be", + ), + ( + "function automatic void f(const ref i_t r); r.a = 1; endfunction i_t v; initial f(v);", + "const ref argument cannot be", + ), + ( + "function automatic void g(ref int x); endfunction function automatic void f(const ref i_t r); g(r.a); endfunction i_t v; initial f(v);", + "const ref argument cannot be", + ), + ( + "function automatic void f(ref i_t r); endfunction i_t q[$]; initial f(q[0]);", + "ref argument of `f` bound to an element of a dynamic array", + ), + ( + "class C; i_t v; endclass C cs[$]; function automatic void f(ref i_t r); endfunction initial f(cs[$urandom_range(0, 1)].v);", + "whole unpacked structure property read through a receiver with a side effect", ), ( "class B; i_t p; endclass class D extends B; int p; endclass D d; int x; initial begin d = new; x = d.p.a; end", diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 9f7812ef13b..6548eb8681b 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -332,7 +332,7 @@ Unpacked structures (IEEE 1800-2023 7.2) may have integral, enumeration, members, each keeping its own 2-state or 4-state type. Variables of such a type may be module variables, procedural locals, class properties, queue, dynamic and associative array elements (`q[i].m` reads a member), and -subroutine arguments of any direction and results. Members are read and written like variables of +subroutine arguments of any direction, including [`ref`](#reference-arguments), and results. Members are read and written like variables of their type; a whole structure is assigned and compared with `==`, `!=`, `===` and `!==` against a value of the same type, chosen with `?:`, or built from an assignment pattern (`'{a, b}`, `'{m: v, default: d}`, `T'{...}`, with @@ -364,7 +364,8 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: array, ANSI port default values, tagged unions, unpacked unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), `real`, and unpacked structs as ports, nets, parameters, static, `rand` or `const` class properties, fixed-size array elements, or with members that - are arrays, `real`, or have default values. + are arrays (also dynamic arrays, queues and associative arrays), `real`, or + have default values. - Sequential processes: `iff` qualifiers in `always_ff` event lists ([#452](https://github.com/celox-sim/celox/issues/452)), and in `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit edge signals, and several edges without an asynchronous reset. @@ -754,8 +755,11 @@ A `ref` or `const ref` formal is the actual itself, not a copy (IEEE 1800-2023 alias it, and a task keeps the reference while it is suspended. The actual can be a variable, including a string, class handle, queue, dynamic or associative array, or unpacked array; a property of a class object, whose handle is -evaluated at the call; or an element of a fixed-size unpacked array, whose -index is evaluated at the call. A `const` qualifier, like the direction, carries +evaluated at the call; an element of a fixed-size unpacked array, whose +index is evaluated at the call; or a member of an unpacked structure. A formal +of [unpacked structure](#unpacked-structures) type refers to each member of a +structure variable, member or class property, also through virtual methods. +A `const` qualifier, like the direction, carries over to the following formals (13.3). These are rejected as the standard requires: `ref` formals of subroutines with @@ -768,8 +772,8 @@ continuous assignment or an event expression (13.4.1; `const ref` is allowed). `ref static`, elements of dynamic arrays, queues and associative arrays (whose references would have to outlive a resize, 13.5.2), elements of class -properties, members of unpacked structures, writes to part of a formal bound to -a class property, and selects of a formal bound to an array element at a +properties, writes to part of a formal bound to a class property or to a +member of one, and selects of a formal bound to an array element at a position only known at run time (positions of unrolled loops are known) are unsupported and rejected. A formal bound to a class property can be passed on to an `output` or `inout` argument; it is written back when that call returns. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 6ae5d465d85..ab322a46e41 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -210,7 +210,7 @@ unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列 クラスハンドル、packed 構造体、入れ子の unpacked 構造体を使え、各メンバは自身の 2 値・4 値の型を保ちます。この型の変数は、モジュール変数、手続き内のローカル変数、クラスプロパティ、 キュー・動的配列・連想配列の要素(`q[i].m` でメンバを読めます)、 -任意の方向のサブルーチン引数と戻り値にできます。メンバはその型の変数と同じように +任意の方向([`ref`](#reference-arguments) を含む)のサブルーチン引数と戻り値にできます。メンバはその型の変数と同じように 読み書きできます。構造体全体は、同じ型の値との代入と `==`・`!=`・`===`・`!==` による 比較、`?:` による選択、assignment pattern(`'{a, b}`、`'{m: v, default: d}`、 `T'{...}`。`default` は入れ子の構造体のメンバにも適用)による構築ができます。 @@ -237,7 +237,7 @@ unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート式(`module m({a, b}, c[3:0], .p(d))` など、[#1953](https://github.com/celox-sim/celox/issues/1953))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、`real`、ポート・ネット・パラメータ・static / `rand` / `const` のクラスプロパティ・固定長配列の要素としての unpacked 構造体、配列・`real`・既定値を持つメンバ。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、`real`、ポート・ネット・パラメータ・static / `rand` / `const` のクラスプロパティ・固定長配列の要素としての unpacked 構造体、配列(動的配列・キュー・連想配列を含む)・`real`・既定値を持つメンバ。 - 順序回路のプロセス:`always_ff` のイベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 非同期リセットを持たない複数のエッジ。 @@ -367,7 +367,8 @@ tagged union と unpacked union は未対応です。 仮引数への書き込みはすぐに見え、実引数の別の名前とも別名になり、task は待ちの間も参照を保ちます。 実引数には、変数(`string`、クラスハンドル、キュー、動的配列、連想配列、unpacked 配列を含む)、 呼び出し時にハンドルを評価するクラスオブジェクトのプロパティ、呼び出し時に添字を評価する -固定長 unpacked 配列の要素を渡せます。`const` は方向と同様に後続の仮引数に引き継がれます(13.3)。 +固定長 unpacked 配列の要素、unpacked 構造体のメンバを渡せます。[unpacked 構造体](#unpacked-structures)型の +仮引数は、構造体の変数・メンバ・クラスプロパティの各メンバを参照します(仮想メソッド経由でも同じ)。`const` は方向と同様に後続の仮引数に引き継がれます(13.3)。 規格どおり次を拒否します:static な寿命のサブルーチンの `ref` 仮引数、式・定数・部分選択・ネット、 または仮引数と等価でない型(6.22.2)の実引数、`const ref` 仮引数への書き込み、`ref` 仮引数への @@ -376,7 +377,7 @@ tagged union と unpacked union は未対応です。 (13.4.1。`const ref` は可)。 `ref static`、動的配列・キュー・連想配列の要素(参照がサイズ変更より長く生きる必要がある、13.5.2)、 -クラスプロパティの要素、unpacked 構造体のメンバ、クラスプロパティに束縛した仮引数の一部への書き込み、 +クラスプロパティの要素、クラスプロパティやそのメンバに束縛した仮引数の一部への書き込み、 配列要素に束縛した仮引数の実行時にしか決まらない位置での選択(展開されるループの位置は決まる)は 未対応として拒否します。クラスプロパティに束縛した仮引数は `output` / `inout` 引数に渡せ、その呼び出しが 戻るときに書き戻します。 diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index df9b5afb1a2..12278f72695 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -418,6 +418,8 @@ test("every retained baseline accepts only its existing failures", () => { "tagged_unions::writable_system_arguments", "tagged_unions::writable_task_arguments", "timing::final_procedure_output_survives_program_completion", + "unpacked_structs::reference_formal_handles_survive_heap_collections", + "unpacked_structs::reference_formals", ], ); } else {