From ee7e1088cf0fabfa6aea0126a7027c81eda5e829 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 05:41:24 +0900 Subject: [PATCH] fix(sv): bind derived classes in their own declaration scopes A class inherits the parameters, body parameters and typedefs its base and the base's bases declare (IEEE 1800-2023 8.13), not the scope around the base's declaration. A specialization therefore records what the class declares itself, and a derived class merges only that from its lineage: a derived class declared in a generate block that hides a module constant now binds its typedefs with the generate block's constant, where it saw the module's before. A class declared in a block that loop generation repeats is a class of its own in each iteration (27.4), which the analyzer does not tell apart yet; such classes are rejected instead of sharing one iteration's constants (#2064). Change-Id: I7b2b0f7066fa671c3a7f19e3360b2dea5293b76f --- crates/celox-sv-analyzer/src/ast.rs | 3 + .../src/ast/classes/specializations.rs | 60 ++++++++++++++++++- crates/celox-test-suite/LIMITATIONS.md | 2 +- .../celox-test-suite/src/sv/cases/class.vtest | 22 +++++++ .../verification/sv/icarus/class.json | 23 +++++++ .../verification/sv/limitations.json | 3 +- .../verification/sv/limitations/icarus.json | 10 +++- .../verification/sv/verilator/class.json | 11 ++++ .../verification/sv/xezim/class.json | 11 ++++ .../verification/xezim-review.json | 12 ++++ .../tests/frontends/systemverilog/class.rs | 10 ++++ 11 files changed, 161 insertions(+), 6 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index b80165f580a..82d93b344f1 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -38,6 +38,9 @@ pub(super) struct AnalysisState { /// its parameter defaults and body see (IEEE 1800-2023 8.25). class_declaration_scopes: std::cell::RefCell, HashMap)>>, + /// The classes declared in a generate block that elaboration repeats, + /// which would be a class of their own in each repetition (27.4). + class_declarations_repeated: std::cell::RefCell>, /// Set once the class methods of the scope being analyzed have their /// signatures, after which a new specialization would have none. class_specializations_frozen: std::cell::Cell, diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index 04003afe908..ec90d03625f 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -23,6 +23,10 @@ pub(in crate::ast) struct Specialization { /// The constants the value parameters hide without a value of their /// own, as a string or four-state value does. pub hidden: Vec, + /// The constants and types the class declares itself, which a class + /// extending it inherits without the scope around the declaration. + pub declared_env: HashMap>, + pub declared_aliases: HashMap, /// The literals that replace the value parameters. pub literals: HashMap, /// The type parameters and typedefs, and the class name itself. @@ -166,6 +170,35 @@ pub(in crate::ast) fn scope( (env, aliases) } +/// `env` and `aliases` with what class `name` and its bases declare added, +/// which class `own` extending it inherits (IEEE 1800-2023 8.13): not the +/// scope around their declarations. +fn inherit( + tree: &AnalysisContext<'_>, + name: &str, + own: &str, + env: &mut HashMap, + aliases: &mut HashMap, +) { + for specialization in lineage(tree, name) { + for (key, value) in &specialization.declared_env { + match value { + Some(value) => env.insert(key.clone(), *value), + None => env.remove(key), + }; + } + aliases.extend( + specialization + .declared_aliases + .iter() + .filter(|(key, _)| { + **key != scope_key(&specialization.generic) || specialization.generic == own + }) + .map(|(key, ty)| (key.clone(), ty.clone())), + ); + } +} + /// `dimensions` and `literals` with the parameters of class `name` added, /// for binding the bodies of its methods. pub(in crate::ast) fn body_scope( @@ -237,6 +270,16 @@ pub(in crate::ast) fn specialize( let native = tree.declarations(); let declaration = super::declaration(tree, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; + if tree + .state + .class_declarations_repeated + .borrow() + .contains(generic) + { + return Err(unsupported(format!( + "class `{generic}` declared in a loop generate block" + ))); + } // The parameters an assignment may set: those of the parameter port // list that are not local, in order. let ports = declaration @@ -367,7 +410,7 @@ pub(in crate::ast) fn specialize( // The body sees the parameters and types of the bases, hidden by the // class's own, and the scope of the specialization (8.25.1). for base in &bases { - (env, aliases) = scope(tree, base, &env, &aliases); + inherit(tree, base, generic, &mut env, &mut aliases); } for (key, value) in ¶meters.own_env { match value { @@ -424,7 +467,9 @@ pub(in crate::ast) fn specialize( ) }); if let Some(ty) = ty { - aliases.insert(instances::normalize_identifier(&alias.name.spelling), ty); + let name = instances::normalize_identifier(&alias.name.spelling); + parameters.own_aliases.insert(name.clone(), ty.clone()); + aliases.insert(name, ty); } } } @@ -439,6 +484,8 @@ pub(in crate::ast) fn specialize( .filter(|(key, value)| value.is_none() && !env.contains_key(*key)) .map(|(key, _)| key.clone()) .collect(), + declared_env: parameters.own_env, + declared_aliases: parameters.own_aliases, env, literals: parameters.literals, aliases, @@ -949,10 +996,17 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens ), None => ((*context.const_env).clone(), context.type_aliases.clone()), }; + let name = instances::normalize_identifier(&class.name.spelling); + if item.is_some_and(|item| items.iter().filter(|other| other.id == item.id).count() > 1) { + tree.state + .class_declarations_repeated + .borrow_mut() + .insert(name.clone()); + } tree.state .class_declaration_scopes .borrow_mut() - .insert(instances::normalize_identifier(&class.name.spelling), scope); + .insert(name, scope); } // Whether `tokens` is in a block of a generate construct. let generated = |tokens: celox_sv_syntax::TokenRange| { diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 86e2f1b4d45..eed64275137 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -550,7 +550,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_cast` | execute | icarus | 1 | Icarus 13.0 does not implement $cast ("System task/function $cast() is not defined by any module"), which IEEE 1800-2023 6.24.2 and 8.16 define. Verilator passes the case. | | `sv_verilator_class_specialization_identity` | execute | verilator | 1 | Verilator 5.052 makes a separate specialization of a parameterized class for each way a parameter value assignment is written, so Box#(2, int)::made and Box#(.N(2), .T(int))::made read 0 after an object of Box#(.T(int), .N(2)) was constructed; the adapter-free source prints 0 1 0 where IEEE 1800-2023 8.25 requires 1 1 1, as the three assignments give the same values. Celox prints 1 1 1. Icarus rejects parameterized classes, see sv_icarus_parameterized_classes. | | `sv_verilator_untyped_class_parameters` | execute | verilator | 1 | Verilator 5.052 gives a class parameter declared without a type the 32-bit type of its default even when a specialization assigns it a sized value, so $bits(V) of Sized#(8'h1) is 32; the adapter-free source prints 32 32 where IEEE 1800-2023 6.20.2 requires 8 32, as the parameter takes the type of its final value after overrides. Celox prints 8 32. Icarus rejects parameterized classes, see sv_icarus_parameterized_classes. | -| `sv_icarus_parameterized_classes` | compile | icarus | 11 | Icarus 13.0 does not parse a parameter port list of a class (class Box #(int N = 4); is a syntax error), which IEEE 1800-2023 8.25 defines; each case declares a parameterized class. Verilator passes all but two cases, see sv_verilator_class_specialization_identity and sv_verilator_untyped_class_parameters. | +| `sv_icarus_parameterized_classes` | compile | icarus | 13 | Icarus 13.0 does not parse a parameter port list of a class (class Box #(int N = 4); is a syntax error), which IEEE 1800-2023 8.25 defines; each case declares a parameterized class. Verilator passes all but two cases, see sv_verilator_class_specialization_identity and sv_verilator_untyped_class_parameters. | | `sv_verilator_class_property_string_methods` | compile | verilator | 1 | Verilator 5.052 stops with an internal error ("AstNode is not of expected type, but instead has type 'MEMBERSEL'") on a string method called on a class property, n.name.itoa(42), which IEEE 1800-2023 6.16 and 8.5 permit. Icarus rejects the case too, see sv_icarus_classes. | | `sv_icarus_unpacked_array_patterns` | compile | icarus | 1 | Icarus 13.0 reports that an assignment pattern with unpacked array items assigned to a multidimensional unpacked array is not yet supported ("Procedural assignment of array or array slice"), so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_display_field_width` | execute | icarus | 1 | Icarus 13.0 zero-pads a value wider than an explicit field width of %h or %o to the argument's full width (%3h of 32'h1234 prints 00001234); IEEE 1800-2023 21.2.1.2 expands the field to the value without leading zeros (1234). Verilator agrees with the expected value. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 72f3d6beedb..b1305205dd0 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -1713,3 +1713,25 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "2 1 1\n1 1\n3.0 3.0\n2\n7\n")) + +(case derived_classes_keep_their_declaration_scopes + (source "class.sv" #" +module Top(output bit done); + localparam int K = 2; + class Base #(int N = 0); + endclass + if (1) begin : g + localparam int K = 3; + class Derived #(int M = 0) extends Base; + typedef bit [K-1:0] T; + endclass + initial begin + Derived#()::T t; + $display("%0d", $bits(t)); + done = 1; + end + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "3\n")) diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 12b0961973a..c2a5199d3ff 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -149,6 +149,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 does not parse a parameter port list of a class (class Box #(int N = 4); is a syntax error), which IEEE 1800-2023 8.25 defines; each case declares a parameterized class. Verilator passes all but two cases, see sv_verilator_class_specialization_identity and sv_verilator_untyped_class_parameters.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_parameterized_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not parse a parameter port list of a class (class Box #(int N = 4); is a syntax error), which IEEE 1800-2023 8.25 defines; each case declares a parameterized class. Verilator passes all but two cases, see sv_verilator_class_specialization_identity and sv_verilator_untyped_class_parameters.", + "upstream": [] + }, + "name": "class::derived_classes_keep_their_declaration_scopes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index a14cb6fdb09..73e0edf3216 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2055,7 +2055,8 @@ "class::untyped_class_parameters_take_the_type_of_their_value", "class::class_declarations_bind_in_their_scopes", "class::parameter_defaults_bind_where_the_class_is_declared", - "class::specialization_keys_follow_the_bound_parameters" + "class::specialization_keys_follow_the_bound_parameters", + "class::derived_classes_keep_their_declaration_scopes" ] } }, diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 8d4523ff88d..daf824e03a2 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 17, "emission_error": 0, - "compile_error": 133, + "compile_error": 134, "runtime_error": 8, "unsupported": 0, "ignored": 0 @@ -1463,6 +1463,14 @@ "name": "class::specialization_keys_follow_the_bound_parameters", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 13; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:12: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module instantiation\n/testbench.sv:11: error: Invalid module item.\n/testbench.sv:12: error: Repeat timeunit found and the initial timeunit for this scope is missing.\n/testbench.sv:13: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n", + "expectation": "Simulation", + "name": "class::derived_classes_keep_their_declaration_scopes", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index b531bcbdd46..7dc91416ad5 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -90,6 +90,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::derived_classes_keep_their_declaration_scopes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/xezim/class.json b/crates/celox-test-suite/verification/sv/xezim/class.json index c74c87503c7..64919583719 100644 --- a/crates/celox-test-suite/verification/sv/xezim/class.json +++ b/crates/celox-test-suite/verification/sv/xezim/class.json @@ -77,6 +77,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "class::derived_classes_keep_their_declaration_scopes at 1737:3: expect_output: expected [51, 10], got [49, 10]", + "expectation": "Simulation", + "name": "class::derived_classes_keep_their_declaration_scopes", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index fc12387205b..8f5cbf55fd1 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -642,6 +642,10 @@ "sv_class-X10": { "title": "In `extends Base #(expr, T)` an ordered value argument that is an operator expression (`M + 1`, `(2 + 4)`) is dropped when another argument follows; the base class gets its default", "standard": "IEEE 1800-2023 8.25, 23.10.2.1" + }, + "sv_class-X4": { + "title": "A typedef inside a class declared in a generate block does not see the generate block's localparams (`typedef bit [K-1:0] T` uses the module-level K, or none)", + "standard": "IEEE 1800-2023 23.9, 27.5" } }, "cases": [ @@ -3955,6 +3959,14 @@ "classification": "xezim_bug", "bug": "sv_class-X10", "note": "Wide #(5) extends Box #(M + 1, int), so its base is Box#(6, int): w.N = 6, base.get() = 100 + 6, kind() = 56, and super.new increments Box#(6, int)::made (1). xezim gives the base the default N = 4 (104 4 54 0) as top and non-top. The ordered argument `M + 1` (even `(2 + 4)`) is lost only in an extends clause and only when a second argument follows; `extends Box #(M + 1)`, `extends Box #(M, int)` and a variable `Box #(2 + 4, int)` work. Repros: work/review5/xezim/r/c14c.sv, work/review5/xezim/r/c14d.sv." + }, + { + "suite": "sv", + "name": "class::derived_classes_keep_their_declaration_scopes", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class-X4", + "note": "Derived is declared in generate block g, whose localparam K = 3 hides the module's K = 2; `typedef bit [K-1:0] T` must use K = 3 (23.9: names resolve from the declaration scope upward), so $bits = 3. xezim prints 1 (as top and non-top); in a reduction with another class it uses the module K (2). It does not depend on `extends`: a plain class in g behaves the same, while a static function in the same class returns K = 3. Repro: work/review5/xezim/r/c3c.sv, work/review5/xezim/r/c3_genscope.sv." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 796adcea29e..4f4a156f218 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -37,6 +37,7 @@ sv_backends! { fn class_class_declarations_bind_in_their_scopes(sim) { @case "class::class_declarations_bind_in_their_scopes"; } fn class_parameter_defaults_bind_where_the_class_is_declared(sim) { @case "class::parameter_defaults_bind_where_the_class_is_declared"; } fn class_specialization_keys_follow_the_bound_parameters(sim) { @case "class::specialization_keys_follow_the_bound_parameters"; } + fn class_derived_classes_keep_their_declaration_scopes(sim) { @case "class::derived_classes_keep_their_declaration_scopes"; } } sv_backends! { @@ -293,6 +294,15 @@ fn misused_parameterized_classes_are_rejected() { "typedef struct packed { int x; } s_t; class Typed #(type T = int); endclass Typed#(s_t) typed;", ["struct or union type as a class type parameter value", ""], ), + ( + // Each iteration would declare a class of its own (#2064). + "for (genvar i = 0; i < 2; i++) begin : g + localparam int K = i + 1; + class C #(int N = K); endclass + initial $display(\"%0d\", C#()::N); + end", + ["class `C` declared in a loop generate block", ""], + ), ( // The class parameter hides the module's `N`, whose value must // not name `Four#(1)` (#1964 tracks four-state actuals).