From 936bdda4932277f827e5b370dad0d4ec882669ae Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 15:24:20 +0900 Subject: [PATCH 1/2] feat(sv): implement enumerated type methods Enum-typed expressions accept `first`, `last`, `next(N)`, `prev(N)`, `num` and `name` (IEEE 1800-2023 6.19.5), with or without parentheses (6.19.5.7), on variables, array and container elements, class properties, static properties, function and method results, casts, enum constants and the results of other enum methods. Types now carry the members of an enumeration with their names, base width, signedness and state count. The methods bind to a new `Callee::Lookup` IR call that evaluates its selector once and returns the value of the first key it matches by case equality, else a default; the frontend lowers it to multiplexers whose selector copies share one node. A receiver with side effects therefore runs once, and only designs that call these methods pay for them. `next`/`prev` wrap around and take the count modulo the number of members; a value that is no member, including one with unknown bits, gives the base type's default initial value ('x for a 4-state base, Table 6-7). `name` returns the empty string for such a value (6.19.5.6). Change-Id: Icf20fb1bef13ec48958bd50e14f82790e72f516a --- conformance/sv-tests/expected.tsv | 20 +- crates/celox-frontend-sv/src/lowering.rs | 119 ++++- crates/celox-frontend-sv/src/lowering/ff.rs | 7 +- .../src/lowering/procedural.rs | 3 + crates/celox-sv-analyzer/src/ast.rs | 27 +- crates/celox-sv-analyzer/src/ast/case.rs | 15 + crates/celox-sv-analyzer/src/ast/classes.rs | 5 +- .../celox-sv-analyzer/src/ast/comb_rewrite.rs | 2 +- .../src/ast/const_functions.rs | 3 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 21 +- .../src/ast/dimensions/discovery.rs | 4 + .../src/ast/dimensions/query_binding.rs | 1 + .../src/ast/dimensions/tests.rs | 1 + crates/celox-sv-analyzer/src/ast/enums.rs | 27 + .../src/ast/expression_binding.rs | 1 + .../src/ast/expression_binding/direct.rs | 72 ++- .../src/ast/expression_binding/enums.rs | 497 ++++++++++++++++++ .../src/ast/expression_binding/objects.rs | 2 +- .../src/ast/expression_binding/references.rs | 4 +- .../src/ast/expression_binding/strings.rs | 17 + crates/celox-sv-analyzer/src/ast/functions.rs | 4 + crates/celox-sv-analyzer/src/ast/generate.rs | 2 + .../src/ast/generate/memo/sites.rs | 6 +- crates/celox-sv-analyzer/src/ast/inlining.rs | 2 +- .../src/ast/packed_structs/selects.rs | 3 +- .../celox-sv-analyzer/src/ast/parameters.rs | 4 + .../src/ast/parameters/skipped.rs | 3 +- .../src/ast/patterns/binding.rs | 6 +- .../celox-sv-analyzer/src/ast/procedural.rs | 8 +- .../src/ast/procedural/randomization.rs | 9 +- .../src/ast/procedural/references.rs | 2 +- crates/celox-sv-analyzer/src/ast/processes.rs | 62 ++- .../src/ast/type_binding/binding.rs | 22 +- crates/celox-sv-analyzer/src/ast/types.rs | 3 +- .../celox-sv-analyzer/src/system_functions.rs | 31 +- crates/celox-sv-analyzer/src/typecheck.rs | 23 + .../celox-test-suite/src/sv/cases/types.vtest | 65 +++ .../frontends/systemverilog/references.rs | 43 ++ .../tests/frontends/systemverilog/types.rs | 197 +++++++ docs/guide/systemverilog-reference.md | 2 +- docs/ja/guide/systemverilog-reference.md | 2 +- 41 files changed, 1279 insertions(+), 68 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/enums.rs create mode 100644 crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index ae00542eef2..c1d56b95e5b 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1177,16 +1177,16 @@ chapter-6/6.19.4--enum_numerical_expr_cast.sv 2state pass chapter-6/6.19.4--enum_numerical_expr_cast.sv 4state pass chapter-6/6.19.4--enum_numerical_expr_no_cast.sv 2state fail chapter-6/6.19.4--enum_numerical_expr_no_cast.sv 4state fail -chapter-6/6.19.5.1--enum_first.sv 2state fail -chapter-6/6.19.5.1--enum_first.sv 4state fail -chapter-6/6.19.5.2--enum_last.sv 2state fail -chapter-6/6.19.5.2--enum_last.sv 4state fail -chapter-6/6.19.5.3--enum_next.sv 2state fail -chapter-6/6.19.5.3--enum_next.sv 4state fail -chapter-6/6.19.5.4--enum_prev.sv 2state fail -chapter-6/6.19.5.4--enum_prev.sv 4state fail -chapter-6/6.19.5.5--enum_num.sv 2state fail -chapter-6/6.19.5.5--enum_num.sv 4state fail +chapter-6/6.19.5.1--enum_first.sv 2state pass +chapter-6/6.19.5.1--enum_first.sv 4state pass +chapter-6/6.19.5.2--enum_last.sv 2state pass +chapter-6/6.19.5.2--enum_last.sv 4state pass +chapter-6/6.19.5.3--enum_next.sv 2state pass +chapter-6/6.19.5.3--enum_next.sv 4state pass +chapter-6/6.19.5.4--enum_prev.sv 2state pass +chapter-6/6.19.5.4--enum_prev.sv 4state pass +chapter-6/6.19.5.5--enum_num.sv 2state pass +chapter-6/6.19.5.5--enum_num.sv 4state pass chapter-6/6.19.5.6--enum_name.sv 2state fail chapter-6/6.19.5.6--enum_name.sv 4state fail chapter-6/6.20.2--parameter.sv 2state pass diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 3d2e810cfc2..8a2322b0314 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1467,7 +1467,8 @@ fn kernel_written_names( } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = subroutines @@ -1671,7 +1672,8 @@ impl DriverScan<'_> { } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self @@ -4944,6 +4946,56 @@ pub(crate) fn attach_instance_glue( Ok(()) } +/// A [`sv::ir::Callee::Lookup`] call as nested multiplexers of case +/// equalities. The selector is lowered once and its node shared by every +/// comparison, so nested lookups lower in linear time. `lower` lowers an +/// operand with a context width and signedness. +fn lower_lookup( + args: &[Option], + width: usize, + signed: bool, + arena: &mut SLTNodeArena, + lower: &mut dyn FnMut( + &sv::ir::Expr, + &mut SLTNodeArena, + Option, + Option, + ) -> Option, +) -> Option { + let (selector, rest) = args.split_first()?; + let (default, pairs) = rest.split_last()?; + let (pairs, []) = pairs.as_chunks::<2>() else { + return None; + }; + let selector = lower(selector.as_ref()?, arena, None, None)?; + let resized = |expr: &Option| { + Some(sv::ir::Expr::Resize { + expr: Box::new(expr.clone()?), + width, + signed, + }) + }; + let mut result = lower(&resized(default)?, arena, Some(width), Some(signed))?; + for [key, value] in pairs.iter().rev() { + let key = lower(key.as_ref()?, arena, None, None)?; + let compared = celox_slt::get_width(selector, arena).max(celox_slt::get_width(key, arena)); + let left = coerce_node_width(arena, selector, Some(compared), false).ok()?; + let right = coerce_node_width(arena, key, Some(compared), false).ok()?; + let cond = arena + .alloc(SLTNode::Binary(left, BinaryOp::EqCase, right)) + .ok()?; + let then_expr = lower(&resized(value)?, arena, Some(width), Some(signed))?; + result = arena + .alloc(SLTNode::Mux { + cond, + then_expr, + else_expr: result, + }) + .ok()?; + } + Some(result) +} + /// `expr inside { items }` as the comparisons the language defines: a value /// matches by wildcard equality, a range by an inclusive bounds check. fn inside_as_comparisons(expr: &sv::ir::Expr, items: &[sv::ir::InsideItem]) -> sv::ir::Expr { @@ -7231,6 +7283,38 @@ fn lower_glue_parent_expr( source_ids, )) } + sv::ir::Expr::Call { + callee: sv::ir::Callee::Lookup { width, signed }, + args, + .. + } => { + let mut sources = HashSet::default(); + let mut source_ids = Vec::new(); + let node = lower_lookup( + args, + *width, + *signed, + arena, + &mut |expr, arena, context_width, context_signed| { + let (node, expr_sources, expr_source_ids) = lower_glue_parent_expr( + expr, + variables, + name_to_id, + constants, + parameter_types, + arena, + context_width, + context_signed, + )?; + sources.extend(expr_sources); + source_ids.extend(expr_source_ids); + Some(node) + }, + )?; + source_ids.sort(); + source_ids.dedup(); + Some((node, sources, source_ids)) + } sv::ir::Expr::Inside { expr, items } => lower_glue_parent_expr( &inside_as_comparisons(expr, items), variables, @@ -8634,6 +8718,34 @@ fn lower_expr_with_context( sources, )) } + sv::ir::Expr::Call { + callee: sv::ir::Callee::Lookup { width, signed }, + args, + .. + } => { + let mut sources = HashSet::default(); + let node = lower_lookup( + args, + *width, + *signed, + arena, + &mut |expr, arena, context_width, context_signed| { + let (node, expr_sources) = lower_expr_with_context( + expr, + variables, + name_to_id, + constants, + parameter_types, + arena, + context_width, + context_signed, + )?; + sources.extend(expr_sources); + Some(node) + }, + )?; + Some((node, sources)) + } sv::ir::Expr::Inside { expr, items } => lower_expr_with_context( &inside_as_comparisons(expr, items), variables, @@ -10856,7 +10968,8 @@ mod tests { } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 13aea80aff2..d0a962166cc 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -933,7 +933,8 @@ impl<'p, 'a> Ff<'p, 'a> { } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self.m.subroutine(&name).cloned() else { @@ -7744,8 +7745,8 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { } continue; } - // A string operation is a value of its operands. - sv::ir::Callee::String(_) => continue, + // A string operation or lookup is a value of its operands. + sv::ir::Callee::String(_) | sv::ir::Callee::Lookup { .. } => continue, // 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. diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 523b8aa3312..b36fe6adf4f 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -288,6 +288,8 @@ impl<'a> ProcModule<'a> { } continue; } + // A lookup is a value of its operands. + sv::ir::Callee::Lookup { .. } => continue, // String operations use the simulator's heap. sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) @@ -1147,6 +1149,7 @@ impl<'a> ProcModule<'a> { pub fn is_callee(&self, callee: &sv::ir::Callee) -> bool { match callee { sv::ir::Callee::System(function) => function.reads_simulation_state(), + sv::ir::Callee::Lookup { .. } => false, sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) | sv::ir::Callee::Checked { .. } => true, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index e6b88f385ae..1cc4cc9b101 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -145,6 +145,7 @@ mod constants; mod declarations; mod dimensions; mod dpi; +mod enums; mod expression_binding; mod expressions; mod ff_process; @@ -1205,6 +1206,7 @@ impl Module { is_2state: function.return_is_2state, string: function.return_string, pattern_type: function.return_type.clone(), + enum_domain: function.return_enum_domain.clone(), }, ) })); @@ -1224,6 +1226,7 @@ impl Module { is_2state: !r#type.is_4state(), string: false, pattern_type: None, + enum_domain: None, }, )) })); @@ -1667,6 +1670,8 @@ pub struct Parameter { is_local: bool, /// See [`Type::signed_element_depth`]. signed_element_depth: Option, + /// The enumerated type the parameter is declared with. + enum_domain: Option>, } impl Parameter { @@ -1691,6 +1696,7 @@ impl Parameter { has_declared_type, is_local, signed_element_depth: None, + enum_domain: None, } } @@ -2160,8 +2166,11 @@ pub enum PortDirection { pub struct Type { container: Option>, is_enum: bool, - /// Resolved legal values for a scalar enum; None if its domain is unsupported. - enum_values: Option>, + /// Resolved members of a scalar enum; None if its domain is unsupported. + enum_domain: Option>, + /// A packed array whose elements are of an enumerated type, whose + /// methods are not supported on its elements. + packed_enum: bool, kind: TypeKind, is_signed: bool, packed_ranges: Vec, @@ -2207,7 +2216,8 @@ impl Type { fn implicit() -> Self { Self { is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, kind: TypeKind::Implicit, is_signed: false, packed_ranges: Vec::new(), @@ -2224,7 +2234,8 @@ impl Type { Self { kind, is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, is_signed: false, packed_ranges: Vec::new(), unpacked_ranges: Vec::new(), @@ -2787,6 +2798,8 @@ struct Function { return_dimensions: Option, return_signed: bool, return_is_2state: bool, + /// The members of an enumerated return type, for its methods. + return_enum_domain: Option>, } fn function_argument_metadata(params: &[FunctionParam]) -> Arc<[FunctionArgumentMetadata]> { @@ -2998,7 +3011,9 @@ struct UnpackedDimension { struct VariableDimensions { container: Option>, randomizable: bool, - enum_values: Option>, + enum_domain: Option>, + /// See [`Type::packed_enum`]. + packed_enum: bool, real: bool, /// A `string`: each element is a heap handle, not packed bits. string: bool, @@ -3035,6 +3050,8 @@ struct FunctionReturnMetadata { string: bool, /// Declared aggregate type, available before function bodies are inlined. pattern_type: Option, + /// The members of an enumerated return type, for its methods. + enum_domain: Option>, } #[derive(Debug, Clone, Default, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index 28701f62ad3..2fbcb574320 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -69,6 +69,21 @@ pub(super) fn expr_is_two_state( callee: Callee::Checked { .. }, .. } => false, + // The selector is compared with case equality; the result is a value + // or the default. + Expr::Call { + callee: Callee::Lookup { .. }, + args, + .. + } => { + let key = |index: usize| index % 2 == 1 && index + 1 != args.len(); + args.iter().enumerate().skip(1).all(|(index, arg)| { + key(index) + || arg + .as_ref() + .is_some_and(|arg| expr_is_two_state(state, arg, packed_dimensions)) + }) + } Expr::Call { callee: Callee::Object(op), .. diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 2b4716c8a28..d4ab21cf3d8 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -43,7 +43,8 @@ impl Property { return None; } if self.r#type.is_enum { - self.r#type.enum_values.as_ref().and_then(|values| { + self.r#type.enum_domain.as_ref().and_then(|domain| { + let values = &domain.members; (1..=256) .contains(&values.len()) .then_some(values.len() as u16) @@ -167,7 +168,7 @@ impl Class { } if (property.rand || property.randc) && (property.field.handle.is_some() - || (property.r#type.is_enum && property.r#type.enum_values.is_none())) + || (property.r#type.is_enum && property.r#type.enum_domain.is_none())) { return Err(unsupported( "class randomize requires integral rand properties with a supported enum domain", diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index 68e6e82b630..e9fa1ed0109 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -112,7 +112,7 @@ pub(super) fn expr_static_width( .. } => Some(op.result_type().0), Expr::Call { - callee: Callee::Checked { width, .. }, + callee: Callee::Checked { width, .. } | Callee::Lookup { width, .. }, .. } => Some(*width), Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 6c5de5936bb..c2450c8a986 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -637,7 +637,8 @@ fn simulation_state_readers(functions: &[Subroutine]) -> HashMap {} + | Callee::Checked { .. } + | Callee::Lookup { .. } => {} Callee::Subroutine(callee) => calls.push(callee.as_str()), } } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 4b6c56b87d2..6a9c799395f 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -134,9 +134,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals( VariableDimensions { container: port.r#type().container.clone(), randomizable: port.r#type().container.is_none() - && (!port.r#type().is_enum || port.r#type().enum_values.is_some()) + && (!port.r#type().is_enum || port.r#type().enum_domain.is_some()) && port.randomizable, - enum_values: port.r#type().enum_values.clone(), + enum_domain: port.r#type().enum_domain.clone(), + packed_enum: port.r#type().packed_enum, real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(port.r#type().kind(), TypeKind::String), class: port.r#type().class().map(str::to_owned), @@ -163,10 +164,11 @@ pub(super) fn packed_dimensions_from_ports_and_signals( VariableDimensions { container: signal.r#type().container.clone(), randomizable: signal.r#type().container.is_none() - && (!signal.r#type().is_enum || signal.r#type().enum_values.is_some()) + && (!signal.r#type().is_enum || signal.r#type().enum_domain.is_some()) && !signal.is_net() && !signal.is_const, - enum_values: signal.r#type().enum_values.clone(), + enum_domain: signal.r#type().enum_domain.clone(), + packed_enum: signal.r#type().packed_enum, real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(signal.r#type().kind(), TypeKind::String), class: signal.r#type().class().map(str::to_owned), @@ -362,7 +364,8 @@ fn extend_variable_dimensions_from_const_env( let ty = Type { container: None, is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, kind: TypeKind::Logic, is_signed: variable_type_is_signed(const_env, name), packed_ranges, @@ -379,7 +382,8 @@ fn extend_variable_dimensions_from_const_env( if let Some(existing) = context.get(name) { shape.container = existing.container.clone(); shape.randomizable = existing.randomizable; - shape.enum_values = existing.enum_values.clone(); + shape.enum_domain = existing.enum_domain.clone(); + shape.packed_enum = existing.packed_enum; shape.members = existing.members.clone(); shape.is_2state = existing.is_2state; shape.signed_element_depth = existing.signed_element_depth; @@ -543,14 +547,15 @@ mod tests; pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariablePackedDimensions { parameters .iter() - .filter(|parameter| !parameter.packed_ranges.is_empty()) + .filter(|parameter| !parameter.packed_ranges.is_empty() || parameter.enum_domain.is_some()) .map(|parameter| { ( parameter.name.clone(), VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: parameter.enum_domain.clone(), + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 4e1da8f54a4..8ff37fa3313 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -391,6 +391,9 @@ fn return_metadata( signed: ty.is_some_and(Type::is_signed), is_2state: ty.is_some_and(|ty| ty.kind() == TypeKind::Bit), string: ty.is_some_and(|ty| ty.kind() == TypeKind::String), + enum_domain: ty + .filter(|ty| ty.unpacked_ranges.is_empty()) + .and_then(|ty| ty.enum_domain.clone()), pattern_type: ty .filter(|ty| { !ty.members.is_empty() @@ -735,6 +738,7 @@ fn settle( is_2state: !ty.is_4state(), string: false, pattern_type: None, + enum_domain: None, }, ); publish(&tree.state.dimensions, key, context); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index c7b9cb3c8c6..e883ba38ec0 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -1016,6 +1016,7 @@ mod tests { is_2state: false, string: false, pattern_type: None, + enum_domain: None, }, ); for declaration in &tree.declarations().data_declarations { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index c437030ae2a..cd08ca70634 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -194,6 +194,7 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( is_2state: f.return_is_2state, string: f.return_string, pattern_type: f.return_type.clone(), + enum_domain: None, }, ) })); diff --git a/crates/celox-sv-analyzer/src/ast/enums.rs b/crates/celox-sv-analyzer/src/ast/enums.rs new file mode 100644 index 00000000000..0ccf4289278 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/enums.rs @@ -0,0 +1,27 @@ +//! Enumerated types (IEEE 1800-2023 6.19) and their methods (6.19.5). + +/// One named member of an enumerated type. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(super) struct EnumMember { + pub name: String, + pub value: i128, +} + +/// The members of an enumerated type in declaration order, with the shape +/// of its base type. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(super) struct EnumDomain { + pub members: Vec, + pub width: usize, + pub signed: bool, + /// Whether the base type is 4-state, whose default initial value is + /// `'x` rather than `'0` (Table 6-7). + pub four_state: bool, +} + +impl EnumDomain { + /// The values of the members, in declaration order. + pub fn values(&self) -> Vec { + self.members.iter().map(|member| member.value).collect() + } +} diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 0f30decf9ce..a6e911ac35a 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -3,6 +3,7 @@ use super::*; use celox_sv_syntax::{Declarations, DimensionKind, ExprId, ExprKind}; mod calls; mod direct; +mod enums; mod lvalues; mod objects; mod references; 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 bbf0009b7b8..2c95136577f 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -234,6 +234,13 @@ enum Finish { Inside(Vec), /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), + /// An enumerated type method; the children are the receiver, then the + /// count when one is given. + EnumMethod { + method: enums::Method, + domain: std::sync::Arc, + count: bool, + }, /// A read of property `property` of the object handle child. ObjectLoad(Box), /// A call of method subroutine `name` with `formals` formals; the first @@ -296,6 +303,53 @@ pub(in crate::ast) fn bind_value( )); } } + let enum_method = match &native.expression(id).kind { + ExprKind::Call { + expression, + arguments, + } => enums::method(tree, *expression, native, dimensions)? + .map(|method| (method, arguments.as_slice())), + ExprKind::Member { .. } => { + enums::method(tree, id, native, dimensions)?.map(|method| (method, &[][..])) + } + _ => None, + }; + if let Some(((method, receiver, domain), arguments)) = enum_method { + // `v.next()` lists one empty argument. + let arguments = match arguments { + [argument] if argument.name.is_none() && argument.value.is_none() => &[], + arguments => arguments, + }; + let counts = arguments + .iter() + .map(|argument| argument.value.filter(|_| argument.name.is_none())) + .collect::>>() + .filter(|counts| counts.len() <= method.formals()) + .ok_or_else(|| { + unsupported(format!( + "arguments of enumerated type method `{}`", + native.token_text(native.expression(id).tokens).trim() + )) + })?; + let mut children = vec![receiver]; + children.extend(&counts); + jobs.push(Job::Finish( + Finish::EnumMethod { + method, + domain, + count: !counts.is_empty(), + }, + children.len(), + scope.clone(), + )); + jobs.extend( + children + .into_iter() + .rev() + .map(|id| Job::Enter(id, None, scope.clone())), + ); + continue; + } if let Some(call) = super::super::processes::value(tree, id, native, dimensions, false)? { @@ -584,7 +638,8 @@ pub(in crate::ast) fn bind_value( "scope randomize requires a packed variable with a supported enum domain", )); } - domains.push(shape.enum_values.clone()); + domains + .push(shape.enum_domain.as_ref().map(|domain| domain.values())); if !expressions::query_actual_is_writable( &Expr::Ident(name), dimensions, @@ -1084,6 +1139,21 @@ pub(in crate::ast) fn bind_value( strings::call(StringOp::Concat, operands) } Finish::Concat => Expr::Concat(operands), + Finish::EnumMethod { + method, + domain, + count, + } => { + let count = count.then(|| operands.pop()).flatten(); + enums::call( + &tree.state, + method, + &domain, + operands.pop(), + count, + dimensions, + )? + } Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs new file mode 100644 index 00000000000..0771dd19d61 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs @@ -0,0 +1,497 @@ +//! Enumerated type methods (IEEE 1800-2023 6.19.5). +//! +//! The methods are values of the members of the receiver's type. They bind +//! to [`Callee::Lookup`] calls, which evaluate the receiver once and compare +//! it with the members by case equality, so a value that is no member of +//! the type, including one with unknown bits, matches none of them. + +use std::sync::Arc; + +use super::direct::call_name; +use super::*; +use crate::ast::enums::EnumDomain; + +/// An enumerated type method. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Method { + First, + Last, + Next, + Prev, + Num, + Name, +} + +impl Method { + fn parse(name: &str) -> Option { + Some(match name { + "first" => Self::First, + "last" => Self::Last, + "next" => Self::Next, + "prev" => Self::Prev, + "num" => Self::Num, + "name" => Self::Name, + _ => return None, + }) + } + + /// Whether the result is a string. + pub(super) fn returns_string(self) -> bool { + self == Self::Name + } + + /// Whether the result is a value of the enumerated type. + fn returns_member(self) -> bool { + matches!(self, Self::First | Self::Last | Self::Next | Self::Prev) + } + + /// The number of arguments the method takes at most: `next` and `prev` + /// take a count, which defaults to 1. + pub(super) fn formals(self) -> usize { + usize::from(matches!(self, Self::Next | Self::Prev)) + } +} + +/// The enumerated type method that native callee expression `id` names, +/// with the expression it is called on and that expression's type. +pub(super) fn method( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted)>> { + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(ungroup(id, native)).kind + else { + return Ok(None); + }; + if separator != "." { + return Ok(None); + } + let Some(method) = Method::parse(&instances::normalize_identifier(&name.spelling)) else { + return Ok(None); + }; + Ok(domain(tree, *expression, native, dimensions)?.map(|domain| (method, *expression, domain))) +} + +/// The enumerated type of native expression `id`, judged before it is +/// bound: a variable, an element of an array, a class property, a call of +/// a function, method or enumerated type method, a cast, or the status of a +/// process. +pub(super) fn domain( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted>> { + // `process::state` (9.7). + if let Some(domain) = processes::state(tree, id, native, dimensions) { + return Ok(Some(domain)); + } + Ok(match &native.expression(ungroup(id, native)).kind { + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + match dimensions.get(&name) { + Some(shape) => variable(shape), + None => match objects::property(tree, id, native, dimensions)? { + Some((property, _)) => scalar(&property.r#type), + None => constant(&tree.state, &name, dimensions), + }, + } + } + ExprKind::Member { .. } => match method(tree, id, native, dimensions)? { + // A method called without parentheses (6.19.5.7). + Some((method, _, domain)) => method.returns_member().then_some(domain), + None => match objects::static_property(tree, id, native, dimensions)? + .or_else(|| call_name(&tree.state, id, native)) + .and_then(|name| dimensions.get(&name)) + { + // A static property or a package variable. + Some(shape) => variable(shape), + // A package-qualified enum constant. + None if let Some(domain) = call_name(&tree.state, id, native) + .and_then(|name| constant(&tree.state, &name, dimensions)) => + { + Some(domain) + } + None => match objects::property(tree, id, native, dimensions)? { + Some((property, _)) => scalar(&property.r#type), + // A member of a packed struct. + None => dimensions::operand_shape(id, tree, dimensions) + .ok() + .flatten() + .and_then(|shape| variable(&shape)), + }, + }, + }, + ExprKind::Select { .. } => element(tree, id, native, dimensions)?, + ExprKind::Call { expression, .. } => { + if let Some((method, _, domain)) = method(tree, *expression, native, dimensions)? { + method.returns_member().then_some(domain) + } else if let ExprKind::Member { + expression: base, + name, + .. + } = &native.expression(ungroup(*expression, native)).kind + && matches!(name.spelling.as_str(), "pop_front" | "pop_back") + && let Some(container) = containers::native_type(*base, native, tree, dimensions)? + { + // An element popped from a queue (7.10.2.4, 7.10.2.5). + scalar(&container.element) + } else { + let name = match objects::method(tree, *expression, native, dimensions)? { + Some((name, _, _)) => Some(name), + None => call_name(&tree.state, *expression, native), + }; + name.and_then(|name| { + dimensions + .function_return_types + .get(&name) + .and_then(|metadata| metadata.enum_domain.clone()) + .or_else(|| { + dimensions + .functions + .get(&name) + .and_then(|function| function.return_enum_domain.clone()) + }) + }) + } + } + ExprKind::Cast { target, .. } => { + let target = ungroup(*target, native); + let ty = if let Some(name) = call_name(&tree.state, target, native) { + dimensions.type_aliases.get(&name).cloned() + } else if let ExprKind::Type(id) = native.expression(target).kind { + type_binding::binding::bind_in(id, native, tree, dimensions)? + } else { + None + }; + ty.as_ref().and_then(scalar) + } + ExprKind::Conditional { + then_expression, + else_expression, + .. + } => { + let then_domain = domain(tree, *then_expression, native, dimensions)?; + let else_domain = domain(tree, *else_expression, native, dimensions)?; + then_domain.filter(|domain| else_domain.as_ref() == Some(domain)) + } + _ => None, + }) +} + +/// The enumerated type of a value of type `ty`. +fn scalar(ty: &Type) -> Option> { + (ty.unpacked_ranges.is_empty() && ty.container.is_none()) + .then(|| ty.enum_domain.clone()) + .flatten() +} + +/// The enumerated type of a value of a variable of shape `shape`. +fn variable(shape: &VariableDimensions) -> Option> { + (shape.unpacked.is_empty() && shape.container.is_none()) + .then(|| shape.enum_domain.clone()) + .flatten() +} + +/// The enumerated type of enum constant `name`: the named type of its scope +/// declaring a member of that name and value. A qualified constant is one +/// of a type of the scope that qualifies it, and an unqualified one that no +/// local type declares is the package item an import makes visible; other +/// scopes may declare members of the same name and value. +fn constant( + state: &AnalysisState, + name: &str, + dimensions: &PackedDimensions, +) -> Option> { + let value = *dimensions.const_env.get(name)?; + let find = |scope: Option<&str>, member: &str| { + let mut candidates = dimensions + .type_aliases + .iter() + .filter(|(alias, _)| match scope { + Some(scope) => alias + .strip_prefix(scope) + .is_some_and(|rest| rest.starts_with("::")), + None => !alias.contains("::"), + }) + .filter_map(|(_, ty)| ty.enum_domain.as_ref()) + .filter(|domain| { + domain + .members + .iter() + .any(|candidate| candidate.name == member && candidate.value == value) + }); + let domain = candidates.next()?; + candidates + .all(|other| other == domain) + .then(|| domain.clone()) + }; + match name.rsplit_once("::") { + Some((scope, member)) => find(Some(scope), member), + None => find(None, name).or_else(|| { + let qualified = scope::imported(state).aliases.get(name)?.clone(); + let (scope, member) = qualified.rsplit_once("::")?; + find(Some(scope), member) + }), + } +} + +/// The enumerated type of an element select `id` of an unpacked array or +/// container whose elements are of one. +fn element( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted>> { + let mut root = ungroup(id, native); + let mut selects = 0; + while let ExprKind::Select { + expression, + dimension, + } = &native.expression(root).kind + { + if !matches!(dimension.kind, DimensionKind::Index(_)) { + return Ok(None); + } + if selects == 0 + && let Some(container) = containers::native_type(*expression, native, tree, dimensions)? + { + return Ok(scalar(&container.element)); + } + selects += 1; + root = ungroup(*expression, native); + } + let (unpacked, domain, packed_enum) = match &native.expression(root).kind { + ExprKind::Name(name) + if let Some(shape) = + dimensions.get(&instances::normalize_identifier(&name.spelling)) => + { + if shape.container.is_some() { + return Ok(None); + } + ( + shape.unpacked.len(), + shape.enum_domain.clone(), + shape.packed_enum, + ) + } + // A static property or a package variable. + ExprKind::Member { .. } + if let Some(shape) = objects::static_property(tree, root, native, dimensions)? + .or_else(|| call_name(&tree.state, root, native)) + .and_then(|name| dimensions.get(&name)) => + { + if shape.container.is_some() { + return Ok(None); + } + ( + shape.unpacked.len(), + shape.enum_domain.clone(), + shape.packed_enum, + ) + } + ExprKind::Name(_) | ExprKind::Member { .. } => { + match objects::property(tree, root, native, dimensions)? { + Some((property, _)) if property.r#type.container.is_none() => ( + property.r#type.unpacked_ranges.len(), + property.r#type.enum_domain.clone(), + property.r#type.packed_enum, + ), + _ => return Ok(None), + } + } + _ => return Ok(None), + }; + if packed_enum && selects > unpacked { + return Err(unsupported( + "method of an element of a packed array of enums", + )); + } + Ok(domain.filter(|_| unpacked == selects)) +} + +/// The value of `method` of `domain` called on `receiver` with `count`. +pub(super) fn call( + state: &AnalysisState, + method: Method, + domain: &EnumDomain, + receiver: Option, + count: Option, + dimensions: &PackedDimensions, +) -> Converted { + let members = &domain.members; + let member = |index: usize| { + Expr::Literal(format_typed_parameter_literal( + members[index].value, + domain.width, + domain.signed, + )) + }; + let int = |value: usize| Expr::Literal(format_typed_parameter_literal(value as i128, 32, true)); + let wide = + |value: usize| Expr::Literal(format_typed_parameter_literal(value as i128, 64, false)); + let lookup = |width, signed, selector, pairs: Vec<(Expr, Expr)>, default| Expr::Call { + callee: Callee::Lookup { width, signed }, + args: std::iter::once(Some(selector)) + .chain( + pairs + .into_iter() + .flat_map(|(key, value)| [Some(key), Some(value)]), + ) + .chain(std::iter::once(Some(default))) + .collect(), + arg_order: Vec::new(), + }; + let count_members = members.len(); + let receiver = receiver.ok_or_else(disagreement)?; + // A result that does not depend on the receiver still evaluates it once, + // for the effects of the calls it makes. + let evaluated = |value: Expr, width, signed| { + let mut effects = false; + lifetimes::visit_calls(&receiver, &mut |callee, _| effects |= callee.is_effectful()); + if effects { + lookup(width, signed, receiver.clone(), Vec::new(), value) + } else { + value + } + }; + Ok(match method { + Method::First => evaluated(member(0), domain.width, domain.signed), + Method::Last => evaluated(member(count_members - 1), domain.width, domain.signed), + Method::Num => evaluated(int(count_members), 32, true), + Method::Next | Method::Prev => { + // A value that is no member gives the default initial value of + // the base type (6.19.5.3, 6.19.5.4, Table 6-7). + let default = Expr::Literal(if domain.four_state { + format!("{}'bx", domain.width) + } else { + format!("{}'b0", domain.width) + }); + // `int unsigned N`: only N modulo the number of members matters. + // The count converts to the formal's type as in an assignment, + // extended by its own signedness; the type is 2-state, so unknown + // bits become 0. + let count = casts::runtime_cast_target_expr( + state, + casts::RuntimeCastTarget::Integral { + target: ExprType { + width: 32, + signed: false, + }, + numeric_size: false, + two_state: true, + }, + count.unwrap_or_else(|| int(1)), + dimensions, + )?; + let constant = expr_to_const(state, count.clone()) + .and_then(|count| eval_ast_const_expr(state, &count, &dimensions.const_env)) + .map(|count| (count as u32 as usize) % count_members); + if let Some(shift) = constant { + let shift = if method == Method::Next { + shift + } else { + count_members - shift + }; + let pairs = (0..count_members) + .map(|index| (member(index), member((index + shift) % count_members))) + .collect(); + lookup( + domain.width, + domain.signed, + receiver.clone(), + pairs, + default, + ) + } else { + // The receiver's index, or 2N for a value that is no member, + // plus the shift selects from the members repeated twice. + let index = lookup( + 64, + false, + receiver.clone(), + (0..count_members) + .map(|index| (member(index), wide(index))) + .collect(), + wide(2 * count_members), + ); + let shift = Expr::Resize { + expr: Box::new(Expr::Binary { + left: Box::new(count), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format_typed_parameter_literal( + count_members as i128, + 32, + false, + ))), + }), + width: 64, + signed: false, + }; + let position = if method == Method::Next { + Expr::Binary { + left: Box::new(index), + op: BinaryOp::Add, + right: Box::new(shift), + } + } else { + Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(index), + op: BinaryOp::Add, + right: Box::new(wide(count_members)), + }), + op: BinaryOp::Sub, + right: Box::new(shift), + } + }; + let pairs = (0..2 * count_members) + .map(|position| (wide(position), member(position % count_members))) + .collect(); + lookup(domain.width, domain.signed, position, pairs, default) + } + } + Method::Name => { + // The bytes of each name, which a value that is no member + // replaces by the empty string (6.19.5.6). + let width = 8 * members + .iter() + .map(|member| member.name.len()) + .max() + .unwrap_or(0) + .max(1); + let pairs = (0..count_members) + .map(|index| { + let bytes = members[index].name.as_bytes(); + let name = if bytes.is_empty() { + "8'h0".to_string() + } else { + format!( + "{}'h{}", + 8 * bytes.len(), + bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::() + ) + }; + (member(index), Expr::Literal(name)) + }) + .collect(); + let bytes = lookup( + width, + false, + receiver.clone(), + pairs, + Expr::Literal(format!("{width}'h0")), + ); + strings::call(StringOp::FromBits, vec![bytes]) + } + }) +} 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 8366951d85e..fa9c870bdf0 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -857,7 +857,7 @@ pub(super) fn random_selection( return Err(unsupported("randomization of a 4-state class property")); } if property.field.handle.is_some() - || (property.r#type.is_enum && property.r#type.enum_values.is_none()) + || (property.r#type.is_enum && property.r#type.enum_domain.is_none()) || (property.randc && property.cyclic_domain_size().is_none()) { return Err(unsupported( 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 9354c71e6c2..86071720434 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs @@ -160,7 +160,7 @@ pub(super) fn check_actual( /// 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 values. +/// state count; an enumeration only by its members. fn equivalent( state: &AnalysisState, a: &VariableDimensions, @@ -210,7 +210,7 @@ fn equivalent( if a.real != b.real || a.string != b.string || a.class != b.class { return false; } - if (a.enum_values.is_some() || b.enum_values.is_some()) && a.enum_values != b.enum_values { + if (a.enum_domain.is_some() || b.enum_domain.is_some()) && a.enum_domain != b.enum_domain { return false; } let width = |shape: &VariableDimensions| { 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 5e4a83e2b54..74b0acb2d54 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -171,7 +171,10 @@ pub(in crate::ast) fn native_string( } ExprKind::Call { expression, .. } => { method(tree, *expression, native, dimensions).is_some_and(|(op, _)| op.returns_string()) + || enum_name(tree, *expression, native, dimensions) } + // `e.name` without parentheses (6.19.5.6, 6.19.5.7). + ExprKind::Member { .. } if enum_name(tree, id, native, dimensions) => true, // A string property of a class object. _ => objects::property(tree, id, native, dimensions) .ok() @@ -182,6 +185,20 @@ pub(in crate::ast) fn native_string( } } +/// Whether native callee expression `id` names the `name` method of an +/// enumerated type (6.19.5.6). +fn enum_name( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> bool { + enums::method(tree, id, native, dimensions) + .ok() + .flatten() + .is_some_and(|(method, _, _)| method.returns_string()) +} + /// The string method that native callee expression `id` names, with the /// expression it is called on. pub(in crate::ast) fn method( diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 541048b79e3..c40ffb644be 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -253,6 +253,10 @@ fn native_signature( }), return_signed: result.is_some_and(|ty| ty.signed), return_is_2state: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::Bit), + return_enum_domain: ty + .as_ref() + .filter(|ty| ty.unpacked_ranges.is_empty()) + .and_then(|ty| ty.enum_domain.clone()), return_type: ty .filter(|ty| { !ty.members.is_empty() diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 68627134adb..a88b3e7d17a 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -2089,6 +2089,7 @@ mod tests { is_2state: false, string: false, pattern_type: None, + enum_domain: None, }; let inner = FunctionReturnMetadata { arguments: None, @@ -2099,6 +2100,7 @@ mod tests { is_2state: true, string: false, pattern_type: None, + enum_domain: None, }; let dimensions = PackedDimensions { function_return_types: [ 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 7b3088d9d89..f44b20d91d2 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs @@ -150,7 +150,8 @@ impl CallSites for Type { fn call_sites(&self, visit: &mut dyn FnMut(usize)) { let Type { is_enum: _, - enum_values: _, + enum_domain: _, + packed_enum: _, kind: _, is_signed: _, packed_ranges, @@ -189,7 +190,8 @@ impl CallSites for VariableDimensions { let VariableDimensions { container: _, randomizable: _, - enum_values: _, + enum_domain: _, + packed_enum: _, real: _, string: _, class: _, diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index bcbffdacd43..da4b901db5a 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -124,7 +124,7 @@ pub(super) fn expr_signedness_with_return_types( .. } => Some(op.result_type().1), Expr::Call { - callee: Callee::Checked { signed, .. }, + callee: Callee::Checked { signed, .. } | Callee::Lookup { signed, .. }, .. } => Some(*signed), Expr::Call { 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 19bba63f9ca..3c033e560da 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -76,7 +76,8 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 4e1615ca057..7f519807931 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -567,6 +567,10 @@ pub(super) fn parameters_from_native_with_environment( parameter.packed_ranges = parameter_ranges.clone(); parameter.members = parameter_members.clone(); parameter.signed_element_depth = parameter_signed_element_depth; + parameter.enum_domain = declared_alias + .as_ref() + .filter(|_| !alias_has_use_site_dimensions) + .and_then(|alias| alias.enum_domain.clone()); validate_parameter_materialization_width( parameter .resolved_type(&environment.types) diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index bfb477f6249..f05a05e2eb9 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -516,7 +516,8 @@ fn pattern_items( VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 8d0254a853d..0e5444bf9a0 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -139,7 +139,8 @@ fn select<'a>( let sub = Shape::Owned(Rc::new(VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, @@ -250,7 +251,8 @@ fn select<'a>( let bit = Shape::Owned(Rc::new(VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index ae82c8c776e..2a7e94b0bc9 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -79,8 +79,9 @@ pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { container: r#type.container.clone(), randomizable: r#type.container.is_none() - && (!r#type.is_enum || r#type.enum_values.is_some()), - enum_values: r#type.enum_values.clone(), + && (!r#type.is_enum || r#type.enum_domain.is_some()), + enum_domain: r#type.enum_domain.clone(), + packed_enum: r#type.packed_enum, real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(r#type.kind(), TypeKind::String), class: r#type.class().map(str::to_owned), @@ -123,7 +124,8 @@ pub(super) fn int_type() -> Type { Type { container: None, is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, kind: TypeKind::Bit, is_signed: true, packed_ranges: vec![PackedRange::new( diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 7cf4e43d484..1b0503e0a00 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -229,7 +229,7 @@ fn lower_methods( if property.constant || property.field.handle.is_some() || (property.r#type.is_enum - && property.r#type.enum_values.is_none()) + && property.r#type.enum_domain.is_none()) { continue; } @@ -383,7 +383,12 @@ fn random_property( classes::object_call(op, vec![Expr::Ident(this.into())]) }; let mut body = Vec::new(); - let value = if let Some(values) = &property.r#type.enum_values { + let value = if let Some(values) = property + .r#type + .enum_domain + .as_ref() + .map(|domain| domain.values()) + { let count = values.len() as u64; let threshold = count.wrapping_neg() % count; let draw = builder.declare("$enum_draw", classes::unsigned_type(64)); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/references.rs b/crates/celox-sv-analyzer/src/ast/procedural/references.rs index 42208409462..62d4d1406b4 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/references.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/references.rs @@ -218,7 +218,7 @@ fn check_formal( .is_none_or(|direction| direction.is_written()), Callee::System(function) => function.writes_argument(position), Callee::Object(op) => op.writes_argument(position), - Callee::String(_) | Callee::Checked { .. } => false, + Callee::String(_) | Callee::Checked { .. } | Callee::Lookup { .. } => false, } }) }; diff --git a/crates/celox-sv-analyzer/src/ast/processes.rs b/crates/celox-sv-analyzer/src/ast/processes.rs index 8e3e6265a3d..199a93cd92a 100644 --- a/crates/celox-sv-analyzer/src/ast/processes.rs +++ b/crates/celox-sv-analyzer/src/ast/processes.rs @@ -5,10 +5,25 @@ use celox_sv_syntax::{Declarations, ExprId, ExprKind}; pub(super) const CLASS: &str = "$builtin::process"; +/// `enum state { FINISHED, RUNNING, WAITING, SUSPENDED, KILLED }` (9.7). +const STATES: [&str; 5] = ["FINISHED", "RUNNING", "WAITING", "SUSPENDED", "KILLED"]; + pub(super) fn state_type() -> Type { let mut ty = procedural::int_type(); ty.is_enum = true; - ty.enum_values = Some((0..5).collect()); + ty.enum_domain = Some(Arc::new(enums::EnumDomain { + members: STATES + .into_iter() + .zip(0..) + .map(|(name, value)| enums::EnumMember { + name: name.into(), + value, + }) + .collect(), + width: 32, + signed: true, + four_state: false, + })); ty } @@ -66,6 +81,45 @@ pub(super) fn qualified_type(path: &[celox_sv_syntax::TypeSegment]) -> Option, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Option> { + let id = expression_binding::ungroup(id, native); + let (callee, called) = match &native.expression(id).kind { + ExprKind::Call { expression, .. } => (*expression, true), + _ => (id, false), + }; + let ExprKind::Member { + expression: receiver, + separator, + name, + } = &native.expression(callee).kind + else { + return None; + }; + let member = instances::normalize_identifier(&name.spelling); + let state = match separator.as_str() { + "::" => { + !called + && STATES.contains(&member.as_str()) + && scope(tree, *receiver, native, dimensions) + } + "." => { + member == "status" + && expression_binding::object_native_class(tree, *receiver, native, dimensions) + .as_deref() + == Some(CLASS) + } + _ => false, + }; + state.then(|| state_type().enum_domain).flatten() +} + pub(super) fn value( tree: &AnalysisContext<'_>, root: ExprId, @@ -96,11 +150,7 @@ pub(super) fn value( return Ok(None); } let method = instances::normalize_identifier(&name.spelling); - if static_receiver - && let Some(code) = ["FINISHED", "RUNNING", "WAITING", "SUSPENDED", "KILLED"] - .iter() - .position(|&n| n == method) - { + if static_receiver && let Some(code) = STATES.iter().position(|&n| n == method) { if !args.is_empty() { return Err(unsupported("call of process state constant")); } 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 9cfab268185..f58f4205990 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -229,7 +229,8 @@ fn bind_in_mode( if matches!(mode, BindingMode::Use) { validate_enum_initializers(id, native, tree, context, &ty)?; } - ty.enum_values = enum_values(id, native, tree, context, &ty); + ty.enum_domain = enum_values(id, native, tree, context, &ty); + ty.packed_enum = !native.data_type(id).packed_dimensions.is_empty(); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); } @@ -330,7 +331,8 @@ fn bind_in_mode( outer.extend(ty.packed_ranges); ty.packed_ranges = outer; ty.is_enum = true; - ty.enum_values = enum_values(id, native, tree, context, &ty); + ty.enum_domain = enum_values(id, native, tree, context, &ty); + ty.packed_enum = !native.data_type(id).packed_dimensions.is_empty(); values.push(ty); } Job::Aggregate { @@ -661,7 +663,7 @@ fn enum_values( tree: &AnalysisContext<'_>, context: &PackedDimensions, ty: &Type, -) -> Option> { +) -> Option> { let data = native.data_type(id); if !data.packed_dimensions.is_empty() { return None; @@ -676,6 +678,7 @@ fn enum_values( let mut env = context.const_env.clone(); let mut next = 0i128; let mut values = Vec::new(); + let mut members = Vec::new(); for item in items { if !item.dimensions.is_empty() { return None; @@ -710,9 +713,20 @@ fn enum_values( } values.push(value); let name = normalize_identifier(&item.name.spelling); + members.push(enums::EnumMember { + name: name.clone(), + value, + }); env.insert(name.clone(), value); dimensions::insert_parameter_type_markers(&mut env, &name, shape); next = value.checked_add(1)?; } - (!values.is_empty()).then_some(values) + (!members.is_empty()).then(|| { + Arc::new(enums::EnumDomain { + members, + width: shape.width, + signed: shape.signed, + four_state: !matches!(ty.kind(), TypeKind::Bit), + }) + }) } diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 95e10b03d5f..85f0915df12 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -243,7 +243,8 @@ pub(super) fn enclose_aliased_packed_type( // array they form is unsigned, whatever its elements (IEEE 1800-2023 // 7.4.1); a type name takes no signing of its own. if !direct_ranges.is_empty() { - r#type.enum_values = None; + r#type.packed_enum |= r#type.is_enum; + r#type.enum_domain = None; r#type.signed_element_depth = if r#type.is_signed { Some(direct_ranges.len()) } else { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 82a7feacd2e..78810f3ad73 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -1075,6 +1075,15 @@ pub enum Callee { width: usize, signed: bool, }, + /// A table lookup with the arguments `selector, key, value, ..., + /// default`: the value of the first key the selector matches with case + /// equality, else the default, resized to `width` and `signed`. The + /// selector is evaluated once. Used for enumerated type methods + /// (IEEE 1800-2023 6.19.5). + Lookup { + width: usize, + signed: bool, + }, /// A user function or a DPI import, by its resolved name. Subroutine(String), System(SystemFunction), @@ -1090,14 +1099,22 @@ impl Callee { pub fn subroutine(&self) -> Option<&str> { match self { Self::Subroutine(name) => Some(name), - Self::System(_) | Self::String(_) | Self::Object(_) | Self::Checked { .. } => None, + Self::System(_) + | Self::String(_) + | Self::Object(_) + | Self::Checked { .. } + | Self::Lookup { .. } => None, } } /// The system function, if this is one. pub fn system(&self) -> Option { match self { - Self::Subroutine(_) | Self::String(_) | Self::Object(_) | Self::Checked { .. } => None, + Self::Subroutine(_) + | Self::String(_) + | Self::Object(_) + | Self::Checked { .. } + | Self::Lookup { .. } => None, Self::System(function) => Some(*function), } } @@ -1106,7 +1123,9 @@ impl Callee { /// lowered as an integral operation; see [`SystemFunction::result_type`]. pub fn result_type(&self) -> Option<(usize, bool)> { match self { - Self::Checked { width, signed } => Some((*width, *signed)), + Self::Checked { width, signed } | Self::Lookup { width, signed } => { + Some((*width, *signed)) + } Self::String(op) => Some(op.result_type()), Self::Object(op) => Some(op.result_type()), _ => self.system()?.result_type(), @@ -1116,7 +1135,7 @@ impl Callee { /// Rename a user subroutine with `rename`. pub fn map_subroutine(self, rename: impl FnOnce(String) -> String) -> Self { match self { - Self::Checked { .. } => self, + Self::Checked { .. } | Self::Lookup { .. } => self, Self::Subroutine(name) => Self::Subroutine(rename(name)), Self::System(function) => Self::System(function), Self::String(op) => Self::String(op), @@ -1128,7 +1147,8 @@ impl Callee { /// the analyzer must not run it twice: user subroutines may have side /// effects, as do the random number functions. pub fn is_effectful(&self) -> bool { - self.system().is_none_or(SystemFunction::is_effectful) + !matches!(self, Self::Lookup { .. }) + && self.system().is_none_or(SystemFunction::is_effectful) } } @@ -1136,6 +1156,7 @@ impl fmt::Display for Callee { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Checked { .. } => f.write_str("tagged union access"), + Self::Lookup { .. } => f.write_str("enumeration lookup"), Self::Subroutine(name) => f.write_str(name), Self::System(function) => f.write_str(function.name()), Self::String(op) => op.fmt(f), diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index dc900c8f812..4035abd9cde 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -239,6 +239,29 @@ pub(crate) fn eval_const_expr_in_env( constants, ) } + Callee::Lookup { width, signed } => { + let (selector, rest) = args.split_first()?; + let (default, pairs) = rest.split_last()?; + let selector = eval_const_expr_in_env(selector, constants)?; + let (pairs, []) = pairs.as_chunks::<2>() else { + return None; + }; + let mut value = default; + for [key, candidate] in pairs { + if eval_const_expr_in_env(key, constants)? == selector { + value = candidate; + break; + } + } + eval_const_expr_in_env( + &ConstExpr::Resize { + expr: Box::new(value.clone()), + width: *width, + signed: *signed, + }, + constants, + ) + } Callee::String(_) | Callee::Object(_) => None, }, ConstExpr::Unary { op, expr: operand } => { diff --git a/crates/celox-test-suite/src/sv/cases/types.vtest b/crates/celox-test-suite/src/sv/cases/types.vtest index abdd5e37810..4f509043de1 100644 --- a/crates/celox-test-suite/src/sv/cases/types.vtest +++ b/crates/celox-test-suite/src/sv/cases/types.vtest @@ -460,3 +460,68 @@ (top Top) (eval) (assert_eq y 0) (assert_eq array_values 0)) + +(case enum_methods_iterate_members + (source "enum_methods.sv" #" + module Top(output bit done); + typedef enum {red, green, blue, yellow} Colors; + Colors c, first, last; + initial begin + c = c.first; + forever begin + $display("%s : %0d", c.name, c); + if (c == c.last) break; + c = c.next; + end + first = c.first(); + last = c.last(); + $display("num=%0d first=%s last=%s", c.num(), first.name(), last.name()); + done = 1; + end + endmodule + "#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "red : 0\ngreen : 1\nblue : 2\nyellow : 3\nnum=4 first=red last=yellow\n")) + +(case enum_methods_wrap_and_count + (source "enum_methods.sv" #" + module Top(output bit done); + typedef enum bit [2:0] {A = 3'd1, B = 3'd4, C = 3'd6} E; + E e; + initial begin + e = B; + $display("%0d %0d %0d %0d %0d", e.next(), e.next(2), e.prev(), e.prev(4), e.next(3)); + e = E'(3'd5); + $display("[%s] %0d %0d", e.name(), e.next(), e.prev()); + done = 1; + end + endmodule + "#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "6 1 1 1 4\n[] 0 0\n")) + +(case enum_methods_in_combinational_and_sequential_logic + (source "enum_methods.sv" #" + module Top(input bit clk, input bit [1:0] sel, + output bit [1:0] following, output bit [1:0] preceding, + output bit [1:0] state); + typedef enum bit [1:0] {IDLE, RUN, DONE} S; + S current, register; + always_comb current = S'(sel); + always_comb following = current.next(2); + always_comb preceding = current.prev(); + always_ff @(posedge clk) register <= register.next(); + assign state = register; + endmodule + "#) + (top Top) + (set sel 1) (set clk 0) (eval) + (assert_eq following 0) + (assert_eq preceding 0) + (set sel 2) (eval) + (assert_eq following 1) + (assert_eq preceding 1) + (tick clk) (tick clk) + (assert_eq state 2) + (tick clk) + (assert_eq state 0)) diff --git a/crates/celox/tests/frontends/systemverilog/references.rs b/crates/celox/tests/frontends/systemverilog/references.rs index d7a97b99a53..72484d39577 100644 --- a/crates/celox/tests/frontends/systemverilog/references.rs +++ b/crates/celox/tests/frontends/systemverilog/references.rs @@ -54,3 +54,46 @@ sv_backends! { @case "references::ref_element_after_an_input_in_forked_activations"; } } + +/// A ref actual of an enumerated type is equivalent only to a formal of the +/// same enumerated type (IEEE 1800-2023 6.22.2): not to its base type, nor +/// to another enumeration of the same base and values. +#[test] +fn ref_actuals_of_enumerated_types_match_only_their_enumeration() { + let source = |formal: &str, actual: &str| { + format!( + "module Top(output logic [1:0] y); + typedef enum bit [1:0] {{A, B, C}} E; + typedef enum bit [1:0] {{P, Q, R}} F; + typedef bit [1:0] U; + {actual} v = {{1'b0, 1'b1}}; + function automatic void advance(ref {formal} x); + x = {formal}'(x + 1); + endfunction + initial begin advance(v); y = v; end + endmodule" + ) + }; + let build = |formal: &str, actual: &str| { + let source = source(formal, actual); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("ref_enums.sv"))], + "Top", + ) + .build() + .map_err(|error| format!("{error:?}")) + }; + let mut sim = build("E", "E").unwrap(); + sim.run_until(0).unwrap(); + let y = sim.signal("y"); + assert_eq!(sim.get(y), num_bigint::BigUint::from(2u8)); + for (formal, actual) in [("E", "F"), ("F", "E"), ("E", "U"), ("U", "E")] { + let error = build(formal, actual) + .err() + .unwrap_or_else(|| panic!("ref {formal} from {actual} must be rejected")); + assert!( + error.contains("the actual's type is not equivalent to the formal's"), + "ref {formal} from {actual}: {error}" + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/types.rs b/crates/celox/tests/frontends/systemverilog/types.rs index c13f8dbd4dc..54233f3da0f 100644 --- a/crates/celox/tests/frontends/systemverilog/types.rs +++ b/crates/celox/tests/frontends/systemverilog/types.rs @@ -1,3 +1,5 @@ +use super::*; + sv_backends! { fn inherited_parameter_aliases_materialize_replication_masks(sim) { @case "types::inherited_parameter_aliases_materialize_replication_masks"; @@ -73,3 +75,198 @@ sv_backends! { @case "types::undriven_internal_nets_convert_to_two_state_zero"; } } + +sv_backends! { + fn enum_methods_iterate_members(sim) { + @case "types::enum_methods_iterate_members"; + } + + fn enum_methods_wrap_and_count(sim) { + @case "types::enum_methods_wrap_and_count"; + } + + fn enum_methods_in_combinational_and_sequential_logic(sim) { + @case "types::enum_methods_in_combinational_and_sequential_logic"; + } +} + +// Receivers, counts and contexts that the external simulators of the shared +// suite do not accept: Verilator rejects non-constant counts and methods of +// casts, constants and call results; Icarus rejects methods of call results +// and of class properties, and methods in continuous assignments; xezim calls a method +// of an array element as one of a class handle and returns 0 instead of the +// 4-state base's 'x for a value that is no member (IEEE 1800-2023 6.19.5.3, +// 6.19.5.4, Table 6-7). +sv_backends! { + fn enum_methods_of_any_enum_expression(sim) { + @setup { + let source = r#" +package p; + typedef enum {PA, PB, PC} P; + typedef enum {SHARED, OTHER} Q; + P states[2] = '{PB, PC}; + localparam P START = PB; +endpackage +package r; + typedef enum {SHARED, MIDDLE, LAST} R; +endpackage +module Top(output bit ok, output logic [1:0] unknown_next, output logic [1:0] unknown_prev, + output bit unnamed, output bit [1:0] continuous, output bit [1:0] gap_next, + output bit [3:0] chained); + typedef enum bit [3:0] {W0, W1, W2, W3, W4, W5, W6, W7, W8, W9, W10, W11, W12, W13, W14, W15} W; + W wide; + // Each nested lookup lowers its selector once, not once per member. + assign chained = wide.next().next().next().next().next().next().next().next(); + typedef enum logic [1:0] {IDLE, RUN, DONE} S; + typedef enum bit [1:0] {K0, K1, K2} K; + typedef enum bit [2:0] {A = 3'd1, B = 3'd4, C = 3'd6} E; + S unknown; + S queue[$]; + S states[3]; + E e; + K current, gap; + bit [2:0] steps; + logic signed [2:0] signed_count; + typedef enum logic [1:0] {LA, LB, LC} L; + L le; + // Parameters of an enumerated type. + localparam S INITIAL = RUN; + localparam E LAST = C; + logic [1:0] unknown_count; + int unsigned n; + int calls; + class Machine; + static S initial_state = DONE; + K state; + function K current(); + return state; + endfunction + function string describe(); + return state.name(); + endfunction + endclass + function automatic S advance(); + calls++; + return RUN; + endfunction + assign continuous = current.next(steps); + assign gap_next = gap.next(2); + initial begin + Machine m; + process running; + ok = 1; + e = B; + ok &= e.next(2).name() == "A" && e.next.next.name == "A" && e.prev.name == "A"; + ok &= S'(0).name() == "IDLE" && E'(3'd6).prev().name() == "B"; + ok &= DONE.prev().name() == "RUN" && RUN.num() == 3 && C.next() == A; + states[1] = DONE; + ok &= states[1].name() == "DONE" && states[1].next.name == "IDLE"; + ok &= Machine::initial_state.name() == "DONE"; + queue.push_back(RUN); + ok &= queue[0].prev().name() == "IDLE"; + ok &= advance().next(2).name() == "IDLE" && calls == 1; + // Results that do not depend on the receiver still evaluate it once. + ok &= advance().first() == IDLE && advance().last() == DONE && advance().num() == 3; + ok &= calls == 4; + ok &= p::PA.next().name() == "PB" && p::PC.prev(2).name() == "PA" && p::PB.num() == 3; + // Each package's enumeration, though both declare SHARED = 0. + ok &= p::states[0].name() == "PB" && p::states[1].next() == p::PA; + ok &= p::SHARED.num() == 2 && r::SHARED.num() == 3 && r::SHARED.next().name() == "MIDDLE"; + queue = '{RUN, DONE}; + ok &= queue.pop_front().name() == "RUN" && queue.pop_back().next() == IDLE; + ok &= DONE.name().len() == 4 && DONE.name().tolower() == "done"; + ok &= RUN.name.toupper() == "RUN" && RUN.next.name.tolower() == "done"; + m = new; + m.state = K1; + ok &= m.current().next().name() == "K2" && m.state.next() == K2; + ok &= m.state.name() == "K1" && m.describe() == "K1"; + n = 5; + ok &= e.next(n) == A && e.prev(n) == C; + n = 32'hffff_ffff; + ok &= e.next(n) == B && e.prev(n) == B; + // A signed count converts to `int unsigned` with sign extension, at + // run time as for a constant: -1 is a multiple of 3 and -2 is 2 more. + signed_count = -1; + ok &= e.next(signed_count) == B && e.next(3'sb111) == B; + signed_count = -2; + ok &= e.prev(signed_count) == C && e.prev(3'sb110) == C; + // `int unsigned` is 2-state: an unknown count converts to 0. + le = LB; + unknown_count = 'x; + ok &= le.next(unknown_count) === LB && le.prev(unknown_count) === LB; + unknown_count = 2'bz1; + ok &= le.next(unknown_count) === LC; + ok &= INITIAL.next().name() == "DONE" && INITIAL.name() == "RUN"; + ok &= LAST.next() == A && LAST.num() == 3 && p::START.next() == p::PC; + // The status of a process and the constants of its `state` type (9.7). + running = process::self(); + ok &= running.status().name() == "RUNNING" && running.status.next() == process::WAITING; + ok &= process::KILLED.next().name() == "FINISHED" && std::process::RUNNING.num() == 5; + e = E'(3'd5); + ok &= e.prev(n) == 0 && e.next(n) == 0; + unknown_next = unknown.next(); + unknown_prev = unknown.prev(2); + unnamed = unknown.name() == ""; + current = K1; + wide = W3; + gap = K'(3); + steps = 4; + end +endmodule +"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("enum_methods.sv"))], "Top") + .four_state(true); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + for name in ["unknown_next", "unknown_prev"] { + let signal = sim.signal(name); + assert_eq!( + sim.get_four_state(signal), + (BigUint::from(3u8), BigUint::from(3u8)), + "{name}" + ); + } + let unnamed = sim.signal("unnamed"); + assert_eq!(sim.get(unnamed), BigUint::from(1u8)); + let continuous = sim.signal("continuous"); + assert_eq!(sim.get(continuous), BigUint::from(2u8)); + let chained = sim.signal("chained"); + assert_eq!(sim.get(chained), BigUint::from(11u8)); + let gap_next = sim.signal("gap_next"); + assert_eq!(sim.get(gap_next), BigUint::from(0u8)); + } +} + +/// Methods of an element of a packed array of enums are not supported yet; +/// they are rejected, not given the members of another type. +#[test] +fn enum_methods_of_packed_array_elements_are_rejected() { + for (declaration, call) in [ + ( + "typedef enum bit [1:0] {A, B, C} E; E [1:0] states;", + "states[0].next()", + ), + ( + "typedef enum bit [1:0] {A, B, C} E; E [1:0] states;", + "states[1].name() == \"B\"", + ), + ("enum bit [1:0] {X, Y} [1:0] states;", "states[0].first()"), + ] { + let source = + format!("module Top(output bit [1:0] y); {declaration} initial y = {call}; endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("packed_enum_methods.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("{source} must be rejected")) + .to_string(); + assert!( + error.contains("method of an element of a packed array of enums"), + "{error}" + ); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 4bb6f1f82b0..4e1883e7610 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -27,7 +27,7 @@ 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), `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, 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'{...}`) | diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 31f649466a9..aeac453a914 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -25,7 +25,7 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard / soft packed untagged union、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | +| 型 | `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 配列、符号付き・符号なし | | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`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'{...}`) | From 11b51543d2a022fb61ec2102c54dc9e1b440e200 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 15:42:17 +0900 Subject: [PATCH 2/2] feat(sv): initialize process static locals with run-time values A static local of a process may now have a run-time initializer, such as `string s = v.name();` or `C h = new;`. IEEE 1800-2023 6.8 allows any run-time expression and runs it once, before any initial or always procedure starts; Celox runs it, in declaration order, in the existing time-zero initializer process, and keeps the local (and every static local it reads) as module storage. An initializer that reads an automatic variable could only run on each entry and is still rejected, as are non-constant initializers of function statics. IEEE 1800-2023 6.21 says that "an explicit static keyword shall be required when an initialization value is specified as part of a static variable's declaration". Celox already accepts the keyword-less form with a constant initializer, and existing sources (including the sv-tests case 6.19.5.6) omit it, so a keyword-less run-time initializer is accepted in a procedure that runs once, such as `initial`, where running it at time zero instead of on entry cannot repeat. In an `always` procedure it stays rejected, because its author likely meant it to run on every entry; the `static` keyword states the intent there. sv-tests: 6.19.5.6 enum_name, 8.7 constructor and 8.7 constructor_param now pass in both state modes. Change-Id: I99990f956dd5985eb2d1087631ae1f918f2bbd0a --- conformance/sv-tests/expected.tsv | 12 +- crates/celox-sv-analyzer/src/ast.rs | 26 ++++- .../src/ast/const_functions.rs | 1 + crates/celox-sv-analyzer/src/ast/functions.rs | 1 + crates/celox-sv-analyzer/src/ast/lifetimes.rs | 99 ++++++++++++++++- .../celox-sv-analyzer/src/ast/procedural.rs | 8 +- .../src/ast/procedural/control.rs | 1 + .../src/sv/cases/procedural.vtest | 21 ++++ .../frontends/systemverilog/procedural.rs | 4 + crates/celox/tests/sv_lifetimes.rs | 105 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 18 ++- docs/ja/guide/systemverilog-reference.md | 13 ++- 12 files changed, 290 insertions(+), 19 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c1d56b95e5b..aad26f6f9c8 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1187,8 +1187,8 @@ chapter-6/6.19.5.4--enum_prev.sv 2state pass chapter-6/6.19.5.4--enum_prev.sv 4state pass chapter-6/6.19.5.5--enum_num.sv 2state pass chapter-6/6.19.5.5--enum_num.sv 4state pass -chapter-6/6.19.5.6--enum_name.sv 2state fail -chapter-6/6.19.5.6--enum_name.sv 4state fail +chapter-6/6.19.5.6--enum_name.sv 2state pass +chapter-6/6.19.5.6--enum_name.sv 4state pass chapter-6/6.20.2--parameter.sv 2state pass chapter-6/6.20.2--parameter.sv 4state pass chapter-6/6.20.2--parameter_aggregate.sv 2state pass @@ -1557,10 +1557,10 @@ chapter-8/8.5--properties_enum.sv 2state fail chapter-8/8.5--properties_enum.sv 4state fail chapter-8/8.6--methods.sv 2state pass chapter-8/8.6--methods.sv 4state pass -chapter-8/8.7--constructor.sv 2state fail -chapter-8/8.7--constructor.sv 4state fail -chapter-8/8.7--constructor_param.sv 2state fail -chapter-8/8.7--constructor_param.sv 4state fail +chapter-8/8.7--constructor.sv 2state pass +chapter-8/8.7--constructor.sv 4state pass +chapter-8/8.7--constructor_param.sv 2state pass +chapter-8/8.7--constructor_param.sv 4state pass chapter-8/8.7--constructor_super.sv 2state pass chapter-8/8.7--constructor_super.sv 4state pass chapter-8/8.8--typed_constructor.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 1cc4cc9b101..bce87c08b8a 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1263,6 +1263,7 @@ impl Module { subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(syntax_tree), statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; @@ -1330,18 +1331,25 @@ impl Module { &subroutine_directions, comb_processes .iter_mut() - .map(|process| &mut process.body) - .chain(ff_processes.iter_mut().map(|process| &mut process.body)) + .map(|process| (&mut process.body, false)) + .chain( + ff_processes + .iter_mut() + .map(|process| (&mut process.body, false)), + ) .chain( initial_processes .iter_mut() - .map(|process| &mut process.body), + .map(|process| (&mut process.body, !process.repeats)), ), + Some(&body_state.explicit_statics), )?; for subroutine in &subroutines { kept.extend(subroutine.persistent_locals.iter().cloned()); } - static_initializers.append(&mut body_state.static_initializers); + // Statics of subroutines are initialized first: a run-time + // initializer of a process local may call the subroutine. + static_initializers.splice(0..0, body_state.static_initializers.drain(..)); locals.retain(|local| !kept.contains(&local.name)); for name in kept { signals.push(Signal::new(name.clone(), statics[&name].clone())); @@ -1352,10 +1360,18 @@ impl Module { .iter() .position(|process| !process.is_initializer()) .unwrap_or(initial_processes.len()); + // They may read module variables, so they also stay after those + // initializers when processes are reordered by creation. + let creation_order = initial_processes + .iter() + .filter(|process| process.is_initializer()) + .map(|process| process.creation_order) + .max() + .unwrap_or(0); initial_processes.insert( first_block, InitialProcess { - creation_order: 0, + creation_order, site: None, condition: None, body: static_initializers, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index c2450c8a986..22a41a5f0ba 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -503,6 +503,7 @@ fn collect_module_constant_functions( subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(tree), statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: true, }; diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index c40ffb644be..0c0813c79aa 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -75,6 +75,7 @@ pub(super) fn native_functions( subroutine_directions: &directions, automatic, statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 9d191a2934c..fed3e3d3183 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -31,18 +31,27 @@ enum Entry { /// time-zero initializations. /// `directions` gives the argument directions of the subroutines a body /// may call. +/// For the bodies of processes, `explicit` gives the statics declared with +/// the `static` keyword, and each body tells whether its process runs once; +/// see [`initialized_at_time_zero`]. pub(super) fn keep_static_locals<'b, T>( state: &AnalysisState, statics: &HashMap, directions: &Directions, - bodies: impl IntoIterator>, + bodies: impl IntoIterator, bool)>, + explicit: Option<&HashSet>, ) -> Result<(Vec, Vec), AnalyzerError> { let mut kept = Vec::new(); let mut initializers = Vec::new(); if statics.is_empty() { return Ok((kept, initializers)); } - for body in bodies { + let mut bodies = bodies.into_iter().collect::>(); + let initialized = match explicit { + Some(explicit) => initialized_at_time_zero(state, statics, explicit, &bodies), + None => HashSet::default(), + }; + for (body, _) in &mut bodies { let mut concurrent = false; for stmt in body.iter() { stmt.walk(&mut |stmt| concurrent |= matches!(stmt, Stmt::Fork { .. })); @@ -51,6 +60,7 @@ pub(super) fn keep_static_locals<'b, T>( state, body, statics, + &initialized, directions, &mut kept, &mut initializers, @@ -60,10 +70,74 @@ pub(super) fn keep_static_locals<'b, T>( Ok((kept, initializers)) } +/// The static locals of process `bodies` whose initializer is not constant +/// but reads no automatic variable, with the static locals they read. The +/// initializer of a static variable may be any run-time expression, and +/// runs once before any procedure starts (IEEE 1800-2023 6.8, 6.21); these +/// locals keep their value so that the time-zero initialization does that. +/// +/// 6.21 requires the `static` keyword on an initialized static variable of +/// a procedural block, to show that the initializer runs only once. Without +/// it, a non-constant initializer is accepted only in a process that runs +/// once, such as an `initial` procedure, where running it at time zero +/// rather than on entry cannot repeat; in an `always` procedure it remains +/// rejected, like one that reads an automatic variable. +fn initialized_at_time_zero( + state: &AnalysisState, + statics: &HashMap, + explicit: &HashSet, + bodies: &[(&mut Vec, bool)], +) -> HashSet { + let mut initializers = HashMap::default(); + let mut automatic = Vec::new(); + for (body, once) in bodies { + for stmt in body.iter() { + stmt.walk(&mut |stmt| { + if let Stmt::Local { name, init } = stmt { + if statics.contains_key(name) { + let allowed = *once || explicit.contains(name); + initializers.insert(name.as_str(), (init.as_ref(), allowed)); + } else { + automatic.push(name.as_str()); + } + } + }); + } + } + let runtime = |init: &Expr| { + !expr_is_constant(state, init) && !automatic.iter().any(|name| expr_reads(init, name)) + }; + let mut pending = initializers + .iter() + .filter(|(_, (init, allowed))| *allowed && init.is_some_and(runtime)) + .map(|(name, _)| *name) + .collect::>(); + let mut initialized = HashSet::default(); + while let Some(name) = pending.pop() { + let (init, allowed) = initializers.get(name).copied().unwrap_or_default(); + if init.is_some_and(|init| !expr_is_constant(state, init) && !(allowed && runtime(init))) + || !initialized.insert(name.to_string()) + { + continue; + } + if let Some(init) = init { + pending.extend( + initializers + .keys() + .filter(|other| expr_reads(init, other)) + .copied(), + ); + } + } + initialized +} + +#[allow(clippy::too_many_arguments)] fn keep_in( state: &AnalysisState, stmts: &mut Vec, statics: &HashMap, + initialized: &HashSet, directions: &Directions, kept: &mut Vec, initializers: &mut Vec, @@ -75,7 +149,8 @@ fn keep_in( // time slot (IEEE 1800-2023 16.5.1), which the local keeps. if let Stmt::Local { name, init } = &stmts[index] && statics.contains_key(name) - && (concurrent + && (initialized.contains(name) + || concurrent || sampled_reads(&stmts[index + 1..], name) || entry( state, @@ -109,6 +184,7 @@ fn keep_in( state, then_body, statics, + initialized, directions, kept, initializers, @@ -118,6 +194,7 @@ fn keep_in( state, else_body, statics, + initialized, directions, kept, initializers, @@ -130,6 +207,7 @@ fn keep_in( state, &mut item.body, statics, + initialized, directions, kept, initializers, @@ -141,6 +219,7 @@ fn keep_in( state, default, statics, + initialized, directions, kept, initializers, @@ -155,6 +234,7 @@ fn keep_in( state, init, statics, + initialized, directions, kept, initializers, @@ -164,6 +244,7 @@ fn keep_in( state, step, statics, + initialized, directions, kept, initializers, @@ -173,6 +254,7 @@ fn keep_in( state, body, statics, + initialized, directions, kept, initializers, @@ -181,7 +263,16 @@ fn keep_in( } Stmt::Fork { branches, .. } => { for branch in branches { - keep_in(state, branch, statics, directions, kept, initializers, true)?; + keep_in( + state, + branch, + statics, + initialized, + directions, + kept, + initializers, + true, + )?; } } _ => {} diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 2a7e94b0bc9..2502af44cd7 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -50,6 +50,8 @@ pub(super) struct BodyState<'a> { /// The locals declared with a static lifetime: their unique names and /// types. pub statics: Vec<(String, Type)>, + /// The statics declared with the `static` keyword. + pub explicit_statics: HashSet, /// Function static declarations initialized once at time zero. pub static_initializers: Vec, /// Constant calls get a fresh frame, even for static declarations (13.4.3). @@ -1134,6 +1136,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { _ => self.automatic, }; if !automatic { + if native.lifetime.as_deref() == Some("static") { + self.state.explicit_statics.insert(name.clone()); + } let r#type = scoped_type(signal.r#type().clone(), &self.dims.const_env); self.state.statics.push((name.clone(), r#type)); } @@ -2555,7 +2560,8 @@ pub(super) fn lower_subroutine( &tree.state, &retained_types, builder.state.subroutine_directions, - std::iter::once(&mut subroutine.body), + std::iter::once((&mut subroutine.body, false)), + None, )?; if retain_result { kept.extend(subroutine.return_var.clone()); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index 7c9482d730c..f1f8ee21e76 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -708,6 +708,7 @@ mod tests { subroutine_directions: &directions, automatic: false, statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index f83879faaf9..b5b67130277 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -1510,3 +1510,24 @@ (tick clk) (assert_eq result wide) (modify (set update 1)) (tick clk) (assert_eq result 0)) + +(case static_locals_with_run_time_initializers_run_before_procedures + (source "static_initializers.sv" #" + module Top(output bit [7:0] first, output bit [7:0] looped); + int m = 1; + initial m = 5; + initial begin + static int k = m + 1; + static int j = k * 10; + first = 8'(j); + for (int i = 0; i < 3; i++) begin + static int once = k; + once++; + looped = 8'(once); + end + end + endmodule + "#) + (top Top) (run_until 0) + (assert_eq first 20) + (assert_eq looped 5)) diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 669313f8044..60855e24280 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -88,6 +88,10 @@ sv_backends! { @case "procedural::static_function_scratch_arrays_are_filled_before_reads"; } + fn static_locals_with_run_time_initializers_run_before_procedures(sim) { + @case "procedural::static_locals_with_run_time_initializers_run_before_procedures"; + } + fn static_function_result_filled_by_constant_loops(sim) { @case "procedural::static_function_result_filled_by_constant_loops"; } diff --git a/crates/celox/tests/sv_lifetimes.rs b/crates/celox/tests/sv_lifetimes.rs index 7457e738a54..ab80e5e38bb 100644 --- a/crates/celox/tests/sv_lifetimes.rs +++ b/crates/celox/tests/sv_lifetimes.rs @@ -311,6 +311,111 @@ fn static_initializers_run_before_initial_blocks() { ); } +/// A static initializer may be any run-time expression; it runs once, +/// before any procedure starts (IEEE 1800-2023 6.8, 6.21). +#[test] +fn run_time_static_initializers_run_once_before_any_procedure() { + // The initializers read the module variable before the other `initial` + // procedure writes it, and in declaration order. Without the `static` + // keyword that 6.21 requires, an `initial` procedure's locals still + // follow this rule. + assert_eq!( + settled( + "module Top(output logic [31:0] y); + typedef enum {a, b, c} e; + int m = 1; + initial m = 5; + initial begin + e v = b; + string s = v.name(); + int k = m + 1; + static int j = k * 10 + v; + v = c; + y = {s.len() == 1 && s == \"b\", 7'(k), 8'(j), 8'(m)}; + end + endmodule" + ), + 0x82_1505 + ); + // Also when an edge process that makes a host request reorders the + // processes by creation. + assert_eq!( + settled( + "module Top(input logic clk, output logic [7:0] y); + int dummy; + int m = dummy + 4; + always @(posedge clk) $fflush; + initial begin static int k = m + 1; y = k; end + endmodule" + ), + 5 + ); + // A static in a loop is initialized once, not on each iteration. + assert_eq!( + settled( + "module Top(output logic [7:0] y); + int m = 1; + initial for (int i = 0; i < 3; i++) begin + static int once = m; + once++; + y = once; + end + endmodule" + ), + 4 + ); + // An explicitly static local of an `always` procedure as well. + assert_eq!( + ticks( + "module Top(input logic clk, output logic [7:0] y); + int m = 4; + always_ff @(posedge clk) begin static int c = m + 1; c++; y <= c; end + endmodule", + 2 + ), + [6, 7] + ); + // The statics of a function it calls are initialized before it. + assert_eq!( + settled( + "module Top(output logic [7:0] y); + int m = 1; + function int f(input int a); + static int c = 7; + c++; + return c + a; + endfunction + initial begin static int k = f(m); y = k + f(0); end + endmodule" + ), + 18 + ); +} + +/// An initializer that reads an automatic variable, or a keyword-less one +/// of a procedure that repeats, could only run on each entry. +#[test] +fn run_time_static_initializers_that_could_repeat_remain_unsupported() { + for source in [ + "module Top(output logic [7:0] y); + initial begin automatic int x = 3; int t = x + 1; y = t; end + endmodule", + "module Top(output logic [7:0] y); + initial begin automatic int x = 3; static int t = x + 1; y = t; end + endmodule", + "module Top(input logic clk, output logic [7:0] y); + int m = 4; + always_ff @(posedge clk) begin int c = m + 1; c++; y <= c; end + endmodule", + ] { + let detail = error(source); + assert!( + detail.contains("initializer that is not constant"), + "{detail}" + ); + } +} + #[test] fn concatenated_targets_select_with_the_entry_value() { assert_eq!( diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 4e1883e7610..b4b120ffe6a 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -872,8 +872,22 @@ stateful function require `Simulation` or a native testbench to execute the initialization process. Constant function calls use fresh values and do not affect runtime storage (13.4.3). -Task locals that keep their values and nonconstant static initializers remain -unsupported; declare those locals `automatic`. Package function state is a +A static local of a process may have a run-time initializer. It runs once, +in declaration order, before any procedure starts (IEEE 1800-2023 6.8), and +may read module variables and other static locals but no automatic variable. +IEEE 1800-2023 6.21 states that "an explicit static keyword shall be required +when an initialization value is specified as part of a static variable's +declaration". Celox also accepts the declaration without the keyword, as +existing sources often omit it (for example `string s = v.name();` in an +`initial` block): with a constant initializer in any procedure, and with a +run-time initializer in a procedure that runs once, such as `initial`. In an +`always` procedure a run-time initializer without the keyword is rejected, +because its author likely meant it to run on every entry; declare the local +`static` or `automatic` to state which. + +Task locals that keep their values and nonconstant initializers of static +function locals remain unsupported; declare those locals `automatic`. Package +function state is a package variable, which the processes of every instance may write. An interface whose default lifetime (`interface automatic`) differs from that of the module it is used in is rejected. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index aeac453a914..9eb08b0e6c7 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -468,7 +468,18 @@ static な output 引数も、代入しない経路では以前の値を保持 定数関数としての呼び出しは 毎回新しい値を使い、実行時の状態に影響しません(13.4.3)。 -値を保持する task ローカル変数と、定数でない static 初期化子は引き続き未対応です。 +プロセスの static なローカル変数には実行時の値を使う初期化子も書けます。初期化子は宣言順に、 +どの手続きよりも先に 1 回だけ実行し(IEEE 1800-2023 6.8)、モジュールの変数とほかの static な +ローカル変数を読めますが、automatic 変数は読めません。IEEE 1800-2023 6.21 は "an explicit static +keyword shall be required when an initialization value is specified as part of a static variable's +declaration" と定め、手続きブロック内で初期化子を持つ static 変数に `static` キーワードを要求します。 +既存のソースはこのキーワードを省くことが多いため(`initial` ブロック内の `string s = v.name();` など)、 +Celox はキーワードのない宣言も受け付けます。定数の初期化子はどの手続きでも、実行時の値を使う初期化子は +`initial` のように 1 回だけ実行する手続きで受け付けます。`always` 手続きでキーワードなしに実行時の値で +初期化すると、入るたびに実行する意図の可能性が高いためエラーになります。`static` か `automatic` を +指定して意図を示してください。 + +値を保持する task ローカル変数と、関数の static なローカル変数の定数でない初期化子は引き続き未対応です。 これらには `automatic` を指定してください。package 関数の状態は package 変数で、 すべてのインスタンスのプロセスが書き込めます。既定の寿命(`interface automatic`)が 使用先のモジュールと異なる interface は拒否します。