From c2abf1b0f0bcc4d5396ad7e4644a5e25cd557df6 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 09:52:35 +0900 Subject: [PATCH 1/2] feat(sv): support class enum randomization Allow rand enum properties and randomize(member) selection of enum properties in unconstrained classes. Preserve declared enum domains through type aliases and select only their declared values with rejection sampling, including sparse, negative, implicit, singleton, and 64-bit values. Normalize unbased fill initializers to the enum base width and signedness before evaluation. Keep rand_mode, inherited properties, dynamic dispatch, and per-object seeding behavior intact. Keep unsupported or unresolved enum domains explicit rather than randomizing the underlying integer. Reject duplicate values, overflowing implicit values, and X/Z domains. Scope randomization of enums, arrays, and class properties wider than 64 bits remain outside this change. Add four shared regression cases and an analyzer rejection test; update the English and Japanese references. Retain narrow external-tool failure evidence: Verilator 5.052 passes the direct enum, inheritance, and unbased fill cases but randomizes an enum typedef alias as raw integer bits. Icarus 13.0 cannot elaborate class randomization methods in these four cases. Shared assertions are unchanged. Validation: - Analyzer unit tests: 796 passed, 3 existing ignores. - Differential SystemVerilog class suite across backends: 179 passed. - Retained external evidence checks: 3 passed. - NAPI build and JavaScript integration: 432 passed. - Analyzer Clippy, formatting, and diff checks pass. - Unbased fill regression: all five backend variants fail before the fix and pass afterward; Verilator also passes the unchanged assertions. - All four new shared cases exercised with Verilator and Icarus; the limitations above are documented with original diagnostics in verification/repros. Change-Id: I076dfe023e39722af4f294144ffae2c202085d52 --- crates/celox-sv-analyzer/src/ast.rs | 4 + crates/celox-sv-analyzer/src/ast/classes.rs | 7 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 1 + .../src/ast/expression_binding/direct.rs | 9 +- .../src/ast/expression_binding/objects.rs | 7 +- .../celox-sv-analyzer/src/ast/parameters.rs | 6 +- .../celox-sv-analyzer/src/ast/procedural.rs | 1 + .../src/ast/procedural/randomization.rs | 81 ++++++++-- .../src/ast/type_binding/binding.rs | 73 ++++++++- crates/celox-sv-analyzer/src/ast/types.rs | 1 + crates/celox-sv-analyzer/src/tests.rs | 22 ++- crates/celox-test-suite/LIMITATIONS.md | 13 ++ .../celox-test-suite/src/sv/cases/class.vtest | 138 ++++++++++++++++++ .../repros/sv_enum_randomization_icarus.json | 55 +++++++ .../sv_enum_randomization_verilator.json | 22 +++ .../verification/sv/icarus/class.json | 92 ++++++++++++ .../verification/sv/limitations.json | 37 +++++ .../verification/sv/verilator/class.json | 23 +++ .../tests/frontends/systemverilog/class.rs | 10 ++ docs/guide/systemverilog-reference.md | 9 +- docs/ja/guide/systemverilog-reference.md | 6 +- 21 files changed, 588 insertions(+), 29 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json create mode 100644 crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 3d026b99fd7..f68754cc08e 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1969,6 +1969,8 @@ pub enum PortDirection { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Type { is_enum: bool, + /// Resolved legal values for a scalar enum; None if its domain is unsupported. + enum_values: Option>, kind: TypeKind, is_signed: bool, packed_ranges: Vec, @@ -1986,6 +1988,7 @@ impl Type { fn implicit() -> Self { Self { is_enum: false, + enum_values: None, kind: TypeKind::Implicit, is_signed: false, packed_ranges: Vec::new(), @@ -2000,6 +2003,7 @@ impl Type { Self { kind, is_enum: false, + enum_values: None, is_signed: false, packed_ranges: Vec::new(), unpacked_ranges: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index a44fee5735b..4b92fe3940d 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -122,9 +122,12 @@ impl Class { if property.randc { return Err(unsupported("class randomize with randc properties")); } - if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) { + if property.rand + && (property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none())) + { return Err(unsupported( - "class randomize requires integral non-enum rand properties", + "class randomize requires integral rand properties with a supported enum domain", )); } } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index bcc9ca9afec..7fd131f1d42 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -350,6 +350,7 @@ fn extend_variable_dimensions_from_const_env( let packed_ranges = ranges.split_off(unpacked); let ty = Type { is_enum: false, + enum_values: None, kind: TypeKind::Logic, is_signed: variable_type_is_signed(const_env, name), packed_ranges, 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 9ebd6e1001e..17b50ff3c53 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -233,7 +233,7 @@ enum Finish { /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), /// A read of property `property` of the object handle child. - ObjectLoad(crate::ast::classes::Property), + ObjectLoad(Box), /// A call of method subroutine `name` with `formals` formals; the first /// child is the object handle when `receiver` is one. MethodCall { @@ -756,9 +756,10 @@ pub(in crate::ast) fn bind_value( let (property, receiver) = objects::property(tree, id, native, dimensions)? .expect("checked by the guard"); match receiver { - Some(receiver) => { - (Finish::ObjectLoad(property), vec![(receiver, None)]) - } + Some(receiver) => ( + Finish::ObjectLoad(Box::new(property)), + vec![(receiver, None)], + ), None => { values.push(objects::load(&property, objects::this())); continue; 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 cfcd38f83ed..26d4e676a93 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -555,9 +555,12 @@ pub(super) fn random_selection( if property.constant { return Err(unsupported("randomize argument is a const property")); } - if property.field.handle.is_some() || property.r#type.is_enum || property.randc { + if property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) + || property.randc + { return Err(unsupported( - "randomize arguments require integral non-enum, non-randc properties", + "randomize arguments require integral, non-randc properties with a supported enum domain", )); } bits[index + 1] = '1'; diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index df53b14d48e..a2f4efd2aab 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -935,7 +935,11 @@ pub(super) fn coerce_const_parameter_value(value: i128, width: usize, signed: bo } } -fn enum_initializer_fits_base_type(value: i128, value_type: ExprType, base_type: ExprType) -> bool { +pub(super) fn enum_initializer_fits_base_type( + value: i128, + value_type: ExprType, + base_type: ExprType, +) -> bool { // A same-width initializer may change its numeric interpretation when // the enum base has different signedness, but it does not lose any bits. if value_type.width <= base_type.width || base_type.width >= 128 { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 47c102a0582..803c11a5b1f 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -115,6 +115,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - pub(super) fn int_type() -> Type { Type { is_enum: false, + enum_values: None, 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 2b8d305459e..597458d6c73 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -133,7 +133,7 @@ pub(super) fn lower( for property in &class.properties { if property.constant || property.field.handle.is_some() - || property.r#type.is_enum + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) { continue; } @@ -150,16 +150,7 @@ pub(super) fn lower( vec![Expr::Ident(this.clone())], )), }, - then_body: vec![Stmt::Eval(classes::object_call( - ObjectOp::Store(property.field), - vec![ - Expr::Ident(this.clone()), - classes::object_call( - ObjectOp::Random, - vec![Expr::Ident(this.clone())], - ), - ], - ))], + then_body: random_property(&mut builder, property, &this), else_body: Vec::new(), }); } @@ -264,3 +255,71 @@ pub(super) fn lower( } Ok(result) } + +/// Select a declared enum value with rejection sampling, so non-power-of-two +/// domains are uniform (IEEE 1800-2023 18.3, 18.4.1). Keep the draws inside the +/// mode guard: a disabled property must not consume its object's random stream. +fn random_property( + builder: &mut BodyBuilder<'_, '_, '_>, + property: &classes::Property, + this: &str, +) -> Vec { + let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]); + let mut body = Vec::new(); + let value = if let Some(values) = &property.r#type.enum_values { + let count = values.len() as u64; + let threshold = count.wrapping_neg() % count; + let draw = builder.declare("$enum_draw", classes::unsigned_type(64)); + body.push(Stmt::Loop { + kind: LoopKind::DoWhile, + init: Vec::new(), + condition: Some(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("64'd{threshold}"))), + }), + step: Vec::new(), + body: vec![Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: random(), + nonblocking: false, + }], + }); + body.push(Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("64'd{count}"))), + }, + nonblocking: false, + }); + let literal = |value| { + Expr::Literal(format_typed_parameter_literal( + value, + property.field.width as usize, + property.field.signed, + )) + }; + let mut value = literal(*values.last().unwrap()); + for (index, &member) in values.iter().enumerate().rev().skip(1) { + value = Expr::Mux { + condition: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal(format!("64'd{index}"))), + }), + then_expr: Box::new(literal(member)), + else_expr: Box::new(value), + }; + } + value + } else { + random() + }; + body.push(Stmt::Eval(classes::object_call( + ObjectOp::Store(property.field), + vec![Expr::Ident(this.into()), value], + ))); + body +} 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 6f96b7edded..a73605e604e 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -18,7 +18,7 @@ pub(in crate::ast) fn bind_in( ) -> Converted> { enum Job { Enter(TypeId), - Enum(Vec), + Enum(TypeId, Vec), Aggregate { owner: Arc, union: bool, @@ -78,11 +78,12 @@ pub(in crate::ast) fn bind_in( } DataTypeKind::Enum { base, .. } => { if let Some(base) = base { - jobs.push(Job::Enum(ranges)); + jobs.push(Job::Enum(id, ranges)); jobs.push(Job::Enter(*base)); } else { let mut ty = builtin_type("int", None).unwrap(); ty.is_enum = true; + ty.enum_values = enum_values(id, native, tree, context, &ty); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); } @@ -156,7 +157,7 @@ pub(in crate::ast) fn bind_in( } } } - Job::Enum(ranges) => { + Job::Enum(id, ranges) => { let Some(mut ty) = values.pop() else { return Err(unsupported("enum base type")); }; @@ -164,6 +165,7 @@ pub(in crate::ast) fn bind_in( outer.extend(ty.packed_ranges); ty.packed_ranges = outer; ty.is_enum = true; + ty.enum_values = enum_values(id, native, tree, context, &ty); values.push(ty); } Job::Aggregate { @@ -272,3 +274,68 @@ pub(in crate::ast) fn expression_type( let value = expression_binding::bind(root, tree, &query)?; Ok(dimensions::bound_bits_type(&tree.state, &value, &query)) } + +/// Domain metadata is best-effort during signature discovery. Only a caller +/// requesting randomization requires a resolved domain; unused types must not +/// start reporting new errors merely because this metadata is collected. +fn enum_values( + id: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + ty: &Type, +) -> Option> { + let data = native.data_type(id); + if !data.packed_dimensions.is_empty() { + return None; + } + let DataTypeKind::Enum { items, .. } = &data.kind else { + return None; + }; + let shape = casts::expr_type_from_type(&tree.state, ty, &context.const_env)?; + if shape.width > 64 { + return None; + } + let mut env = context.const_env.clone(); + let mut next = 0i128; + let mut values = Vec::new(); + for item in items { + if !item.dimensions.is_empty() { + return None; + } + let value = if let Some(id) = item.value { + let expr = constant_binding::expression(id, native, tree, &env, &context.type_aliases) + .ok()??; + // Unbased fills take the enum base's width and signedness, just + // as they do when resolving the declared enum constants (5.7.1). + let expr = match expr { + ConstExpr::Literal(literal) => ConstExpr::Literal( + resize_unbased_fill_literal_for_cast(&literal, shape.width, shape.signed) + .unwrap_or(literal), + ), + expr => expr, + }; + let value = eval_ast_const_expr(&tree.state, &expr, &env)?; + let value_type = infer_const_expr_type(&expr, ¶meter_types_from_const_env(&env))?; + if !parameters::enum_initializer_fits_base_type(value, value_type, shape) { + return None; + } + value + } else { + if parameters::coerce_const_parameter_value(next, shape.width, shape.signed) != next { + return None; + } + next + }; + let value = parameters::coerce_const_parameter_value(value, shape.width, shape.signed); + if values.contains(&value) { + return None; + } + values.push(value); + let name = normalize_identifier(&item.name.spelling); + 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) +} diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index fa20c7e6cb5..22ed86204db 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -177,6 +177,7 @@ 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.signed_element_depth = if r#type.is_signed { Some(direct_ranges.len()) } else { diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index dcc648cb2c5..4f81363593c 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6597,7 +6597,11 @@ fn class_randomize_rejects_unsupported_semantics() { "c.f()", "object receiver", ), - ("rand string x;", "c.randomize()", "integral non-enum"), + ( + "rand string x;", + "c.randomize()", + "integral rand properties", + ), ( "rand int x;", "c.randomize() with { x == 1; }", @@ -6665,3 +6669,19 @@ fn randomization_signatures_do_not_force_unused_interface_class_layouts() { analyze_source(&source, Path::new("unused_interface_class.sv")).unwrap(); } } + +#[test] +fn class_randomize_rejects_unresolved_enum_domains() { + for members in ["A=3, B", "A=0, B=0", "A=2'bx, B=1"] { + let source = format!( + "module Top; + class C; rand enum bit [1:0] {{{members}}} value; endclass + C c; initial begin c = new; void'(c.randomize()); end + endmodule" + ); + assert!( + analyze_source(&source, Path::new("enum_domain.sv")).is_err(), + "{members}" + ); + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 51e04377b4c..a645644c645 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -669,3 +669,16 @@ Verilator 5.052 has two narrower exclusions, recorded in the The setter's formal is `bit` (18.8), so the required conversion truncates 2 to 0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control, inline member selection and pre-hook control cases pass Verilator. + +Enum class randomization (`sv_icarus_enum_randomization`) excludes the four +`class::randomization_enum_*` cases from Icarus 13.0 because it cannot elaborate +class randomization methods. [Original diagnostics](verification/repros/sv_enum_randomization_icarus.json) +retain the failures without changing the shared assertions. + +Verilator 5.052 passes the direct enum and inherited enum cases, but treats a +typedef alias of an enum as the underlying integer during randomization +(`sv_verilator_enum_alias_randomization`). The generated randomizer assigns raw +8-bit random values rather than selecting declared enum values, contrary to +IEEE 1800-2023 18.3. Only `class::randomization_enum_alias` is excluded; +[the mismatch evidence](verification/repros/sv_enum_randomization_verilator.json) +retains its unchanged domain assertion. diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 768617f2953..06c4057355b 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -929,3 +929,141 @@ module Top(output bit done, output int errors); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_domain + (source "enum_randomize.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=MID+89} sparse_t; + typedef enum bit [63:0] {LOW=64'h100000000, TOP=64'h8000000000000000} wide_t; + class Base; + rand sparse_t value; + sparse_t selected; + rand wide_t wide_value; + rand enum bit [2:0] {ONLY=5} single; + rand enum {FIRST=11, SECOND=35, THIRD} extra; + endclass + Base a, b; + Base base; + int seen; + int old_value; + initial begin + a = new; b = new; base = a; + a.srandom(123); b.srandom(123); + repeat (256) begin + if (!base.randomize() || !b.randomize()) errors++; + if (a.value != b.value || a.wide_value != b.wide_value || a.extra != b.extra) errors++; + case (a.value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + if (a.wide_value != LOW && a.wide_value != TOP) errors++; + if (a.single != 5) errors++; + if (a.extra != 11 && a.extra != 35 && a.extra != 36) errors++; + end + if (seen != 7) errors++; + a.value.rand_mode(0); + old_value = a.value; + if (!a.randomize() || a.value != old_value) errors++; + if (!a.randomize(selected)) errors++; + if (a.selected != NEG && a.selected != MID && a.selected != HIGH) errors++; + if (a.value != old_value || a.value.rand_mode() != 0) errors++; + if (!base.randomize(value)) errors++; + if (a.value != NEG && a.value != MID && a.value != HIGH) errors++; + if (a.value.rand_mode() != 0) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_inheritance + (source "enum_inheritance.sv" #" +module Top(output bit done, output int errors); + class Parent; + rand enum bit [7:0] {P=7, Q=93} x; + endclass + class Child extends Parent; + rand enum bit [7:0] {R=11, S=57, T=98} y; + endclass + Child child; + Parent parent; + int seen; + initial begin + child = new; parent = child; + repeat (128) begin + if (parent.randomize() != 1) errors++; + if (child.x != 7 && child.x != 93) errors++; + case (child.y) + 11: seen |= 1; + 57: seen |= 2; + 98: seen |= 4; + default: errors++; + endcase + end + if (seen != 7) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_alias + (source "enum_alias.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=91} original_t; + typedef original_t alias_t; + class Sample; + rand alias_t value; + endclass + Sample object; + int seen; + initial begin + object = new; + repeat (128) begin + if (object.randomize() != 1) errors++; + case (object.value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + end + if (seen != 7) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_fill_literals + (source "enum_fill.sv" #" +module Top(output bit done, output int errors); + typedef enum bit [63:0] {WIDE_ALL='1} wide_t; + typedef enum bit [3:0] {SMALL_ALL='1} small_t; + typedef enum bit signed [63:0] {SIGNED_ALL='1} signed_t; + typedef enum bit [63:0] {ZERO='0} zero_t; + class Sample; + rand wide_t wide_value; + rand small_t small_value; + rand signed_t signed_value; + rand zero_t zero_value; + endclass + Sample object; + initial begin + object = new; + repeat (8) begin + if (object.randomize() != 1) errors++; + if (object.wide_value != 64'hffffffffffffffff) errors++; + if (object.small_value != 4'hf) errors++; + if (object.signed_value != -64'sd1) errors++; + if (object.zero_value != 64'd0) errors++; + if (object.wide_value != WIDE_ALL || object.small_value != SMALL_ALL + || object.signed_value != SIGNED_ALL || object.zero_value != ZERO) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json b/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json new file mode 100644 index 00000000000..d0fa8229844 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json @@ -0,0 +1,55 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:13: Error: randomize is not a method of class Sample.\n/source_0.sv:13: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:13: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 24; see /build.log\n/source_0.sv:18: error: Can't find task srandom in class Base\n/source_0.sv:18: error: Enable of unknown task ``a.srandom''.\n/source_0.sv:18: error: Can't find task srandom in class Base\n/source_0.sv:18: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:20: Error: randomize is not a method of class Base.\n/source_0.sv:20: error: Object celox_suite_tb.dut.base has no method \"randomize(...)\".\n/source_0.sv:20: Error: randomize is not a method of class Base.\n/source_0.sv:20: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:20: error: Unable to elaborate condition expression.\n/source_0.sv:33: error: Can't find task rand_mode in class Base\n/source_0.sv:33: error: Enable of unknown task ``a.value.rand_mode''.\n/source_0.sv:35: Error: randomize is not a method of class Base.\n/source_0.sv:35: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:35: error: Unable to elaborate condition expression.\n/source_0.sv:36: Error: randomize is not a method of class Base.\n/source_0.sv:36: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:36: error: Unable to elaborate condition expression.\n/source_0.sv:38: sorry: Method name nesting is not supported yet.\n/source_0.sv:38: : method path: value.rand_mode\n/source_0.sv:38: error: Object celox_suite_tb.dut.a has no method \"value.rand_mode(...)\".\n/source_0.sv:38: error: Unable to elaborate condition expression.\n/source_0.sv:39: Error: randomize is not a method of class Base.\n/source_0.sv:39: error: Object celox_suite_tb.dut.base has no method \"randomize(...)\".\n/source_0.sv:39: error: Unable to elaborate condition expression.\n/source_0.sv:41: sorry: Method name nesting is not supported yet.\n/source_0.sv:41: : method path: value.rand_mode\n/source_0.sv:41: error: Object celox_suite_tb.dut.a has no method \"value.rand_mode(...)\".\n/source_0.sv:41: error: Unable to elaborate condition expression.\n24 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_domain", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:17: Error: randomize is not a method of class Sample.\n/source_0.sv:17: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:17: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_fill_literals", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:15: Error: randomize is not a method of class Parent.\n/source_0.sv:15: error: Object celox_suite_tb.dut.parent has no method \"randomize(...)\".\n/source_0.sv:15: error: Unable to elaborate condition expression.\n/source_0.sv:17: assert: dup_expr.cc:215: failed assertion 0\nAborted (core dumped)\n", + "expectation": "Simulation", + "name": "class::randomization_enum_inheritance", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json b/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json new file mode 100644 index 00000000000..c9062c4139b --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json @@ -0,0 +1,22 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "class::randomization_enum_alias at 1038:46: assert_eq errors: expected 0x0, got 0x7e", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052" +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 9e91a1b7c19..96bafddf611 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -309,6 +309,98 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_domain", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_fill_literals", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_inheritance", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "expectation": "Simulation", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index b9acfdf7286..eae83a2806a 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2140,5 +2140,42 @@ "class::randomization_mode_bit_argument" ] } + }, + { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomization_enum_alias", + "class::randomization_enum_domain", + "class::randomization_enum_fill_literals", + "class::randomization_enum_inheritance" + ] + } + }, + { + "id": "sv_verilator_enum_alias_randomization", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_enum_alias" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index a255bf9044d..67802610550 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -190,6 +190,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "known_issue": { + "id": "sv_verilator_enum_alias_randomization", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "expectation": "Simulation", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 17b93891c46..b2c81061d78 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -378,3 +378,13 @@ sv_backends! { assert_eq!(sim.get(sim.signal("errors")), 0u8.into()); } } + +sv_backends! { + fn class_randomization_enum_inheritance(sim) { @case "class::randomization_enum_inheritance"; } + fn class_randomization_enum_alias(sim) { @case "class::randomization_enum_alias"; } + fn class_randomization_enum_domain(sim) { @case "class::randomization_enum_domain"; } +} + +sv_backends! { + fn class_randomization_enum_fill_literals(sim) { @case "class::randomization_enum_fill_literals"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index af7fea78edf..838888d15b6 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -107,8 +107,11 @@ constants, selects and concatenation arguments are unsupported and rejected. ### Class randomization `object.randomize()` randomizes enabled `rand` properties and returns signed -`int` value `1`. Supported properties are 2-state, non-enum integral values up -to 64 bits in classes without constraints. Inherited properties are included, +`int` value `1`. Supported properties are 2-state integral values, including scalar enums, up +to 64 bits in classes without constraints. Enum randomization selects uniformly +from the declared values, including sparse and negative values (18.3, 18.4.1). +Enums with unresolved or X/Z values and ranged enumerator declarations remain +unsupported for randomization. Inherited properties are included, and a call through a base handle uses the dynamic object's class and its `pre_randomize()` / `post_randomize()` hooks. A derived hook replaces the base hook; call `super.pre_randomize()` or `super.post_randomize()` explicitly to @@ -134,7 +137,7 @@ Each object has an independent random stream, seeded from its creating process. `object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve both RNG and mode state (18.13.3, 18.14.3). Random sequences are implementation-specific. `randc` randomization, constraints, `with`, static random properties, and random -enum/array/object/string properties remain unsupported. A constrained dynamic +array/object/string properties remain unsupported. A constrained dynamic subclass is rejected rather than silently randomizing only its base properties. A call through `null` is a runtime error. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index c10c355185b..c8e23bb19e7 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -98,7 +98,9 @@ select・連結式の引数は未対応として拒否します。 ### クラスの乱数化 `object.randomize()` は有効な `rand` プロパティを乱数化し、成功値の1(signed `int`)を返します。 -制約のないクラスで、64ビット以下の2値・非enum整数型に対応します。 +制約のないクラスで、スカラーenumを含む64ビット以下の2値整数型に対応します。 +enumは宣言された値だけから均等に抽選し、飛び飛びの値や負数にも対応します(18.3、18.4.1)。 +値が未解決またはX/Zを含むenum、列挙子の範囲指定は乱数化に未対応です。 継承したプロパティも対象になり、基底型のハンドルを通した呼び出しでも、実際のオブジェクトの クラスと `pre_randomize()` / `post_randomize()` を使います。子クラスでフックを定義すると 親のフックを置き換えるため、親の処理も必要なら `super.pre_randomize()` などを明示的に呼びます @@ -119,7 +121,7 @@ select・連結式の引数は未対応として拒否します。 オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します (18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 -`randc` の乱数化、制約、`with`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の +`randc` の乱数化、制約、`with`、staticな乱数プロパティ、配列・オブジェクト・文字列の 乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 `null` を通した呼び出しは実行時エラーです。 From effa03ce80eff6ca3525ded1c1d25a032eaa85b2 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 11:44:48 +0900 Subject: [PATCH 2/2] perf(sv): skip scope discovery for literal query operands Preliminary typing of each literal array-pattern element rediscovered all visible declarations. Publishing intermediate dimension snapshots repeatedly copied and dropped unrelated expression trees, causing Taxi frontend runs to exceed their 120-second limit. Reuse the existing query-context projection for literals, including grouped literals, before scope types are complete. Literals do not require lexical name resolution; other operands retain the existing discovery path. Add an owning-crate regression comparing literal query results against forced discovery and asserting that the shortcut performs no declaration discovery. Validation: - Full SystemVerilog suite: 4,366 passed, 20 existing ignored, across all five backends. Analyzer: 796 passed, 3 existing ignored; frontend: 5 passed; doctests: 2 passed. - Clippy for affected crates/all targets with -D warnings, formatting, and diff checks passed. Shared cases and external adapters are unchanged. - Replayed the same 25 Taxi configurations using original RTL/parameters, release frontend binaries, two workers and 120-second limits. Timeouts decrease from 17 to zero; all 25 reach existing unpacked-parameter forwarding errors: 18 GT_TX_DIFFCTRL and 7 STAT_PREFIX_STR. Elapsed times are 2.142-21.296 seconds (median 10.245). These are frontend error results, not full FPGA-core or cocotb test passes. All 188 resolved SV sources match the earlier upstream hashes. - Synthetic source-to-scheduling probe with 256 declarations and 256 literal array elements: baseline completed samples take 38.929 and 42.647 seconds (a third times out at 60 seconds); patched samples take 0.038-0.042 seconds. Three repetitions alternate old/new order on a shared machine; these measurements do not establish a universal speedup or linear complexity. This change builds on real-valued parameter overrides from #1839. Remaining unpacked-array parameter forwarding errors are separate follow-up work. Change-Id: I00f31b062932d07ebdbe89b7fc3a7080e2aa2308 --- .../src/ast/dimensions/query_binding.rs | 11 +++- .../src/ast/dimensions/tests.rs | 56 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) 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 d3fe2977483..353055ff483 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -26,7 +26,16 @@ pub(in crate::ast) fn query_context_for_operand( tree: &AnalysisContext<'_>, context: &PackedDimensions, ) -> Converted { - if context.scope_types_complete { + // Literals carry their type in their spelling and cannot reference lexical + // declarations. Pattern elements otherwise rediscover the whole scope for + // each literal while the surrounding declaration is still being bound. + let operand = expression_binding::ungroup(root, tree.declarations()); + if context.scope_types_complete + || matches!( + tree.declarations().expression(operand).kind, + ExprKind::Literal(_) + ) + { return Ok(query_context(context)); } Ok(query_context(&query_operand_dimensions_id( diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index 10c9d8a9e4f..f29dadcf3e5 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -517,3 +517,59 @@ fn recursive_generate_dimension_discovery_uses_explicit_specialization() { ); } } + +#[test] +fn preliminary_literal_queries_do_not_discover_scope_declarations() { + let tree = crate::source_tree::parse_scope_fixture( + r#"module Top; + logic [7:0] unrelated [0:31]; + localparam A = $bits(123); + localparam B = $bits((8'shff)); + localparam C = $bits(4'bx); + localparam D = $bits("ab"); + localparam E = $bits('1); + endmodule"#, + Path::new("literal_query.sv"), + ) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + let input = PackedDimensions::default(); + let calls = native_calls(&tree); + assert_eq!(calls.len(), 5); + // Keep the discovery path as an independent reference for the result. + let discovered = calls + .iter() + .map(|call| { + let celox_sv_syntax::ExprKind::Call { arguments, .. } = + &tree.declarations().expression(*call).kind + else { + unreachable!() + }; + let context = + query_operand_dimensions_id(arguments[0].value.unwrap(), &tree, &input).unwrap(); + query_number( + *call, + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&context), + ) + }) + .collect::>(); + SYNTAX_TYPE_DISCOVERIES.with(|count| count.set(0)); + let direct = calls + .iter() + .map(|call| { + query_number( + *call, + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&input), + ) + }) + .collect::>(); + assert_eq!(&direct[..4], &[Some(32), Some(8), Some(4), Some(16)]); + assert_eq!(direct, discovered); + assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|count| count.get()), 0); +}