From 02e37d48ef13c7ef03da64d23593f3ce1caff0c5 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 22:23:13 +0900 Subject: [PATCH 1/2] fix(sv): lower loop-indexed packed word part-selects Procedural loops selecting bytes from multidimensional packed words or implicitly typed packed parameters failed with "indexed part-select start". Accept deferred starts for the selected packed word and constant parameter metadata, preserving preceding indices and the index expression width/sign. This lets normal loop unrolling and optimization handle expressions such as words[n][i*8 +: 8] and ID[8*(last-i) +: 8]. Add three portable regressions covering ascending/descending packed ranges, masked writes, generated memory banks, and string parameter ROM bytes. Validation: - Full SV backend harness: 3873 passed, 20 existing ignored; analyzer unit tests: 784 passed, 3 existing ignored, on master a061e1396. - Affected library/harness Clippy, cargo fmt, and diff checks pass. - All four related procedural-loop cases pass Verilator and Icarus. - Shared suite unit tests: 46 passed, 2 existing ignored (base 446753453). - Unchanged upstream Taxi sources pass all 88 cocotb tests across seven representative configurations (DMA RAM x2, XFCP APB/AXI/AXI-Lite/I2C/switch), using O1 and two-state simulation with no skipped tests. This runtime replay used base 446753453; the latest-base checks above cover the combined tree. Change-Id: I6d1f2581123bd6805227a49d01c9edb22f4517a8 --- crates/celox-sv-analyzer/src/ast/selects.rs | 25 ++--- .../src/sv/cases/indexed_select.vtest | 97 +++++++++++++++++++ .../frontends/systemverilog/indexed_select.rs | 11 +++ 3 files changed, 122 insertions(+), 11 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index 941ef781958..3945c4f45eb 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -981,18 +981,21 @@ pub(super) fn indexed_select_bounds_values( // unsigned type or truncate a carry across the base expression's width. let Some(base_value) = eval_ast_const_expr(state, &base, &dimensions.const_env) else { // A procedural loop index is not constant while its body is bound. - // Keep the endpoints in declared coordinates so normal memory range - // flattening retains the element offset. Lowering can then unroll the - // loop before requiring a constant selection inside each memory word. - let memory_word = name - .and_then(|name| dimensions.get(name)) - .is_some_and(|shape| { - !shape.unpacked.is_empty() - && index_count == shape.unpacked.len() - && shape.packed.len() == 1 - }); + // Keep the endpoints in declared coordinates so normal range flattening + // retains preceding unpacked and packed indices. Lowering can then unroll + // the loop before requiring a constant selection inside the selected word. + let selected_word = name.is_some_and(|name| { + if let Some(shape) = dimensions.get(name) { + index_count >= shape.unpacked.len() + && index_count + 1 == shape.unpacked.len() + shape.packed.len() + } else { + index_count == 0 + && dimensions::parameter_type_from_const_env(&dimensions.const_env, name) + .is_some_and(|ty| ty.width > 1) + } + }); let ty = self_determined_type(state, &base, dimensions).filter(|ty| ty.0 <= 32); - let Some(ty) = ty.filter(|_| memory_word) else { + let Some(ty) = ty.filter(|_| selected_word) else { return Err(unsupported("indexed part-select start")); }; let base = ConstExpr::Resize { diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index da1e5612b22..7a3c79395be 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1763,3 +1763,100 @@ (modify (set index index_value)) (assert_eq narrowed (& (>> 0x0123456789abcdef (& index_value 3)) 15)) (assert_eq typed (& (>> 0x0123456789abcdef (& index_value 7)) 15)))) + +; IEEE 1800-2023 11.5.1: an indexed select remains valid after selecting +; a packed array element; procedural loop indices keep their own width/sign. +(case procedural_loop_selects_packed_words + (source "loop_packed_words.sv" #" + module Top(input logic clk, input logic [3:0] be, + input logic [31:0] data, + output logic [31:0] down_plus, down_minus, up_plus, up_minus); + logic [1:0][31:0] down = '0; + logic [2:3][0:31] up = '0; + always_ff @(posedge clk) begin + for (integer i = 0; i < 4; i = i + 1) begin + if (be[i]) begin + down[1][i*8 +: 8] <= data[i*8 +: 8]; + down[0][31-i*8 -: 8] <= data[31-i*8 -: 8]; + up[2][i*8 +: 8] <= data[i*8 +: 8]; + up[3][31-i*8 -: 8] <= data[31-i*8 -: 8]; + end + end + end + assign down_plus = down[1]; + assign down_minus = down[0]; + assign up_plus = up[2]; + assign up_minus = up[3]; + endmodule + "#) + (top Top) + (modify (set be 15) (set data 0x12345678)) + (tick clk) + (assert_eq down_plus 0x12345678) + (assert_eq down_minus 0x12345678) + (assert_eq up_plus 0x78563412) + (assert_eq up_minus 0x78563412) + (modify (set be 5) (set data 0xaabbccdd)) + (tick clk) + (assert_eq down_plus 0x12bb56dd) + (assert_eq down_minus 0xaa34cc78) + (assert_eq up_plus 0xdd56bb12) + (assert_eq up_minus 0x78cc34aa)) + +(case procedural_loop_reads_packed_words_into_memory + (source "loop_packed_memory.sv" #" + module Top(input logic clk, en, input logic [1:0] addr, + input logic [63:0] data, output logic [31:0] low_word, high_word); + wire [1:0][31:0] words = data; + wire [1:0][31:0] read_words; + for (genvar n = 0; n < 2; n = n + 1) begin : bank + logic [31:0] mem[4]; + initial for (integer k = 0; k < 4; k = k + 1) mem[k] = 0; + always_ff @(posedge clk) begin + for (integer i = 0; i < 4; i = i + 1) begin + if (en) mem[addr][i*8 +: 8] <= words[n][i*8 +: 8]; + end + end + assign read_words[n] = mem[addr]; + end + assign low_word = read_words[0]; + assign high_word = read_words[1]; + endmodule + "#) + (top Top) + (modify (set en 1) (set addr 1) (set data 0x1234567889abcdef)) + (tick clk) + (assert_eq low_word 0x89abcdef) + (assert_eq high_word 0x12345678) + (modify (set addr 2) (set data 0xfedcba9876543210)) + (tick clk) + (assert_eq low_word 0x76543210) + (assert_eq high_word 0xfedcba98) + (modify (set en 0) (set addr 1)) + (assert_eq low_word 0x89abcdef) + (assert_eq high_word 0x12345678)) + + +(case procedural_loop_selects_constant_packed_bytes + (source "loop_constant_packed_bytes.sv" #" + module Top(input logic [1:0] addr, output logic [7:0] q); + localparam ID = "ABCD"; + logic [7:0] rom[4]; + initial begin + integer last; + last = 3; + for (integer i = 0; i < 4; i = i + 1) begin + rom[i] = ID[8*(last-i) +: 8]; + end + end + assign q = rom[addr]; + endmodule + "#) + (top Top) + (assert_eq q 0x41) + (modify (set addr 1)) + (assert_eq q 0x42) + (modify (set addr 2)) + (assert_eq q 0x43) + (modify (set addr 3)) + (assert_eq q 0x44)) diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 94701d08590..7f38381d410 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -3,6 +3,17 @@ use super::*; // IEEE 1800-2023 11.5.1: the index operator and declaration direction // independently determine the endpoints of the selected range. sv_backends! { + fn procedural_loop_selects_constant_packed_bytes(sim) { + @case "indexed_select::procedural_loop_selects_constant_packed_bytes"; + } + + fn procedural_loop_selects_packed_words(sim) { + @case "indexed_select::procedural_loop_selects_packed_words"; + } + fn procedural_loop_reads_packed_words_into_memory(sim) { + @case "indexed_select::procedural_loop_reads_packed_words_into_memory"; + } + fn procedural_loop_writes_memory_word_part_selects(sim) { @case "indexed_select::procedural_loop_writes_memory_word_part_selects"; } From 20012bcdf87c5e07edfc401330b9532a054e4443 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 14:57:44 +0900 Subject: [PATCH 2/2] feat(sv)!: support classes with properties, methods and constructors SystemVerilog classes declared in a module now simulate. A class variable is a 32-bit handle of an object in the simulator heap that already holds strings (IEEE 1800-2023 8.4). - The heap keeps objects as their class id and property bytes, with the offsets of handle properties so that collection follows them from object to object. Operations through `null` record a fault that the runtime reports as a runtime error after the step. - The parser records class declarations: name, base, qualifiers, properties and methods. - The analyzer lays out each class (2-state integral properties up to 64 bits, `string` and class handles; bases first) and rewrites property reads and writes into object operations that carry the layout. Methods become subroutines `C::m` whose first argument is `this`; a constructor, explicit or implicit, creates the object, runs the property initializers and returns the handle. Inside a method, properties shadow module names. `extern` methods use their out-of-block definitions; pure virtual methods and interface classes are not lowered. - A variable initialized with a bare `new` is kept when its type is a class instead of being dropped like a covergroup instance. - The frontend lowers object operations to calls of the heap helper. - Checkpoints keep objects. State files cannot record them: `StateSchema::capture` now returns a `Result` and fails with `StateError::Objects` while a variable holds an object. 4-state, `real`, array and wider properties, base-class constructors and `super`, virtual method calls, static members and parameterized classes remain unsupported. sv-tests: 8.4, 8.5, 8.6, 8.12-assignment, 8.24, 8.26.5-implemented class handle and 6.20.6-const now pass in both state modes (500 / 502). Verilator and Icarus limitations on the new shared cases are recorded. BREAKING CHANGE: `StateSchema::capture` returns `Result`, `StateError` has an `Objects` variant and `ValueKind` an `ObjRef` variant. Change-Id: I2389fee4f668b7d915cc475f31a0be37e4030255 --- conformance/sv-tests/README.md | 13 + conformance/sv-tests/expected.tsv | 28 +- crates/celox-design/src/lib.rs | 2 + crates/celox-frontend-sv/src/lowering.rs | 48 +- crates/celox-frontend-sv/src/lowering/ff.rs | 19 +- .../src/lowering/ff/objects.rs | 81 +++ .../src/lowering/ff/strings.rs | 16 +- .../src/lowering/procedural.rs | 17 +- crates/celox-heap/src/lib.rs | 89 +++- crates/celox-heap/src/objects.rs | 185 +++++++ crates/celox-heap/src/ops.rs | 28 + crates/celox-napi/src/lib.rs | 10 +- crates/celox-sv-analyzer/src/ast.rs | 27 +- .../src/ast/array_compatibility.rs | 1 + .../src/ast/bound_patterns.rs | 4 + crates/celox-sv-analyzer/src/ast/case.rs | 5 + crates/celox-sv-analyzer/src/ast/classes.rs | 320 ++++++++++++ .../celox-sv-analyzer/src/ast/comb_rewrite.rs | 4 + .../src/ast/const_functions.rs | 2 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 17 +- .../src/ast/dimensions/discovery.rs | 134 ++++- .../src/ast/dimensions/query_binding.rs | 1 + .../src/ast/dimensions/tests.rs | 1 + .../src/ast/expression_binding.rs | 11 + .../src/ast/expression_binding/direct.rs | 104 +++- .../src/ast/expression_binding/objects.rs | 254 +++++++++ .../src/ast/expression_binding/strings.rs | 45 +- crates/celox-sv-analyzer/src/ast/functions.rs | 1 + crates/celox-sv-analyzer/src/ast/generate.rs | 6 +- crates/celox-sv-analyzer/src/ast/inlining.rs | 4 + .../src/ast/packed_structs/selects.rs | 1 + .../src/ast/parameters/skipped.rs | 3 + crates/celox-sv-analyzer/src/ast/patterns.rs | 1 + .../src/ast/patterns/binding.rs | 4 + .../celox-sv-analyzer/src/ast/procedural.rs | 486 +++++++++++++++++- .../src/ast/subroutine_owners.rs | 5 +- .../celox-sv-analyzer/src/ast/type_binding.rs | 24 +- .../src/ast/type_binding/binding.rs | 4 + crates/celox-sv-analyzer/src/ir.rs | 15 +- .../celox-sv-analyzer/src/system_functions.rs | 76 ++- crates/celox-sv-analyzer/src/typecheck.rs | 2 +- crates/celox-sv-syntax/src/nodes.rs | 50 ++ crates/celox-sv-syntax/src/parser.rs | 13 + crates/celox-sv-syntax/src/parser/classes.rs | 119 ++++- .../src/parser/declarations.rs | 7 + .../celox-sv-syntax/src/parser/procedures.rs | 15 +- crates/celox-sv-syntax/src/parser/tests.rs | 50 ++ crates/celox-test-suite/LIMITATIONS.md | 3 + .../celox-test-suite/src/sv/cases/class.vtest | 231 +++++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../verification/sv/icarus.json | 1 + .../verification/sv/icarus/class.json | 164 ++++++ .../verification/sv/limitations.json | 55 ++ .../verification/sv/limitations/icarus.json | 52 +- .../sv/limitations/verilator.json | 10 +- .../verification/sv/verilator.json | 1 + .../verification/sv/verilator/class.json | 104 ++++ crates/celox/src/simulation.rs | 1 + crates/celox/src/simulator.rs | 6 +- crates/celox/src/simulator/heap.rs | 45 +- crates/celox/src/simulator/state_file.rs | 21 +- crates/celox/src/testbench.rs | 16 +- .../tests/frontends/systemverilog/class.rs | 89 ++++ crates/celox/tests/systemverilog.rs | 2 + docs/guide/systemverilog-reference.md | 18 +- docs/guide/systemverilog.md | 2 +- docs/ja/guide/systemverilog-reference.md | 9 +- docs/ja/guide/systemverilog.md | 2 +- 68 files changed, 3009 insertions(+), 179 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/ff/objects.rs create mode 100644 crates/celox-heap/src/objects.rs create mode 100644 crates/celox-sv-analyzer/src/ast/classes.rs create mode 100644 crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs create mode 100644 crates/celox-test-suite/src/sv/cases/class.vtest create mode 100644 crates/celox-test-suite/verification/sv/icarus/class.json create mode 100644 crates/celox-test-suite/verification/sv/verilator/class.json create mode 100644 crates/celox/tests/frontends/systemverilog/class.rs diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 965e6cbfc51..abc9b898890 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -141,6 +141,19 @@ The full pinned run reviewed all 2,054 rows, with 496 passing cases in 2state and 498 in 4state; no passing case regresses. The existing scanf probes retain their verdicts because their other unsupported constructs remain unchanged. +Classes update fourteen reviewed expectation rows: both state modes for +`8.4--instantiation`, `8.5--properties`, `8.6--methods`, `8.12--assignment`, +`8.24--out_of_block_methods`, `8.26.5--implemented_class_handle` and +`6.20.6--const` change from fail to pass. The simulated cases were run and their +values checked, including the shared object behind two handles in +`8.12--assignment`. Full official runs at the pinned revision report 524 passing +cases in 2state and 526 in 4state. No passing case regresses: classes that are +declared but never constructed, interface classes and pure virtual methods are +not lowered. `8.7--constructor` keeps failing because it initializes an +implicitly static procedural variable without the `static` keyword, which IEEE +1800-2023 6.21 requires. Inheritance with constructors, `super`, static members, +virtual dispatch and parameterized classes stay unsupported. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 1415a69311c..612e0df260b 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1217,8 +1217,8 @@ chapter-6/6.20.5--specparam.sv 2state pass chapter-6/6.20.5--specparam.sv 4state pass chapter-6/6.20.5--specparam_inv.sv 2state pass chapter-6/6.20.5--specparam_inv.sv 4state pass -chapter-6/6.20.6--const.sv 2state fail -chapter-6/6.20.6--const.sv 4state fail +chapter-6/6.20.6--const.sv 2state pass +chapter-6/6.20.6--const.sv 4state pass chapter-6/6.23--localparam_type_decl.sv 2state pass chapter-6/6.23--localparam_type_decl.sv 4state pass chapter-6/6.23--type_op.sv 2state fail @@ -1465,8 +1465,8 @@ chapter-8/8.10--static_methods.sv 2state fail chapter-8/8.10--static_methods.sv 4state fail chapter-8/8.11--this.sv 2state pass chapter-8/8.11--this.sv 4state pass -chapter-8/8.12--assignment.sv 2state fail -chapter-8/8.12--assignment.sv 4state fail +chapter-8/8.12--assignment.sv 2state pass +chapter-8/8.12--assignment.sv 4state pass chapter-8/8.12--shallow_copy.sv 2state fail chapter-8/8.12--shallow_copy.sv 4state fail chapter-8/8.13--inheritance.sv 2state fail @@ -1499,8 +1499,8 @@ chapter-8/8.22--dynamic_method_lookup.sv 2state fail chapter-8/8.22--dynamic_method_lookup.sv 4state fail chapter-8/8.23--scope_resolution.sv 2state fail chapter-8/8.23--scope_resolution.sv 4state fail -chapter-8/8.24--out_of_block_methods.sv 2state fail -chapter-8/8.24--out_of_block_methods.sv 4state fail +chapter-8/8.24--out_of_block_methods.sv 2state pass +chapter-8/8.24--out_of_block_methods.sv 4state pass chapter-8/8.25--parametrized_class_extend.sv 2state fail chapter-8/8.25--parametrized_class_extend.sv 4state fail chapter-8/8.25.1--parametrized_class_invalid_scope_resolution.sv 2state pass @@ -1525,8 +1525,8 @@ chapter-8/8.26.4--illegal_implements_parameter.sv 2state pass chapter-8/8.26.4--illegal_implements_parameter.sv 4state pass chapter-8/8.26.5--cast_between_interface_classes.sv 2state fail chapter-8/8.26.5--cast_between_interface_classes.sv 4state fail -chapter-8/8.26.5--implemented_class_handle.sv 2state fail -chapter-8/8.26.5--implemented_class_handle.sv 4state fail +chapter-8/8.26.5--implemented_class_handle.sv 2state pass +chapter-8/8.26.5--implemented_class_handle.sv 4state pass chapter-8/8.26.5--invalid_interface_instantiation.sv 2state pass chapter-8/8.26.5--invalid_interface_instantiation.sv 4state pass chapter-8/8.26.6.1--name_conflict_resolved.sv 2state fail @@ -1545,16 +1545,16 @@ chapter-8/8.26.7--partial_implementation.sv 2state fail chapter-8/8.26.7--partial_implementation.sv 4state fail chapter-8/8.27--forward_declaration.sv 2state pass chapter-8/8.27--forward_declaration.sv 4state pass -chapter-8/8.4--instantiation.sv 2state fail -chapter-8/8.4--instantiation.sv 4state fail +chapter-8/8.4--instantiation.sv 2state pass +chapter-8/8.4--instantiation.sv 4state pass chapter-8/8.5--parameters.sv 2state fail chapter-8/8.5--parameters.sv 4state fail -chapter-8/8.5--properties.sv 2state fail -chapter-8/8.5--properties.sv 4state fail +chapter-8/8.5--properties.sv 2state pass +chapter-8/8.5--properties.sv 4state pass 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 fail -chapter-8/8.6--methods.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 diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index c93669c5ccb..7ce9a2c0c34 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -70,6 +70,8 @@ pub enum ValueKind { Bits, /// A handle of a string in the simulator's heap. StrRef, + /// A handle of a class object in the simulator's heap, `0` for `null`. + ObjRef, } impl ValueKind { diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 3efdbe94393..8de255a72ce 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -68,8 +68,9 @@ const EVENT_PREFIX: &str = "$event["; #[derive(Clone)] struct SvVariable { float: Option, - /// A `string`: each element is a heap handle. - string: bool, + /// What each element holds: packed bits, or a heap handle of a string + /// or a class object. + value_kind: celox_design::ValueKind, path: Vec, width: usize, signed: bool, @@ -95,7 +96,7 @@ fn reads_string_variable( names: &HashMap, ) -> bool { matches!(expr, sv::ir::Expr::Ident(name) - if names.get(name).and_then(|id| variables.get(id)).is_some_and(|v| v.string)) + if names.get(name).and_then(|id| variables.get(id)).is_some_and(|v| v.value_kind == celox_design::ValueKind::StrRef)) } impl SvVariable { @@ -110,11 +111,7 @@ impl SvVariable { kind: self.domain_kind, type_kind: self.type_kind, array_dims: self.array_dims.clone(), - value_kind: if self.string { - celox_design::ValueKind::StrRef - } else { - celox_design::ValueKind::Bits - }, + value_kind: self.value_kind, }, unpacked_ranges: self.unpacked_ranges.clone(), packed_dims: self @@ -1165,7 +1162,7 @@ impl DriverScan<'_> { } continue; } - sv::ir::Callee::String(_) => continue, + sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self @@ -1549,7 +1546,7 @@ fn prepare_external_hierarchy_collecting( SvVariable { float: None, - string: false, + value_kind: celox_design::ValueKind::Bits, path: vec![variable.path.join("$")], width: variable.metadata.width, signed: variable.signed, @@ -2773,7 +2770,7 @@ fn lower_module_with_overrides( let variable = SvVariable { float: type_info.float, - string: type_info.string, + value_kind: type_info.value_kind, path, width: type_info.width, signed: type_info.signed, @@ -2857,7 +2854,7 @@ fn lower_module_with_overrides( let variable = SvVariable { float: type_info.float, - string: type_info.string, + value_kind: type_info.value_kind, path, width: type_info.width, signed: type_info.signed, @@ -2933,7 +2930,7 @@ fn lower_module_with_overrides( SvVariable { float: None, - string: false, + value_kind: celox_design::ValueKind::Bits, path: vec![parameter.name().to_string()], width, signed, @@ -4046,7 +4043,7 @@ fn lower_initial_processes( SvVariable { float: None, - string: false, + value_kind: celox_design::ValueKind::Bits, path: vec![format!("$initial[{index}]"), slot.to_string()], width, signed: false, @@ -4451,7 +4448,7 @@ fn ensure_parent_output_signals( let variable = SvVariable { float: None, - string: false, + value_kind: celox_design::ValueKind::Bits, path: vec![actual.to_string()], width: 1, signed: false, @@ -5759,7 +5756,7 @@ fn signal_kind_from_port_direction( struct SvSignalType { float: Option, - string: bool, + value_kind: celox_design::ValueKind, width: usize, signed: bool, is_4state: bool, @@ -5848,8 +5845,11 @@ fn signal_type_from_sv( sv::ir::TypeKind::Shortreal => Some(celox_sir::FloatPrecision::F32), _ => None, }; - let is_4state = - float.is_none() && !matches!(typ.kind(), sv::ir::TypeKind::Bit | sv::ir::TypeKind::String); + let is_4state = float.is_none() + && !matches!( + typ.kind(), + sv::ir::TypeKind::Bit | sv::ir::TypeKind::String | sv::ir::TypeKind::Object + ); let packed_ranges = typ .packed_ranges() .iter() @@ -5874,10 +5874,14 @@ fn signal_type_from_sv( sv::ir::TypeKind::Logic | sv::ir::TypeKind::Reg | sv::ir::TypeKind::Implicit => { PortTypeKind::Logic } - sv::ir::TypeKind::String => PortTypeKind::Other, + sv::ir::TypeKind::String | sv::ir::TypeKind::Object => PortTypeKind::Other, + }; + let value_kind = match typ.kind() { + sv::ir::TypeKind::String => celox_design::ValueKind::StrRef, + sv::ir::TypeKind::Object => celox_design::ValueKind::ObjRef, + _ => celox_design::ValueKind::Bits, }; - let string = typ.kind() == sv::ir::TypeKind::String; - if string && !array_dims.is_empty() { + if value_kind == celox_design::ValueKind::StrRef && !array_dims.is_empty() { // Selects of such an array would need to tell element selects from // character selects. return Err(sv::AnalyzerError::Unsupported( @@ -5886,7 +5890,7 @@ fn signal_type_from_sv( } Ok(SvSignalType { float, - string, + value_kind, width, signed, is_4state, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index f637b17630c..27aa30c38db 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -11,6 +11,7 @@ mod file_io; mod fread; +mod objects; mod scan; mod strings; @@ -267,7 +268,7 @@ impl<'p, 'a> Ff<'p, 'a> { } continue; } - sv::ir::Callee::String(_) => continue, + sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self.m.subroutine(&name).cloned() else { @@ -874,6 +875,11 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.string_call(*op, args)?, + Expr::Call { + callee: sv::ir::Callee::Object(op), + args, + .. + } => self.object_call(op, args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fopen), args, @@ -1009,8 +1015,11 @@ impl<'p, 'a> Ff<'p, 'a> { sv::ir::TypeKind::Shortreal => Some(celox_sir::FloatPrecision::F32), _ => None, }; - self.m.variables.get_mut(&temp).unwrap().string = - r#type.kind() == sv::ir::TypeKind::String; + self.m.variables.get_mut(&temp).unwrap().value_kind = match r#type.kind() { + sv::ir::TypeKind::String => celox_design::ValueKind::StrRef, + sv::ir::TypeKind::Object => celox_design::ValueKind::ObjRef, + _ => celox_design::ValueKind::Bits, + }; let Some(result) = result else { return Err(unsupported(format!( "void function `{name}` used as a value" @@ -4690,7 +4699,7 @@ impl Ff<'_, '_> { source: None, hidden: true, force_control: None, - string: false, + value_kind: Default::default(), }, ); let mut renames = HashMap::default(); @@ -4919,6 +4928,8 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { } // A string operation is a value of its operands. sv::ir::Callee::String(_) => continue, + // A property can change without the handle changing. + sv::ir::Callee::Object(op) => return Some(op.to_string()), sv::ir::Callee::Subroutine(name) => name, }; if !visited.insert(name.clone()) { diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs new file mode 100644 index 00000000000..4ea69cf98bb --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -0,0 +1,81 @@ +//! Class object operations (IEEE 1800-2023 clause 8), lowered to calls of +//! the heap helper. +//! +//! An object handle is 32 bits like a string handle. The analyzer has laid +//! out each class, so an operation carries the byte offset and width of the +//! property it reads or writes. + +use super::*; +use celox_heap::ops; +use sv::ir::{HandleProperty, ObjectOp}; + +impl Ff<'_, '_> { + /// The value of object operation `op`, as a temporary. + pub(super) fn object_call( + &mut self, + op: &ObjectOp, + args: &[Option], + ) -> Result { + let args = args + .iter() + .map(|arg| { + arg.clone() + .ok_or_else(|| unsupported(format!("omitted argument of {op}"))) + }) + .collect::, _>>()?; + let result = match op { + ObjectOp::New { + class, + size, + handles, + } => { + let size = self.constant64(u64::from(*size)); + let object = + self.heap_call(ops::encode(ops::OBJECT_NEW, u64::from(*class)), &[size]); + for &(offset, kind) in handles { + let offset = self.constant64(u64::from(offset)); + let kind = self.constant64(match kind { + HandleProperty::String => 0, + HandleProperty::Object => 1, + }); + self.heap_call(ops::OBJECT_HANDLE, &[object, offset, kind]); + } + object + } + ObjectOp::Load(field) => { + let object = self.handle(&args[0])?; + let offset = self.constant64(u64::from(field.offset)); + let count = self.constant64(u64::from(field.bytes())); + self.heap_call(ops::OBJECT_LOAD, &[object, offset, count]) + } + ObjectOp::Store(field) => { + let object = self.handle(&args[0])?; + let place = + self.constant64(u64::from(field.offset) | u64::from(field.bytes()) << 32); + let value = self.integer_of_width(&args[1], field.width as usize, field.signed)?; + self.heap_call(ops::OBJECT_STORE, &[object, place, value]) + } + ObjectOp::ClassOf => { + let object = self.handle(&args[0])?; + self.heap_call(ops::OBJECT_CLASS, &[object]) + } + }; + let (width, signed) = op.result_type(); + let value = self.b.alloc_bit(width, signed); + self.b.emit(SIRInstruction::Slice(value, result, 0, width)); + let (temp, name) = self.m.temp("object", width, signed, false); + let kind = match op { + ObjectOp::New { .. } => Some(celox_design::ValueKind::ObjRef), + ObjectOp::Load(field) => field.handle.map(|handle| match handle { + HandleProperty::String => celox_design::ValueKind::StrRef, + HandleProperty::Object => celox_design::ValueKind::ObjRef, + }), + ObjectOp::Store(_) | ObjectOp::ClassOf => None, + }; + if let Some(kind) = kind { + self.m.variables.get_mut(&temp).unwrap().value_kind = kind; + } + self.store(temp, SIROffset::Static(0), width, value); + Ok(sv::ir::Expr::Ident(name)) + } +} diff --git a/crates/celox-frontend-sv/src/lowering/ff/strings.rs b/crates/celox-frontend-sv/src/lowering/ff/strings.rs index 48fdf000cb5..b4bb99866e3 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/strings.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/strings.rs @@ -109,7 +109,9 @@ impl Ff<'_, '_> { let value = self.b.alloc_bit(width, false); self.b.emit(SIRInstruction::Slice(value, result, 0, width)); let (temp, name) = self.m.temp("string", width, signed, false); - self.m.variables.get_mut(&temp).unwrap().string = op.returns_string(); + if op.returns_string() { + self.m.variables.get_mut(&temp).unwrap().value_kind = celox_design::ValueKind::StrRef; + } self.store(temp, SIROffset::Static(0), width, value); Ok(sv::ir::Expr::Ident(name)) } @@ -121,7 +123,9 @@ impl Ff<'_, '_> { target: SourceVarId, value: sv::ir::Expr, ) -> sv::ir::Expr { - if self.m.var(target).string && !self.m.expr_is_string(&value) { + if self.m.var(target).value_kind == celox_design::ValueKind::StrRef + && !self.m.expr_is_string(&value) + { sv::ir::Expr::Call { callee: sv::ir::Callee::String(StringOp::FromBits), args: vec![Some(value)], @@ -134,7 +138,7 @@ impl Ff<'_, '_> { /// Call the heap helper with `code` and up to three operands; the result /// is a 64-bit register. - fn heap_call(&mut self, code: u64, operands: &[RegisterId]) -> RegisterId { + pub(super) fn heap_call(&mut self, code: u64, operands: &[RegisterId]) -> RegisterId { let mut args = vec![self.constant64(code)]; args.extend_from_slice(operands); while args.len() < celox_sir::extern_abi::HEAP_HELPER_ARGUMENTS { @@ -149,7 +153,7 @@ impl Ff<'_, '_> { dst } - fn constant64(&mut self, value: u64) -> RegisterId { + pub(super) fn constant64(&mut self, value: u64) -> RegisterId { let register = self.b.alloc_bit(64, false); self.b.emit(SIRInstruction::Imm( register, @@ -159,7 +163,7 @@ impl Ff<'_, '_> { } /// The handle of string `expr`, as a 64-bit operand. - fn handle(&mut self, expr: &sv::ir::Expr) -> Result { + pub(super) fn handle(&mut self, expr: &sv::ir::Expr) -> Result { self.integer_of_width(expr, celox_design::HANDLE_WIDTH, false) } @@ -174,7 +178,7 @@ impl Ff<'_, '_> { /// `expr` converted to `width` bits, then extended to a 64-bit operand. /// Unknown bits read as zero. - fn integer_of_width( + pub(super) fn integer_of_width( &mut self, expr: &sv::ir::Expr, width: usize, diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 707700e0b78..8cc6ba97f48 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -70,11 +70,16 @@ impl<'a> ProcModule<'a> { .name_to_id .get(name) .and_then(|id| self.variables.get(id)) - .is_some_and(|variable| variable.string), + .is_some_and(|variable| variable.value_kind == celox_design::ValueKind::StrRef), sv::ir::Expr::Call { callee: sv::ir::Callee::String(op), .. } => op.returns_string(), + sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(op), + .. + } => matches!(**op, sv::ir::ObjectOp::Load(field) + if field.handle == Some(sv::ir::HandleProperty::String)), sv::ir::Expr::Call { callee: sv::ir::Callee::Subroutine(name), .. @@ -248,7 +253,7 @@ impl<'a> ProcModule<'a> { continue; } // String operations use the simulator's heap. - sv::ir::Callee::String(_) => return true, + sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => return true, sv::ir::Callee::Subroutine(name) => name, }; if let Some(subroutine) = self.subroutine(&name) { @@ -741,7 +746,7 @@ impl<'a> ProcModule<'a> { SvVariable { float: None, - string: false, + value_kind: celox_design::ValueKind::Bits, path: vec![name.clone()], width: width.max(1), signed, @@ -811,7 +816,7 @@ impl<'a> ProcModule<'a> { let variable = SvVariable { float: None, - string: false, + value_kind: celox_design::ValueKind::Bits, path, width: 1, signed: false, @@ -882,7 +887,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::String(_) => true, + sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => true, sv::ir::Callee::Subroutine(name) => { self.subroutines.contains_key(name) || self.dpi_imports.contains_key(name) } @@ -1274,7 +1279,7 @@ pub(super) fn register_locals( SvVariable { float: type_info.float, - string: type_info.string, + value_kind: type_info.value_kind, path: vec![local.source_name.clone()], width: type_info.width, signed: type_info.signed, diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index 8185824690a..09ebcd75fa8 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -16,8 +16,11 @@ use std::sync::Arc; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; +mod objects; pub mod ops; +pub use objects::{Fault, NULL}; + /// A reference to a heap entry, as stored in state memory. pub type Handle = u32; @@ -31,7 +34,37 @@ pub const EMPTY_STRING: Handle = 0; /// unless the live set is larger. const MIN_COLLECTION_INTERVAL: usize = 1024; -/// Dynamic strings referenced by [`Handle`]. +/// What a handle refers to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum HandleKind { + String, + Object, +} + +/// A handle that a collection must keep alive, with what it refers to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Root { + pub kind: HandleKind, + pub handle: Handle, +} + +impl Root { + pub fn string(handle: Handle) -> Self { + Self { + kind: HandleKind::String, + handle, + } + } + + pub fn object(handle: Handle) -> Self { + Self { + kind: HandleKind::Object, + handle, + } + } +} + +/// Dynamic strings and class objects referenced by [`Handle`]. #[derive(Clone, Debug)] pub struct Heap { strings: HashMap>, @@ -41,6 +74,11 @@ pub struct Heap { /// Mutable strings under construction, see [`ops`]. buffers: Vec>>, free_buffers: Vec, + objects: HashMap, + /// The handle the next object gets. + next_object: Handle, + /// The first heap operation error since the runtime last checked. + fault: Option, /// Entries below this handle are never collected. pinned: Handle, created: usize, @@ -66,6 +104,9 @@ impl Heap { next: EMPTY_STRING + 1, buffers: Vec::new(), free_buffers: Vec::new(), + objects: HashMap::default(), + next_object: NULL + 1, + fault: None, pinned: 1, created: 0, live_after_collection: 1, @@ -118,9 +159,18 @@ impl Heap { false } - /// Bytes of string contents, excluding allocator overhead. + /// Bytes of string contents and object properties, excluding allocator + /// overhead. pub fn content_size(&self) -> usize { - self.strings.values().map(|value| value.len()).sum() + self.strings + .values() + .map(|value| value.len()) + .sum::() + + self + .objects + .values() + .map(objects::Object::size) + .sum::() } /// Whether enough entries were created since the last collection to make @@ -130,24 +180,43 @@ impl Heap { self.created >= MIN_COLLECTION_INTERVAL.max(self.live_after_collection) } - /// Free every unpinned entry that no handle in `roots` refers to. Roots - /// that name no entry are ignored. - pub fn collect(&mut self, roots: impl IntoIterator) { - let marked: HashSet = roots.into_iter().collect(); + /// Free every unpinned entry that `roots` cannot reach through the + /// handle properties of objects. Roots that name no entry are ignored. + pub fn collect(&mut self, roots: impl IntoIterator) { + let mut strings = HashSet::default(); + let mut objects = HashSet::default(); + let mut pending: Vec = roots.into_iter().collect(); + while let Some(root) = pending.pop() { + match root.kind { + HandleKind::String => { + strings.insert(root.handle); + } + HandleKind::Object => { + if self.objects.contains_key(&root.handle) && objects.insert(root.handle) { + pending.extend( + self.handles_of(root.handle) + .into_iter() + .map(|(kind, handle)| Root { kind, handle }), + ); + } + } + } + } let pinned = self.pinned; let lookup = &mut self.lookup; self.strings.retain(|handle, value| { - let live = *handle < pinned || marked.contains(handle); + let live = *handle < pinned || strings.contains(handle); if !live { lookup.remove(value); } live }); + self.objects.retain(|handle, _| objects.contains(handle)); // No buffer outlives the kernel that built it. self.buffers.clear(); self.free_buffers.clear(); self.created = 0; - self.live_after_collection = self.len(); + self.live_after_collection = self.len() + self.objects.len(); } fn new_buffer(&mut self, bytes: Vec) -> u64 { @@ -213,7 +282,7 @@ mod tests { let mut heap = Heap::new(); let kept = heap.intern(b"kept"); let dropped = heap.intern(b"dropped"); - heap.collect([kept, 999]); + heap.collect([Root::string(kept), Root::string(999)]); assert_eq!(heap.string(kept), b"kept"); assert!(!heap.contains(dropped)); assert!(heap.contains(EMPTY_STRING)); diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs new file mode 100644 index 00000000000..112083a86af --- /dev/null +++ b/crates/celox-heap/src/objects.rs @@ -0,0 +1,185 @@ +//! Class objects (IEEE 1800-2023 clause 8). +//! +//! An object is the class it was created as and the bytes of its +//! properties, laid out by the frontend in the encoding of state memory. +//! The heap knows nothing of the layout except which properties hold +//! handles, which the code that creates an object declares right after +//! creating it, so a collection can follow them. + +use crate::{Handle, HandleKind, Heap}; + +/// The handle of `null`, the value of zero-initialized memory. +pub const NULL: Handle = 0; + +#[derive(Clone, Debug)] +pub(crate) struct Object { + class: u32, + bytes: Box<[u8]>, + /// Byte offsets of the handle properties, with what they refer to. + pub(crate) handles: Vec<(u32, HandleKind)>, +} + +impl Object { + pub(crate) fn size(&self) -> usize { + self.bytes.len() + } +} + +/// An error that compiled code made in a heap operation, which the runtime +/// reports once control returns to it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// A property access or method call through `null` or a handle of no + /// live object (IEEE 1800-2023 8.4). + NullDereference, +} + +impl std::fmt::Display for Fault { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NullDereference => f.write_str("null object handle dereferenced"), + } + } +} + +impl Heap { + /// A new object of `class` with `size` zeroed bytes. + pub fn new_object(&mut self, class: u32, size: usize) -> Handle { + let handle = self.next_object; + self.next_object = handle + .checked_add(1) + .expect("the heap created more objects than handles can name"); + self.objects.insert( + handle, + Object { + class, + bytes: vec![0; size].into(), + handles: Vec::new(), + }, + ); + self.created += 1; + handle + } + + /// Declare that the property of `object` at byte `offset` holds a handle + /// of `kind`. + pub fn declare_handle(&mut self, object: Handle, offset: u32, kind: HandleKind) { + if let Some(object) = self.object_mut(object) { + object.handles.push((offset, kind)); + } + } + + /// The class `object` was created as, or 0 for `null`. + pub fn class_of(&self, object: Handle) -> u32 { + self.objects.get(&object).map_or(0, |object| object.class) + } + + /// `count` bytes of `object` at `offset`, little-endian. `count` is at + /// most 8. + pub fn load(&mut self, object: Handle, offset: usize, count: usize) -> u64 { + let Some(bytes) = self.object_mut(object).map(|object| &object.bytes) else { + return 0; + }; + let mut word = [0; 8]; + let count = count.min(8); + if let Some(source) = bytes.get(offset..offset + count) { + word[..count].copy_from_slice(source); + } + u64::from_le_bytes(word) + } + + /// Write the low `count` bytes of `value` into `object` at `offset`. + pub fn store(&mut self, object: Handle, offset: usize, count: usize, value: u64) { + let Some(object) = self.object_mut(object) else { + return; + }; + let count = count.min(8); + if let Some(target) = object.bytes.get_mut(offset..offset + count) { + target.copy_from_slice(&value.to_le_bytes()[..count]); + } + } + + /// The object behind `handle`, recording a fault when there is none. + fn object_mut(&mut self, handle: Handle) -> Option<&mut Object> { + let object = self.objects.get_mut(&handle); + if object.is_none() { + self.fault.get_or_insert(Fault::NullDereference); + } + object + } + + /// The first fault since the last call, if any. + pub fn take_fault(&mut self) -> Option { + self.fault.take() + } + + /// Whether `handle` names a live object. + pub fn contains_object(&self, handle: Handle) -> bool { + self.objects.contains_key(&handle) + } + + /// The handles stored in the handle properties of `object`. + pub(crate) fn handles_of(&self, object: Handle) -> Vec<(HandleKind, Handle)> { + let Some(object) = self.objects.get(&object) else { + return Vec::new(); + }; + object + .handles + .iter() + .filter_map(|&(offset, kind)| { + let bytes = object + .bytes + .get(offset as usize..offset as usize + crate::HANDLE_BYTES)?; + Some((kind, Handle::from_le_bytes(bytes.try_into().ok()?))) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Root; + + #[test] + fn properties_read_back_what_was_written() { + let mut heap = Heap::new(); + let object = heap.new_object(7, 16); + assert_eq!(heap.class_of(object), 7); + heap.store(object, 4, 4, 0x1234_5678_9abc); + assert_eq!(heap.load(object, 4, 4), 0x5678_9abc); + assert_eq!(heap.load(object, 0, 8), 0x5678_9abc_0000_0000); + assert_eq!(heap.take_fault(), None); + } + + #[test] + fn null_dereferences_are_faults_that_read_zero() { + let mut heap = Heap::new(); + assert_eq!(heap.load(NULL, 0, 4), 0); + heap.store(NULL, 0, 4, 1); + assert_eq!(heap.take_fault(), Some(Fault::NullDereference)); + assert_eq!(heap.take_fault(), None); + assert_eq!(heap.class_of(NULL), 0); + } + + #[test] + fn collection_follows_handle_properties() { + let mut heap = Heap::new(); + let outer = heap.new_object(1, 8); + let inner = heap.new_object(2, 4); + let text = heap.intern(b"kept through an object"); + let lost = heap.new_object(3, 4); + heap.declare_handle(outer, 0, HandleKind::Object); + heap.declare_handle(outer, 4, HandleKind::String); + heap.store(outer, 0, 4, inner.into()); + heap.store(outer, 4, 4, text.into()); + heap.collect([Root::object(outer)]); + assert!(heap.contains_object(outer)); + assert!(heap.contains_object(inner)); + assert!(!heap.contains_object(lost)); + assert_eq!(heap.string(text), b"kept through an object"); + heap.collect([]); + assert!(!heap.contains_object(outer)); + assert!(!heap.contains(text)); + } +} diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index 80097bb14b0..e8680035a1f 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -49,6 +49,18 @@ pub const REPLICATE: u64 = 24; pub const ITOA: u64 = 25; /// `freeze(buffer)`: the interned string holding `buffer`, which is freed. pub const FREEZE: u64 = 32; +/// `new_object(size)`: a new object of the class in the parameter, with +/// `size` zeroed bytes. +pub const OBJECT_NEW: u64 = 48; +/// `declare_handle(object, offset, kind)`: the property at byte `offset` +/// holds a handle; `kind` is 0 for a string and 1 for an object. +pub const OBJECT_HANDLE: u64 = 49; +/// `load(object, offset, count)`: `count` bytes at `offset`, at most 8. +pub const OBJECT_LOAD: u64 = 50; +/// `store(object, offset | count << 32, value)`: write `count` bytes. +pub const OBJECT_STORE: u64 = 51; +/// `class_of(object)`: its class, or 0 for `null`. +pub const OBJECT_CLASS: u64 = 52; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -140,6 +152,22 @@ impl Heap { let bytes = self.take_buffer(a); self.intern(&bytes).into() } + OBJECT_NEW => self.new_object(parameter as u32, a as usize).into(), + OBJECT_HANDLE => { + let kind = if c == 0 { + crate::HandleKind::String + } else { + crate::HandleKind::Object + }; + self.declare_handle(a as Handle, b as u32, kind); + 0 + } + OBJECT_LOAD => self.load(a as Handle, b as usize, c as usize), + OBJECT_STORE => { + self.store(a as Handle, b as u32 as usize, (b >> 32) as usize, c); + 0 + } + OBJECT_CLASS => self.class_of(a as Handle).into(), other => panic!("unknown heap operation {other}"), } } diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index 0a531dbc467..ddc686da9fd 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -1052,7 +1052,10 @@ impl HandleBackend { } } - fn save_state_file(&self, schema: &celox::StateSchema) -> celox::StateFile { + fn save_state_file( + &self, + schema: &celox::StateSchema, + ) -> std::result::Result { match self { Self::Default(backend) => schema.capture(backend), Self::Tiered(backend) => schema.capture(backend.as_ref()), @@ -1709,7 +1712,10 @@ impl NativeSimulatorHandle { .ok_or_else(|| Error::from_reason("Simulator has been disposed"))?; b.eval_comb() .map_err(|e| napi_runtime_error(&runtime_errors, e))?; - state_file_bytes(&b.save_state_file(&self.state_schema)) + let file = b + .save_state_file(&self.state_schema) + .map_err(|e| Error::from_reason(e.to_string()))?; + state_file_bytes(&file) } /// Load state file bytes, matching objects by path, and settle diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 306a1d59579..2de89298948 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -27,6 +27,8 @@ pub(super) struct AnalysisState { root_subroutines: std::cell::Cell, next_call_site: std::rc::Rc>, timescales: timescales::State, + /// Classes laid out so far, by name. + classes: std::cell::RefCell>>, } /// Syntax and specialization bindings for one scope within an analysis session. @@ -90,7 +92,9 @@ impl Deref for AnalysisContext<'_> { } } -pub use crate::system_functions::{ArrayQuery, Callee, StringOp, SystemFunction, SystemTask}; +pub use crate::system_functions::{ + ArrayQuery, Callee, ObjectOp, StringOp, SystemFunction, SystemTask, +}; use crate::{AnalyzerError, system_functions, typecheck}; mod array_compatibility; @@ -99,6 +103,7 @@ mod assignment_analysis; mod bound_patterns; mod case; mod casts; +mod classes; mod comb_process; pub use bound_patterns::BoundPattern; mod comb_rewrite; @@ -1048,6 +1053,7 @@ impl Module { dimensions: function.return_dimensions, signed: function.return_signed, is_2state: function.return_is_2state, + string: function.return_string, }, ) })); @@ -1065,9 +1071,12 @@ impl Module { dimensions: Some(usize::from(r#type.width() > 1)), signed: r#type.is_signed(), is_2state: !r#type.is_4state(), + string: false, }, )) })); + // Class methods are subroutines `class::method` (IEEE 1800-2023 8.6). + dimensions::all_class_signatures(syntax_tree, &mut packed_dimensions); packed_dimensions.functions = Arc::new(functions.clone()); packed_dimensions.expression_signedness = expression_signedness.clone().into(); for instance in &mut instances { @@ -1919,6 +1928,8 @@ pub struct Type { /// named type, which is signed although the whole array is not (IEEE /// 1800-2023 7.4.1). signed_element_depth: Option, + /// The class of an object handle type. + class: Option, } impl Type { @@ -1931,6 +1942,7 @@ impl Type { unpacked_ranges: Vec::new(), members: Vec::new(), signed_element_depth: None, + class: None, } } @@ -1943,9 +1955,15 @@ impl Type { unpacked_ranges: Vec::new(), members: Vec::new(), signed_element_depth: None, + class: None, } } + /// The class of an object handle type. + pub fn class(&self) -> Option<&str> { + self.class.as_deref() + } + pub fn kind(&self) -> TypeKind { self.kind } @@ -1969,6 +1987,9 @@ pub enum TypeKind { Shortreal, /// IEEE 1800-2023 6.16: a dynamically sized string, held as a heap handle. String, + /// IEEE 1800-2023 8.4: a handle of a class object, `null` or an object + /// in the heap. + Object, Bit, Logic, Reg, @@ -2641,6 +2662,8 @@ struct VariableDimensions { real: bool, /// A `string`: each element is a heap handle, not packed bits. string: bool, + /// The class of an object handle variable. + class: Option, packed: Vec, unpacked: Vec, signed: bool, @@ -2668,6 +2691,8 @@ struct FunctionReturnMetadata { dimensions: Option, signed: bool, is_2state: bool, + /// The function returns a `string`. + string: bool, } #[derive(Debug, Clone, Default, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs index 38200c36ebe..7f9ae36c9cb 100644 --- a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs +++ b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs @@ -53,6 +53,7 @@ pub(super) fn selected_unpacked_shape( Some(VariableDimensions { real: false, string: false, + class: None, unpacked: unpacked.to_vec(), ..shape.clone() }) diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs index 3c7fc313c9a..63ff17e5348 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -164,6 +164,7 @@ impl Value { let shape = VariableDimensions { real: false, string: false, + class: None, unpacked: rest.to_vec(), ..shape.clone() }; @@ -227,6 +228,7 @@ impl BoundPattern { VariableDimensions { real: false, string: false, + class: None, unpacked: rest.to_vec(), ..shape.clone() }; @@ -267,6 +269,7 @@ impl BoundPattern { VariableDimensions { real: false, string: false, + class: None, packed: rest.to_vec(), signed: shape.signed_element_depth == Some(1), signed_element_depth: shape @@ -293,6 +296,7 @@ impl BoundPattern { VariableDimensions { real: false, string: false, + class: None, packed: Vec::new(), signed: false, signed_element_depth: None, diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index b5cfa3255c1..f309f94a38d 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -64,6 +64,11 @@ pub(super) fn expr_is_two_state( callee: Callee::String(op), .. } => !matches!(op, crate::system_functions::StringOp::Atoi(_)), + // Properties are 2-state. + Expr::Call { + callee: Callee::Object(_), + .. + } => true, Expr::Call { callee: Callee::Subroutine(name), .. diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs new file mode 100644 index 00000000000..9b3aefc0111 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -0,0 +1,320 @@ +//! Classes (IEEE 1800-2023 clause 8). +//! +//! A class variable holds a handle of an object in the simulator's heap. The +//! analyzer lays out the properties of each class as bytes of the object, +//! in the encoding of state memory, and rewrites property accesses into +//! [`ObjectOp`] calls that carry that layout. Methods become subroutines whose +//! first argument is the handle `this`; a constructor allocates the object +//! and returns its handle. + +use std::rc::Rc; + +use super::*; +use crate::system_functions::{HandleProperty, ObjectField, ObjectOp}; + +/// Bit width of a handle, see `celox_design::HANDLE_WIDTH`. +pub(super) const HANDLE_WIDTH: usize = 32; + +/// The name of the implicit handle argument of a method. +pub(super) const THIS: &str = "this"; + +/// A property of a class as laid out in its objects. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Property { + pub name: String, + pub r#type: Type, + pub field: ObjectField, + /// The initializer of the declaration, evaluated by the constructor. + pub initializer: Option, +} + +/// A method of a class. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Method { + pub name: String, + /// The class that declares the method. + pub owner: String, + pub native: celox_sv_syntax::SubroutineId, + pub qualifiers: celox_sv_syntax::ClassQualifiers, +} + +/// A class with the layout of its objects. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Class { + pub name: String, + /// Identifies the class at run time; stable across modules and runs. + pub id: u32, + pub base: Option, + /// Properties of the class and its bases, bases first. + pub properties: Vec, + /// Methods visible in the class, overrides replacing inherited ones. + pub methods: Vec, + /// Bytes of an object. + pub size: u32, +} + +impl Class { + /// The property `name`; one the class declares hides one of a base + /// (IEEE 1800-2023 8.14). + pub fn property(&self, name: &str) -> Option<&Property> { + self.properties + .iter() + .rev() + .find(|property| property.name == name) + } + + pub fn method(&self, name: &str) -> Option<&Method> { + self.methods.iter().find(|method| method.name == name) + } + + /// The subroutine name of `method` of `owner`. + pub fn subroutine_name(owner: &str, method: &str) -> String { + format!("{owner}::{method}") + } +} + +/// The declaration of class `name`, if one exists. +fn declaration<'a>( + tree: &'a AnalysisContext<'_>, + name: &str, +) -> Option<&'a celox_sv_syntax::ClassDeclaration> { + tree.declarations() + .classes + .iter() + .find(|class| instances::normalize_identifier(&class.name.spelling) == name) +} + +/// The classes that body item `item` declares, except interface classes, +/// which have no implementation (IEEE 1800-2023 8.26). +pub(super) fn item_classes( + item: celox_sv_syntax::BodyItemId, + tree: &AnalysisContext<'_>, +) -> Vec { + let native = tree.declarations(); + let item = native.body_item(item); + if !matches!(&item.kind, celox_sv_syntax::BodyItemKind::Unconverted { category, .. } if category == "class") + { + return Vec::new(); + } + native + .classes + .iter() + .filter(|class| { + !class.interface + && item.tokens.start <= class.tokens.start + && class.tokens.end <= item.tokens.end + }) + .map(|class| instances::normalize_identifier(&class.name.spelling)) + .collect() +} + +/// The methods that class `name` implements, with their definitions: the +/// method itself or, for an `extern` method, its out-of-block definition. +/// A pure virtual method has none (IEEE 1800-2023 8.21). +pub(super) fn declared_methods( + tree: &AnalysisContext<'_>, + name: &str, +) -> Converted> { + let Some(declaration) = declaration(tree, name) else { + return Ok(Vec::new()); + }; + let native = tree.declarations(); + declaration + .methods + .iter() + .filter(|method| !method.qualifiers.is_pure) + .map(|method| { + let subroutine = native.subroutine(method.subroutine); + if !subroutine.prototype { + return Ok(method.subroutine); + } + let method_name = instances::normalize_identifier(&subroutine.name.spelling); + out_of_block_definition(tree, name, &method_name).ok_or_else(|| { + unsupported(format!( + "extern method `{name}::{method_name}` without a body" + )) + }) + }) + .collect() +} + +/// The handle type of class `name`, if it is a class. +pub(super) fn handle_type(tree: &AnalysisContext<'_>, name: &str) -> Option { + declaration(tree, name)?; + let mut ty = Type::new(TypeKind::Object); + ty.packed_ranges.push(PackedRange::new( + ConstExpr::Literal((HANDLE_WIDTH - 1).to_string()), + ConstExpr::Literal("0".into()), + )); + ty.class = Some(name.to_owned()); + Some(ty) +} + +/// The class `name`, laid out with its bases. +pub(super) fn class( + tree: &AnalysisContext<'_>, + name: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + if let Some(class) = tree.state.classes.borrow().get(name) { + return Ok(class.clone()); + } + let declaration = + declaration(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + if declaration.interface { + return Err(unsupported("interface class")); + } + let native = tree.declarations(); + let base = match &declaration.base { + None => None, + Some(base) => { + let ty = type_binding::procedural_type(base.data_type, native, tree, env, aliases)? + .and_then(|ty| ty.class.clone()) + .ok_or_else(|| unsupported("base class type"))?; + Some(class(tree, &ty, env, aliases)?) + } + }; + let mut properties = base + .as_ref() + .map(|base| base.properties.clone()) + .unwrap_or_default(); + let mut size = base.as_ref().map_or(0, |base| base.size); + for property in &declaration.properties { + if property.qualifiers.is_static { + return Err(unsupported("static class property")); + } + let ty = type_binding::procedural_type( + property.declaration.data_type, + native, + tree, + env, + aliases, + )? + .ok_or_else(|| unsupported("class property type"))?; + for variable in &property.declaration.variables { + if !variable.dimensions.is_empty() { + return Err(unsupported("class property with unpacked dimensions")); + } + let name = instances::normalize_identifier(&variable.name.spelling); + let field = field(&tree.state, &ty, env, size)?; + size = field.offset + field.bytes(); + properties.push(Property { + name, + r#type: ty.clone(), + field, + initializer: variable.value, + }); + } + } + let mut methods = base + .as_ref() + .map(|base| base.methods.clone()) + .unwrap_or_default(); + for method in &declaration.methods { + let subroutine = native.subroutine(method.subroutine); + let method_name = instances::normalize_identifier(&subroutine.name.spelling); + // A pure virtual method has no implementation to call; calls of + // virtual methods are rejected where they are bound. + if method.qualifiers.is_pure { + continue; + } + let native_id = if subroutine.prototype { + out_of_block_definition(tree, name, &method_name).ok_or_else(|| { + unsupported(format!( + "extern method `{name}::{method_name}` without a body" + )) + })? + } else { + method.subroutine + }; + methods.retain(|known| known.name != method_name); + methods.push(Method { + name: method_name, + owner: name.to_owned(), + native: native_id, + qualifiers: method.qualifiers, + }); + } + let class = Rc::new(Class { + name: name.to_owned(), + id: class_id(name), + base: base.map(|base| base.name.clone()), + properties, + methods, + size: size.max(1), + }); + tree.state + .classes + .borrow_mut() + .insert(name.to_owned(), class.clone()); + Ok(class) +} + +/// The definition `function ... class::method` outside class `class`. +fn out_of_block_definition( + tree: &AnalysisContext<'_>, + class: &str, + method: &str, +) -> Option { + let native = tree.declarations(); + native.subroutine_ids().find(|&id| { + let subroutine = native.subroutine(id); + !subroutine.prototype + && instances::normalize_identifier(&subroutine.name.spelling) == method + && matches!(&subroutine.scope[..], [scope] + if instances::normalize_identifier(&scope.name.spelling) == class) + }) +} + +/// The layout of a property of type `ty` at the first aligned offset at or +/// after `offset`. +fn field( + state: &AnalysisState, + ty: &Type, + env: &HashMap, + offset: u32, +) -> Converted { + let (width, signed, handle) = match ty.kind() { + TypeKind::String => (HANDLE_WIDTH, false, Some(HandleProperty::String)), + TypeKind::Object => (HANDLE_WIDTH, false, Some(HandleProperty::Object)), + TypeKind::Bit => { + let shape = casts::expr_type_from_type(state, ty, env) + .ok_or_else(|| unsupported("class property type"))?; + if shape.width > 64 { + return Err(unsupported("class property wider than 64 bits")); + } + (shape.width, shape.signed, None) + } + TypeKind::Real | TypeKind::Shortreal => { + return Err(unsupported("real class property")); + } + TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit => { + return Err(unsupported("4-state class property")); + } + }; + Ok(ObjectField { + offset: offset.next_multiple_of(8), + width: width as u32, + signed, + handle, + }) +} + +/// A run-time identifier of class `name`: an FNV-1a hash, never 0, which +/// `null` reads as. +fn class_id(name: &str) -> u32 { + let hash = name.bytes().fold(0x811c_9dc5u32, |hash, byte| { + (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) + }); + hash.max(1) +} + +/// A call of object operation `op`. +pub(super) fn object_call(op: ObjectOp, args: Vec) -> Expr { + Expr::Call { + callee: Callee::Object(Box::new(op)), + args: args.into_iter().map(Some).collect(), + arg_order: Vec::new(), + } +} diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index e5310d1e48b..41cb101e880 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -103,6 +103,10 @@ pub(super) fn expr_static_width( callee: Callee::String(op), .. } => Some(op.result_type().0), + Expr::Call { + callee: Callee::Object(op), + .. + } => Some(op.result_type().0), Expr::Call { callee: Callee::Subroutine(name), .. diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 8d31d1bdda6..93bb8241772 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -610,7 +610,7 @@ fn simulation_state_readers(functions: &[Subroutine]) -> HashMap { reads.get_or_insert(*system); } - Callee::System(_) | Callee::String(_) => {} + Callee::System(_) | Callee::String(_) | Callee::Object(_) => {} 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 80f2c03c262..bcc9ca9afec 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -3,6 +3,7 @@ use super::*; mod discovery; pub(super) use discovery::State; +pub(super) use discovery::all_class_signatures; mod query_binding; pub(super) use discovery::query_operand_dimensions_id; mod queries; @@ -134,12 +135,17 @@ pub(super) fn packed_dimensions_from_ports_and_signals( randomizable: !port.r#type().is_enum && port.randomizable, 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), packed: signal_packed_dimension_widths(port.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(port.r#type().unpacked_ranges()), signed: port.r#type().is_signed(), is_2state: matches!( port.r#type().kind(), - TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal | TypeKind::String + TypeKind::Bit + | TypeKind::Real + | TypeKind::Shortreal + | TypeKind::String + | TypeKind::Object ), members: port.r#type().members.clone(), signed_element_depth: port.r#type().signed_element_depth, @@ -153,12 +159,17 @@ pub(super) fn packed_dimensions_from_ports_and_signals( randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const, 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), packed: signal_packed_dimension_widths(signal.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(signal.r#type().unpacked_ranges()), signed: signal.r#type().is_signed(), is_2state: matches!( signal.r#type().kind(), - TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal | TypeKind::String + TypeKind::Bit + | TypeKind::Real + | TypeKind::Shortreal + | TypeKind::String + | TypeKind::Object ), members: signal.r#type().members.clone(), signed_element_depth: signal.r#type().signed_element_depth, @@ -348,6 +359,7 @@ fn extend_variable_dimensions_from_const_env( .collect(), members: Vec::new(), signed_element_depth: None, + class: None, }; let mut shape = procedural::dimensions_from_type(&ty); if let Some(existing) = context.get(name) { @@ -522,6 +534,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP randomizable: true, real: false, string: false, + class: None, packed: function_packed_dimension_widths(¶meter.packed_ranges), unpacked: Vec::new(), signed: parameter.declared_signed.unwrap_or(false), diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index d32057707b9..ce1ddd82ae2 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -161,11 +161,9 @@ fn variables( let Some(base) = type_binding::bind(declaration.data_type, tree, context)? else { return Ok(()); }; - for variable in declaration - .variables - .iter() - .filter(|variable| type_binding::ordinary_variable(variable, tree.declarations())) - { + for variable in declaration.variables.iter().filter(|variable| { + type_binding::ordinary_variable(variable, declaration.data_type, tree.declarations()) + }) { let ty = type_with_dimensions(base.clone(), &variable.dimensions, tree, context)?; shape(context, name(&variable.name), &ty, local); publish(&tree.state.dimensions, key, context); @@ -368,6 +366,7 @@ 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), } } fn signature( @@ -376,8 +375,107 @@ fn signature( context: &mut PackedDimensions, ) -> Converted<()> { let subroutine = tree.declarations().subroutine(id); - let n = name(&subroutine.name); let formals = formal_types(subroutine, tree, context)?; + let result = return_type(subroutine, tree, context)?; + publish_signature(name(&subroutine.name), formals, result, tree, context); + Ok(()) +} +/// The return type of a function, `None` for a task. +fn return_type( + subroutine: &celox_sv_syntax::Subroutine, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, +) -> Converted>> { + if subroutine.kind != SubroutineKind::Function { + return Ok(None); + } + let mut ty = subroutine + .return_type + .map(|id| type_binding::bind(id, tree, context)) + .transpose()? + .flatten(); + if subroutine.return_type.is_some_and(|id| { + matches!( + tree.declarations().data_type(id).kind, + DataTypeKind::Implicit + ) + }) && let Some(ty) = &mut ty + { + ty.kind = TypeKind::Logic; + } + Ok(Some(ty)) +} +/// The methods of `class` as subroutines `class::method`: a method takes +/// the handle `this` before its formals, and the constructor, declared or +/// implicit, returns the handle of the object it creates (IEEE 1800-2023 +/// 8.6, 8.7). +fn class_signatures( + class: &celox_sv_syntax::ClassDeclaration, + tree: &AnalysisContext<'_>, + context: &mut PackedDimensions, +) -> Converted<()> { + let class_name = name(&class.name); + let Some(handle) = classes::handle_type(tree, &class_name) else { + return Ok(()); + }; + let mut constructor = false; + for method in &class.methods { + let subroutine = tree.declarations().subroutine(method.subroutine); + let mut formals = formal_types(subroutine, tree, context)?; + let result = if subroutine.kind == SubroutineKind::Constructor { + constructor = true; + Some(Some(handle.clone())) + } else { + formals.insert( + 0, + ( + FunctionArgumentMetadata { + name: classes::THIS.into(), + direction: ParamDirection::Input, + has_default: false, + }, + handle.clone(), + ), + ); + return_type(subroutine, tree, context)? + }; + publish_signature( + classes::Class::subroutine_name(&class_name, &name(&subroutine.name)), + formals, + result, + tree, + context, + ); + } + if !constructor { + publish_signature( + classes::Class::subroutine_name(&class_name, "new"), + Vec::new(), + Some(Some(handle)), + tree, + context, + ); + } + Ok(()) +} +/// Publish the signatures of the methods of every class in the source. +pub(in crate::ast) fn all_class_signatures( + tree: &AnalysisContext<'_>, + context: &mut PackedDimensions, +) { + for class in &tree.declarations().classes { + if !class.interface { + let _ = class_signatures(class, tree, context); + } + } +} +fn publish_signature( + n: String, + formals: Vec<(FunctionArgumentMetadata, Type)>, + result: Option>, + tree: &AnalysisContext<'_>, + context: &mut PackedDimensions, +) { let arguments = formals .iter() .map(|(argument, _)| argument.clone()) @@ -396,27 +494,12 @@ fn signature( .map(|(argument, _)| argument.name.clone()) .collect(), ); - if subroutine.kind == SubroutineKind::Function { - let mut ty = subroutine - .return_type - .map(|id| type_binding::bind(id, tree, context)) - .transpose()? - .flatten(); - if subroutine.return_type.is_some_and(|id| { - matches!( - tree.declarations().data_type(id).kind, - DataTypeKind::Implicit - ) - }) && let Some(ty) = &mut ty - { - ty.kind = TypeKind::Logic; - } + if let Some(ty) = result { context.function_return_types.insert( n, return_metadata(&tree.state, ty.as_ref(), arguments, context), ); } - Ok(()) } fn local_declaration( item: &LocalDeclaration, @@ -605,7 +688,9 @@ pub(in crate::ast) fn query_operand_dimensions_id( let before = context.clone(); for frame in &frames { for id in frame { - if let BodyItemKind::Subroutine(id) = native.body_item(*id).kind { + if let BodyItemKind::Subroutine(id) = native.body_item(*id).kind + && native.subroutine(id).scope.is_empty() + { let _ = signature(id, tree, &mut context); publish(&tree.state.dimensions, &key, &context); } else if let BodyItemKind::Dpi(id) = native.body_item(*id).kind @@ -621,12 +706,15 @@ pub(in crate::ast) fn query_operand_dimensions_id( dimensions: Some(usize::from(ty.width() > 1)), signed: ty.is_signed(), is_2state: !ty.is_4state(), + string: false, }, ); publish(&tree.state.dimensions, &key, &context); } } } + all_class_signatures(tree, &mut context); + publish(&tree.state.dimensions, &key, &context); if let Ok(unit) = tree.root_unit() { if let Some(parameters) = &unit.parameters { for parameter_node in parameters { 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 3ba3408febd..6778c863882 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -864,6 +864,7 @@ mod tests { dimensions: Some(2), signed: false, is_2state: false, + string: false, }, ); 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 684034a3d40..67d66b43944 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -124,6 +124,7 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( dimensions: f.return_dimensions, signed: f.return_signed, is_2state: f.return_is_2state, + string: f.return_string, }, ) })); diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 87798b461f4..54768b99b7d 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -4,6 +4,7 @@ use celox_sv_syntax::{Declarations, DimensionKind, ExprId, ExprKind}; mod calls; mod direct; mod lvalues; +mod objects; #[cfg(test)] mod selected; mod strings; @@ -13,6 +14,10 @@ pub(super) use direct::{ remove_real_division_guards, ungroup, }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; +pub(super) use objects::{ + constructor as object_constructor, method as object_method, property as object_property, + receiver as object_receiver, this as object_this, +}; pub(super) use strings::{ call as string_call, method as string_method, native_string, to_string as string_operand, }; @@ -37,6 +42,12 @@ pub(super) fn expression( LValue::Ident(name) => dimensions.get(name), _ => None, }; + // `new` creates an object of the variable's class (IEEE 1800-2023 8.7). + if let Some(class) = shape.and_then(|shape| shape.class.as_deref()) + && let Some(call) = objects::constructor(tree, root, native, dimensions, class)? + { + return Ok(call); + } let value = bind_value(root, native, tree, dimensions, shape)?; // A string literal or integral value assigned to a string becomes its // bytes (IEEE 1800-2023 6.16). 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 5ea9cc6bb66..a93b9505792 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -232,6 +232,18 @@ enum Finish { Inside(Vec), /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), + /// A read of property `property` of the object handle child. + ObjectLoad { + class: String, + property: String, + }, + /// A call of method subroutine `name` with `formals` formals; the first + /// child is the receiver unless `this` passes the enclosing method's own. + MethodCall { + name: String, + formals: usize, + this: bool, + }, } enum Job { @@ -310,6 +322,11 @@ pub(in crate::ast) fn bind_value( jobs.push(Job::Enter(*inner, target, scope.clone())); continue; } + ExprKind::Literal(text) if text == "null" => { + // A handle of no object (IEEE 1800-2023 8.4). + values.push(Expr::Literal("32'h0".into())); + continue; + } ExprKind::Literal(text) => { if let Some(packed) = packed_string_literal(text) { values.push(Expr::Literal(packed)); @@ -326,9 +343,20 @@ pub(in crate::ast) fn bind_value( } ExprKind::Name(name) if !name.spelling.starts_with('$') => { let name = instances::normalize_identifier(&name.spelling); - if matches!(name.as_str(), "null" | "this" | "super") { + if name == "null" { + values.push(Expr::Literal("32'h0".into())); + continue; + } + if matches!(name.as_str(), "this" | "super") + && dimensions.get(&name).is_none() + { return Err(unsupported(format!("`{name}`"))); } + if let Some(value) = objects::unqualified_property(tree, dimensions, &name)? + { + values.push(value); + continue; + } values.push(expressions::identifier_expression( &tree.state, name, @@ -384,8 +412,37 @@ pub(in crate::ast) fn bind_value( ExprKind::Call { expression, arguments: args, - } if strings::method(*expression, native, dimensions).is_some() => { - let (op, base) = strings::method(*expression, native, dimensions) + } if objects::method(tree, *expression, native, dimensions)?.is_some() => { + let (name, formals, receiver) = + objects::method(tree, *expression, native, dimensions)? + .expect("checked by the guard"); + if args.len() > formals || args.iter().any(|arg| arg.name.is_some()) { + return Err(unsupported(format!("arguments of method `{name}`"))); + } + let mut children: Vec<_> = + receiver.into_iter().map(|id| (id, None)).collect(); + for arg in args { + let Some(value) = arg.value else { + return Err(unsupported(format!( + "omitted argument of method `{name}`" + ))); + }; + children.push((value, None)); + } + ( + Finish::MethodCall { + name, + formals, + this: receiver.is_none(), + }, + children, + ) + } + ExprKind::Call { + expression, + arguments: args, + } if strings::method(tree, *expression, native, dimensions).is_some() => { + let (op, base) = strings::method(tree, *expression, native, dimensions) .expect("checked by the guard"); if op.updates_receiver() { return Err(unsupported(format!( @@ -646,7 +703,7 @@ pub(in crate::ast) fn bind_value( ExprKind::Select { expression, dimension, - } if strings::native_string(*expression, native, dimensions) => { + } if strings::native_string(tree, *expression, native, dimensions) => { let celox_sv_syntax::DimensionKind::Index(index) = dimension.kind else { return Err(unsupported("part-select of a string")); }; @@ -655,6 +712,23 @@ pub(in crate::ast) fn bind_value( vec![(*expression, None), (index, None)], ) } + ExprKind::Member { + expression, + separator, + name, + } if separator == "." + && objects::native_class(tree, *expression, native, dimensions) + .is_some() => + { + ( + Finish::ObjectLoad { + class: objects::native_class(tree, *expression, native, dimensions) + .expect("checked by the guard"), + property: instances::normalize_identifier(&name.spelling), + }, + vec![(*expression, None)], + ) + } ExprKind::Member { .. } | ExprKind::Select { .. } => { values.push(selected_value(id, native, tree, dimensions)?); continue; @@ -819,6 +893,28 @@ pub(in crate::ast) fn bind_value( Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } + Finish::ObjectLoad { class, property } => { + let handle = operands.pop().ok_or_else(disagreement)?; + objects::load(tree, dimensions, &class, &property, handle)? + } + Finish::MethodCall { + name, + formals, + this, + } => { + let mut args: Vec> = Vec::with_capacity(formals + 1); + if this { + args.push(Some(objects::this())); + } + args.extend(operands.into_iter().map(Some)); + // Omitted trailing arguments take their defaults. + args.resize(formals + 1, None); + Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order: Vec::new(), + } + } Finish::Cast(target) => { let operand = remove_real_division_guards( guard_zero_divisions( diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs new file mode 100644 index 00000000000..109c10d885e --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -0,0 +1,254 @@ +//! Class object handles (IEEE 1800-2023 clause 8). +//! +//! A property access through a handle becomes an [`ObjectOp`] call that +//! carries the property's layout, and a method call becomes a call of the +//! method's subroutine with the handle as its first argument. Inside a +//! method, unqualified property and method names refer to `this`. + +use std::rc::Rc; + +use super::*; +use crate::ast::classes::{self, Class, THIS}; +use crate::system_functions::ObjectOp; + +/// The class `name`, laid out. +pub(in crate::ast) fn class( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + name: &str, +) -> Converted> { + classes::class(tree, name, &dimensions.const_env, &dimensions.type_aliases) +} + +/// The class of native expression `id` when it is an object handle, judged +/// before it is bound: a handle variable, or a handle property. +pub(in crate::ast) fn native_class( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Option { + if let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind + && let Some(ty) = dimensions.get(&instances::normalize_identifier(&name.spelling)) + { + return ty.class.clone(); + } + let (property, _) = property(tree, id, native, dimensions).ok()??; + property.r#type.class().map(str::to_owned) +} + +/// The class whose method is being bound, whose properties and methods +/// unqualified names may refer to. +pub(in crate::ast) fn scope_class(dimensions: &PackedDimensions) -> Option { + dimensions.get(THIS).and_then(|ty| ty.class.clone()) +} + +/// The property that native expression `id` names, `h.p` or an unqualified +/// `p` inside a method of its class, with the receiver: the expression of +/// the handle, or `None` for the enclosing method's `this`. +pub(in crate::ast) fn property( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted)>> { + let (class_name, name, receiver) = match &native.expression(ungroup(id, native)).kind { + ExprKind::Member { + expression, + separator, + name, + } if separator == "." => match native_class(tree, *expression, native, dimensions) { + Some(class) => (class, name, Some(*expression)), + None => return Ok(None), + }, + ExprKind::Name(name) => { + if dimensions + .get(&instances::normalize_identifier(&name.spelling)) + .is_some() + { + return Ok(None); + } + match scope_class(dimensions) { + Some(class) => (class, name, None), + None => return Ok(None), + } + } + _ => return Ok(None), + }; + let class = class(tree, dimensions, &class_name)?; + Ok(class + .property(&instances::normalize_identifier(&name.spelling)) + .map(|property| (property.clone(), receiver))) +} + +/// The handle of the object that `receiver` of [`property`] refers to. +pub(in crate::ast) fn receiver( + tree: &AnalysisContext<'_>, + receiver: Option, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted { + match receiver { + Some(receiver) => bind_value(receiver, native, tree, dimensions, None), + None => Ok(this()), + } +} + +/// A read of property `property` of the object `handle` of class `class`. +pub(in crate::ast) fn load( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + class_name: &str, + property: &str, + handle: Expr, +) -> Converted { + let class = class(tree, dimensions, class_name)?; + let property = class + .property(property) + .ok_or_else(|| unsupported(format!("property `{property}` of class `{class_name}`")))?; + Ok(classes::object_call( + ObjectOp::Load(property.field), + vec![handle], + )) +} + +/// The unqualified name `name` inside a method of the scope class, when it +/// names one of its properties: a read through `this`. +pub(in crate::ast) fn unqualified_property( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + name: &str, +) -> Converted> { + if dimensions.get(name).is_some() { + return Ok(None); + } + let Some(class_name) = scope_class(dimensions) else { + return Ok(None); + }; + let class = class(tree, dimensions, &class_name)?; + Ok(class.property(name).map(|property| { + classes::object_call( + ObjectOp::Load(property.field), + vec![Expr::Ident(THIS.into())], + ) + })) +} + +/// The method that native callee expression `id` names: through a handle +/// (`h.m`), `this.m`, or unqualified inside a method. Returns the method's +/// subroutine, its number of formals, and the receiver to pass as `this`, +/// `None` for the enclosing method's own `this`. +pub(in crate::ast) fn method( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted)>> { + let (class_name, method_name, receiver) = match &native.expression(ungroup(id, native)).kind { + ExprKind::Member { + expression, + separator, + name, + } if separator == "." => match native_class(tree, *expression, native, dimensions) { + Some(class) => (class, name, Some(*expression)), + None => return Ok(None), + }, + ExprKind::Name(name) if dimensions.get(THIS).is_some() => { + let normalized = instances::normalize_identifier(&name.spelling); + if dimensions.get(&normalized).is_some() { + return Ok(None); + } + match scope_class(dimensions) { + Some(class) => (class, name, None), + None => return Ok(None), + } + } + _ => return Ok(None), + }; + let class = class(tree, dimensions, &class_name)?; + let Some(method) = class.method(&instances::normalize_identifier(&method_name.spelling)) else { + return Ok(None); + }; + if method.qualifiers.is_static || method.qualifiers.is_virtual { + return Err(unsupported(format!( + "{} method `{}`", + if method.qualifiers.is_static { + "static" + } else { + "virtual" + }, + method.name + ))); + } + let formals = native + .subroutine(method.native) + .ports + .as_ref() + .map_or(0, Vec::len); + Ok(Some(( + Class::subroutine_name(&method.owner, &method.name), + formals, + receiver, + ))) +} + +/// The receiver of an unqualified method call inside a method. +pub(in crate::ast) fn this() -> Expr { + Expr::Ident(THIS.into()) +} + +/// The constructor call that `new` or `new(args)` in native expression +/// `id` makes for an object of class `class_name`, if `id` is one. +pub(in crate::ast) fn constructor( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + class_name: &str, +) -> Converted> { + let arguments: &[celox_sv_syntax::Argument] = match &native.expression(ungroup(id, native)).kind + { + ExprKind::Name(name) if name.spelling == "new" => &[], + ExprKind::Call { + expression, + arguments, + } if matches!(&native.expression(ungroup(*expression, native)).kind, + ExprKind::Name(name) if name.spelling == "new") => + { + arguments + } + _ => return Ok(None), + }; + let class = class(tree, dimensions, class_name)?; + let formals = class.method("new").map_or(0, |method| { + native + .subroutine(method.native) + .ports + .as_ref() + .map_or(0, Vec::len) + }); + let mut args = arguments + .iter() + .map(|argument| { + if argument.name.is_some() { + return Err(unsupported("named constructor argument")); + } + argument + .value + .map(|value| bind_value(value, native, tree, dimensions, None)) + .transpose() + }) + .collect::, _>>()?; + if args.len() > formals { + return Err(unsupported(format!( + "constructor of class `{class_name}` with {} arguments", + args.len() + ))); + } + args.resize(formals, None); + Ok(Some(Expr::Call { + callee: Callee::Subroutine(Class::subroutine_name(class_name, "new")), + args, + arg_order: Vec::new(), + })) +} 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 101a8b4b0ab..d8002410748 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -19,10 +19,21 @@ pub(in crate::ast) fn string_value(expr: &Expr, dimensions: &PackedDimensions) - Expr::Call { callee: Callee::Subroutine(name), .. - } => dimensions - .functions - .get(name) - .is_some_and(|function| function.return_string), + } => { + dimensions + .functions + .get(name) + .is_some_and(|function| function.return_string) + || dimensions + .function_return_types + .get(name) + .is_some_and(|metadata| metadata.string) + } + Expr::Call { + callee: Callee::Object(op), + .. + } => matches!(**op, crate::system_functions::ObjectOp::Load(field) + if field.handle == Some(crate::system_functions::HandleProperty::String)), Expr::Mux { then_expr, else_expr, @@ -114,24 +125,38 @@ pub(in crate::ast) fn operands( /// Whether native expression `id` has type `string`, judged before it is /// bound: a string variable, or a method of a string value that returns one. pub(in crate::ast) fn native_string( + tree: &AnalysisContext<'_>, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> bool { match &native.expression(ungroup(id, native)).kind { - ExprKind::Name(name) => dimensions - .get(&instances::normalize_identifier(&name.spelling)) - .is_some_and(|ty| ty.string), + ExprKind::Name(name) + if dimensions + .get(&instances::normalize_identifier(&name.spelling)) + .is_some() => + { + dimensions + .get(&instances::normalize_identifier(&name.spelling)) + .is_some_and(|ty| ty.string) + } ExprKind::Call { expression, .. } => { - method(*expression, native, dimensions).is_some_and(|(op, _)| op.returns_string()) + method(tree, *expression, native, dimensions).is_some_and(|(op, _)| op.returns_string()) } - _ => false, + // A string property of a class object. + _ => objects::property(tree, id, native, dimensions) + .ok() + .flatten() + .is_some_and(|(property, _)| { + property.field.handle == Some(crate::system_functions::HandleProperty::String) + }), } } /// The string method that native callee expression `id` names, with the /// expression it is called on. pub(in crate::ast) fn method( + tree: &AnalysisContext<'_>, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -144,7 +169,7 @@ pub(in crate::ast) fn method( else { return None; }; - if separator != "." || !native_string(*expression, native, dimensions) { + if separator != "." || !native_string(tree, *expression, native, dimensions) { return None; } let (op, _) = StringOp::method(&name.spelling)?; diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 9fd06946100..fcabc298ad0 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -97,6 +97,7 @@ pub(super) fn native_functions( &item.literals, &mut state, item, + None, ) { Ok(subroutine) => { let has_real = subroutine.return_type.as_ref().is_some_and(|ty| { diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index a8672d7c67a..efd555044b1 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -874,7 +874,9 @@ impl<'a> Elaborator<'a, '_> { value .variables .iter() - .filter(|variable| type_binding::ordinary_variable(variable, native)) + .filter(|variable| { + type_binding::ordinary_variable(variable, value.data_type, native) + }) .map(|variable| (&variable.name, variable.dimensions.as_slice())) .collect(), ), @@ -2060,6 +2062,7 @@ mod tests { dimensions: Some(2), signed: false, is_2state: false, + string: false, }; let inner = FunctionReturnMetadata { arguments: None, @@ -2068,6 +2071,7 @@ mod tests { dimensions: Some(1), signed: true, is_2state: true, + string: false, }; let dimensions = PackedDimensions { function_return_types: [ diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index 418ab612044..87149c159ab 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -109,6 +109,10 @@ pub(super) fn expr_signedness_with_return_types( callee: Callee::String(op), .. } => Some(op.result_type().1), + Expr::Call { + callee: Callee::Object(op), + .. + } => Some(op.result_type().1), Expr::Call { callee: Callee::Subroutine(name), .. 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 4839d928e56..26ba51430bd 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -59,6 +59,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - randomizable: true, real: false, string: false, + class: None, packed: function_packed_dimension_widths(&r#type.packed_ranges), unpacked: Vec::new(), signed: r#type.is_signed, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 65a8d898fc9..177764df0b8 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -466,6 +466,7 @@ fn pattern_items( VariableDimensions { real: false, string: false, + class: None, unpacked: rest.to_vec(), ..shape.clone() }, @@ -488,6 +489,7 @@ fn pattern_items( VariableDimensions { real: false, string: false, + class: None, packed: rest.to_vec(), ..shape.clone() }, @@ -502,6 +504,7 @@ fn pattern_items( randomizable: true, real: false, string: false, + class: None, packed: Vec::new(), unpacked: Vec::new(), members: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index f6dffb8f3d8..51ce1e95e31 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -66,6 +66,7 @@ fn pattern_value( let element = VariableDimensions { real: false, string: false, + class: None, unpacked: rest.to_vec(), ..shape.clone() }; diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 4a07987a791..e70aab770d1 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -107,6 +107,7 @@ fn select<'a>( let sub = Shape::Owned(Rc::new(VariableDimensions { real: false, string: false, + class: None, unpacked: rest.to_vec(), ..(*shape).clone() })); @@ -208,6 +209,7 @@ fn select<'a>( randomizable: true, real: false, string: false, + class: None, packed: rest.to_vec(), unpacked: Vec::new(), signed: shape.signed_element_depth == Some(1), @@ -244,6 +246,7 @@ fn select<'a>( randomizable: true, real: false, string: false, + class: None, packed: Vec::new(), unpacked: Vec::new(), signed: false, @@ -386,6 +389,7 @@ pub(in crate::ast) fn bind_native( let sub = Shape::Owned(Rc::new(VariableDimensions { real: false, string: false, + class: None, unpacked: rest.to_vec(), ..(*shape).clone() })); diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index f89edc1b21d..ab2176bf1ed 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -71,12 +71,17 @@ pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { randomizable: !r#type.is_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), packed: dimensions::signal_packed_dimension_widths(r#type.packed_ranges()), unpacked: unpacked_dimension_widths(r#type.unpacked_ranges()), signed: r#type.is_signed(), is_2state: matches!( r#type.kind(), - TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal | TypeKind::String + TypeKind::Bit + | TypeKind::Real + | TypeKind::Shortreal + | TypeKind::String + | TypeKind::Object ), members: r#type.members.clone(), signed_element_depth: r#type.signed_element_depth, @@ -114,6 +119,7 @@ fn int_type() -> Type { unpacked_ranges: Vec::new(), members: Vec::new(), signed_element_depth: None, + class: None, } } @@ -253,6 +259,19 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } } + /// Hide the module-scope names that the properties of `class` shadow + /// inside its methods (IEEE 1800-2023 8.5), until the scope ends. + fn enter_class_scope(&mut self, class: &classes::Class) { + for property in &class.properties { + let entry = self.take_binding(&property.name, None, 0); + self.scopes + .last_mut() + .expect("a body always has a scope") + .entries + .push(entry); + } + } + fn lookup(&self, source: &str) -> Option<&str> { for scope in self.scopes.iter().rev() { if let Some(entry) = scope @@ -469,9 +488,17 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if let Some(stmt) = self.string_character_assignment(op, nonblocking, left, right)? { return Ok(stmt); } + if let Some(stmt) = self.property_assignment(op, nonblocking, left, right)? { + return Ok(stmt); + } let (written, lhs) = self.native_lvalue(left)?; if op != "=" - && expression_binding::native_string(left, self.tree.declarations(), &self.dims) + && expression_binding::native_string( + self.tree, + left, + self.tree.declarations(), + &self.dims, + ) { return Err(unsupported(format!("operator `{op}` on a string"))); } @@ -525,7 +552,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { else { return Ok(None); }; - if !expression_binding::native_string(*expression, native, &self.dims) { + if !expression_binding::native_string(self.tree, *expression, native, &self.dims) { return Ok(None); } let celox_sv_syntax::DimensionKind::Index(index) = dimension.kind else { @@ -547,6 +574,134 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .map(Some) } + /// An assignment to a property of a class object: `h.p = v`, or `p = v` + /// inside a method of its class (IEEE 1800-2023 8.5). + fn property_assignment( + &self, + op: &str, + nonblocking: bool, + left: celox_sv_syntax::ExprId, + right: celox_sv_syntax::ExprId, + ) -> Result, AnalyzerError> { + let native = self.tree.declarations(); + let Some((property, receiver)) = + expression_binding::object_property(self.tree, left, native, &self.dims)? + else { + return Ok(None); + }; + if nonblocking { + return Err(unsupported("nonblocking assignment to a class property")); + } + let handle = expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + let target = dimensions_from_type(&property.r#type); + let bind = |right| { + expression_binding::bind_value(right, native, self.tree, &self.dims, Some(&target)) + }; + let mut value = match property.r#type.class() { + Some(class) if op == "=" => { + match expression_binding::object_constructor( + self.tree, right, native, &self.dims, class, + )? { + Some(call) => call, + None => bind(right)?, + } + } + _ if op == "=" => bind(right)?, + _ => expression_binding::value(right, native, self.tree, &self.dims)?, + }; + if property.field.handle == Some(system_functions::HandleProperty::String) { + if op != "=" { + return Err(unsupported(format!("operator `{op}` on a string"))); + } + value = expression_binding::string_operand(value, &self.dims); + } + if op != "=" { + let operator = match op.strip_suffix('=') { + Some("+") => BinaryOp::Add, + Some("-") => BinaryOp::Sub, + Some("*") => BinaryOp::Mul, + Some("/") => BinaryOp::Div, + Some("%") => BinaryOp::Mod, + Some("&") => BinaryOp::BitAnd, + Some("|") => BinaryOp::BitOr, + Some("^") => BinaryOp::BitXor, + Some("<<") | Some("<<<") => BinaryOp::Shl, + Some(">>") => BinaryOp::Shr, + Some(">>>") => BinaryOp::Sar, + _ => return Err(unsupported(format!("assignment operator `{op}`"))), + }; + value = Expr::Binary { + left: Box::new(classes::object_call( + system_functions::ObjectOp::Load(property.field), + vec![handle.clone()], + )), + op: operator, + right: Box::new(value), + }; + } + let mut store = classes::object_call( + system_functions::ObjectOp::Store(property.field), + vec![handle, value], + ); + self.rename_expr(&mut store); + Ok(Some(Stmt::Eval(store))) + } + + /// A call of a class method as a statement, `h.m(args)`, `h.m`, or an + /// unqualified `m(args)` inside a method of its class (IEEE 1800-2023 + /// 8.10). + fn method_call_statement( + &self, + root: celox_sv_syntax::ExprId, + ) -> Result, AnalyzerError> { + let native = self.tree.declarations(); + let call = match native.expression(root).kind { + celox_sv_syntax::ExprKind::Call { expression, .. } => { + if expression_binding::object_method(self.tree, expression, native, &self.dims)? + .is_none() + { + return Ok(None); + } + expression_binding::value(root, native, self.tree, &self.dims)? + } + _ => { + let Some((name, formals, receiver)) = + expression_binding::object_method(self.tree, root, native, &self.dims)? + else { + return Ok(None); + }; + let receiver = match receiver { + Some(receiver) => { + expression_binding::value(receiver, native, self.tree, &self.dims)? + } + None => expression_binding::object_this(), + }; + let mut args = vec![Some(receiver)]; + args.resize(formals + 1, None); + Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order: Vec::new(), + } + } + }; + let mut call = call; + self.rename_expr(&mut call); + let Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order, + } = call + else { + return Err(unsupported("method call statement")); + }; + Ok(Some(Stmt::Call { + name, + args, + arg_order, + })) + } + /// `string = op(string, args)`: a method that updates the string it is /// called on. fn string_update( @@ -556,6 +711,30 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { args: Vec, nonblocking: bool, ) -> Result { + let native = self.tree.declarations(); + if let Some((property, receiver)) = + expression_binding::object_property(self.tree, string, native, &self.dims)? + { + if nonblocking { + return Err(unsupported("nonblocking assignment to a class property")); + } + let handle = + expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + let receiver = (op == StringOp::Putc).then(|| { + classes::object_call( + system_functions::ObjectOp::Load(property.field), + vec![handle.clone()], + ) + }); + let value = + expression_binding::string_call(op, receiver.into_iter().chain(args).collect()); + let mut store = classes::object_call( + system_functions::ObjectOp::Store(property.field), + vec![handle, value], + ); + self.rename_expr(&mut store); + return Ok(Stmt::Eval(store)); + } let (written, lhs) = self.native_lvalue(string)?; let LValue::Ident(name) = &written else { return Err(unsupported(format!( @@ -696,7 +875,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { signals .into_iter() .zip(native.variables.iter().filter(|variable| { - type_binding::ordinary_variable(variable, self.tree.declarations()) + type_binding::ordinary_variable( + variable, + native.data_type, + self.tree.declarations(), + ) })) { // A declaration may not repeat a name of its own scope, such as @@ -834,7 +1017,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .expression(expression_binding::ungroup(root, native)) .kind && let Some((op, string)) = - expression_binding::string_method(*expression, native, &self.dims) + expression_binding::string_method(self.tree, *expression, native, &self.dims) { let (_, count) = StringOp::method(&op.to_string()).expect("a method name"); let args = arguments @@ -860,6 +1043,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { let query_root = expression_binding::call_statement_root(root, discarded, self.tree.declarations())?; + if let Some(call) = self.method_call_statement(query_root)? { + return Ok(vec![call]); + } if let celox_sv_syntax::ExprKind::Call { expression, .. } = self.tree.declarations().expression(query_root).kind && matches!( @@ -1289,6 +1475,57 @@ pub(super) fn subroutine_argument_names( names.insert(qualified.clone(), params); shapes.insert(qualified, param_shapes); } + for class in classes::item_classes(item.id, tree) { + let _constant_functions = item.enter(); + let aliases = item.type_aliases(type_aliases); + let handle = classes::handle_type(tree, &class) + .ok_or_else(|| unsupported(format!("class `{class}`")))?; + let mut constructor = false; + for native_id in classes::declared_methods(tree, &class)? { + let native = tree.declarations().subroutine(native_id); + let mut params = subroutine_param_declarations(native, tree, &item.env, &aliases)?; + if native.kind == celox_sv_syntax::SubroutineKind::Constructor { + constructor = true; + } else { + params.insert( + 0, + ( + classes::THIS.to_owned(), + ParamDirection::Input, + handle.clone(), + None, + ), + ); + } + let qualified = item.name(&classes::Class::subroutine_name( + &class, + &instances::normalize_identifier(&native.name.spelling), + )); + directions.insert( + qualified.clone(), + params.iter().map(|(_, direction, ..)| *direction).collect(), + ); + shapes.insert( + qualified.clone(), + params + .iter() + .map(|(_, _, r#type, _)| { + dimensions_from_type(&scoped_type(r#type.clone(), &item.env)) + }) + .collect(), + ); + names.insert( + qualified, + params.into_iter().map(|(name, ..)| name).collect(), + ); + } + if !constructor { + let qualified = item.name(&classes::Class::subroutine_name(&class, "new")); + directions.insert(qualified.clone(), Vec::new()); + shapes.insert(qualified.clone(), Vec::new()); + names.insert(qualified, Vec::new()); + } + } } Ok((names, shapes, directions)) } @@ -1393,6 +1630,7 @@ pub(super) fn subroutines_with_symbolic_parameters( literals, state, item, + None, ); let subroutine = match (lowered, rejected.as_deref_mut()) { (Ok(subroutine), _) => subroutine, @@ -1413,6 +1651,30 @@ pub(super) fn subroutines_with_symbolic_parameters( } subroutines.push(subroutine); } + for class in classes::item_classes(item.id, tree) { + let (item_dimensions, literals) = views.get(item); + let _constant_functions = item.enter(); + let type_aliases = item.type_aliases(module_type_aliases); + match ( + lower_class( + &class, + tree, + &item.env, + &type_aliases, + item_dimensions, + literals, + state, + item, + ), + rejected.as_deref_mut(), + ) { + (Ok(methods), _) => subroutines.extend(methods), + (Err(error), Some(rejected)) => { + rejected.insert(class, error); + } + (Err(error), None) => return Err(error), + } + } } Ok(subroutines) } @@ -1430,9 +1692,17 @@ pub(super) fn lower_subroutine( literals: &HashMap, state: &mut BodyState<'_>, item: &generate::Item, + class: Option<&classes::Class>, ) -> Converted { let native = tree.declarations().subroutine(native_id); let name = instances::normalize_identifier(&native.name.spelling); + let constructor = native.kind == celox_sv_syntax::SubroutineKind::Constructor; + let handle = class + .map(|class| { + classes::handle_type(tree, &class.name) + .ok_or_else(|| unsupported(format!("class `{}`", class.name))) + }) + .transpose()?; let params = subroutine_param_declarations(native, tree, declaration_env, type_aliases)?; let mut formal_names = HashSet::default(); if let Some((name, ..)) = params @@ -1442,6 +1712,7 @@ pub(super) fn lower_subroutine( return Err(unsupported(format!("duplicate function argument `{name}`"))); } let return_type = match native.return_type { + _ if constructor => handle.clone(), Some(id) if matches!( tree.declarations().data_type(id).kind, @@ -1480,10 +1751,14 @@ pub(super) fn lower_subroutine( "unknown native subroutine lifetime".into(), )); } - None => builder.automatic, + // Methods are automatic (IEEE 1800-2023 8.6). + None => builder.automatic || class.is_some(), }; let first_static = builder.state.statics.len(); builder.push_scope(); + if let Some(class) = class { + builder.enter_class_scope(class); + } // Defaults bind in the enclosing declaration scope, before // any formal can shadow those names (IEEE 1800-2023 13.5.3). let defaults = params @@ -1499,7 +1774,22 @@ pub(super) fn lower_subroutine( }) .collect::, _>>()?; let mut lowered_params = Vec::new(); - for ((source, direction, r#type, _), default) in params.into_iter().zip(defaults) { + // A method receives the handle of its object first, and a constructor + // returns the handle of the object it creates. + let this = handle.clone().filter(|_| !constructor).map(|handle| { + ( + classes::THIS.to_owned(), + ParamDirection::Input, + handle, + None, + ) + }); + let defaults = this + .iter() + .map(|_| None) + .chain(defaults) + .collect::>(); + for ((source, direction, r#type, _), default) in this.into_iter().chain(params).zip(defaults) { let name = builder.declare(&source, r#type.clone()); lowered_params.push(SubroutineParam { name, @@ -1515,11 +1805,18 @@ pub(super) fn lower_subroutine( default, }); } - let return_var = return_type - .as_ref() - .map(|r#type| builder.declare(&name, r#type.clone())); + let return_var = return_type.as_ref().map(|r#type| { + builder.declare( + if constructor { classes::THIS } else { &name }, + r#type.clone(), + ) + }); let parameter_locals_end = builder.state.locals.len(); - let body = builder.native_body(&native.items, &native.authored_statements)?; + let mut body = match (class, &return_var) { + (Some(class), Some(this)) if constructor => builder.constructor_prologue(class, this)?, + _ => Vec::new(), + }; + body.extend(builder.native_body(&native.items, &native.authored_statements)?); builder.pop_scope(); let statics: HashSet = builder .state @@ -1528,7 +1825,8 @@ pub(super) fn lower_subroutine( .into_iter() .map(|(name, _)| name) .collect(); - if return_var.is_some() { + // A constructor's `return;` returns the object (IEEE 1800-2023 8.7). + if return_var.is_some() && !constructor { let mut expressionless = false; for stmt in &body { stmt.walk(&mut |stmt| expressionless |= matches!(stmt, Stmt::Return(None))); @@ -1538,7 +1836,10 @@ pub(super) fn lower_subroutine( } } let mut subroutine = Subroutine { - name: item.name(&name), + name: item.name(&match class { + Some(class) => classes::Class::subroutine_name(&class.name, &name), + None => name, + }), is_task: native.kind == celox_sv_syntax::SubroutineKind::Task, automatic_locals: builder.state.locals[first_local..] .iter() @@ -1605,6 +1906,153 @@ pub(super) fn lower_subroutine( Ok(subroutine) } +impl BodyBuilder<'_, '_, '_> { + /// The statements a constructor of `class` runs before its body: create + /// the object into `this` and initialize the properties that have + /// initializers (IEEE 1800-2023 8.7, 8.8). + fn constructor_prologue(&mut self, class: &classes::Class, this: &str) -> Converted> { + let native = self.tree.declarations(); + let handles = class + .properties + .iter() + .filter_map(|property| { + property + .field + .handle + .map(|handle| (property.field.offset, handle)) + }) + .collect(); + let mut body = vec![Stmt::Assign { + lhs: LValue::Ident(this.to_owned()), + rhs: classes::object_call( + system_functions::ObjectOp::New { + class: class.id, + size: class.size, + handles, + }, + Vec::new(), + ), + nonblocking: false, + }]; + for property in &class.properties { + let Some(initializer) = property.initializer else { + continue; + }; + let mut value = match property.r#type.class() { + Some(class) => expression_binding::object_constructor( + self.tree, + initializer, + native, + &self.dims, + class, + )?, + None => None, + }; + let mut value = match value.take() { + Some(value) => value, + None => expression_binding::bind_value( + initializer, + native, + self.tree, + &self.dims, + Some(&dimensions_from_type(&property.r#type)), + )?, + }; + if property.field.handle == Some(system_functions::HandleProperty::String) { + value = expression_binding::string_operand(value, &self.dims); + } + self.rename_expr(&mut value); + body.push(Stmt::Eval(classes::object_call( + system_functions::ObjectOp::Store(property.field), + vec![Expr::Ident(this.to_owned()), value], + ))); + } + Ok(body) + } +} + +/// The methods of class `name` as subroutines, with an implicit constructor +/// when the class declares none (IEEE 1800-2023 8.7). +#[allow(clippy::too_many_arguments)] +fn lower_class( + name: &str, + tree: &AnalysisContext<'_>, + declaration_env: &HashMap, + type_aliases: &HashMap, + item_dimensions: &PackedDimensions, + literals: &HashMap, + state: &mut BodyState<'_>, + item: &generate::Item, +) -> Converted> { + let class = classes::class(tree, name, declaration_env, type_aliases)?; + if let Some(base) = &class.base + && classes::class(tree, base, declaration_env, type_aliases)? + .method("new") + .is_some() + { + return Err(unsupported("class extending a class with a constructor")); + } + let mut subroutines = Vec::new(); + let mut constructor = false; + for id in classes::declared_methods(tree, name)? { + constructor |= + tree.declarations().subroutine(id).kind == celox_sv_syntax::SubroutineKind::Constructor; + subroutines.push(lower_subroutine( + id, + tree, + declaration_env, + type_aliases, + item_dimensions, + literals, + state, + item, + Some(&class), + )?); + } + if !constructor { + let handle = classes::handle_type(tree, name) + .ok_or_else(|| unsupported(format!("class `{name}`")))?; + let mut builder = BodyBuilder::new( + tree, + item_dimensions, + state, + system_functions::Body::Subroutine, + ); + builder.automatic = true; + let first_local = builder.state.locals.len(); + builder.push_scope(); + builder.enter_class_scope(&class); + let this = builder.declare(classes::THIS, handle.clone()); + let body = builder.constructor_prologue(&class, &this)?; + builder.pop_scope(); + let mut subroutine = Subroutine { + name: item.name(&classes::Class::subroutine_name(name, "new")), + is_task: false, + automatic_locals: builder.state.locals[first_local..] + .iter() + .map(|local| local.name.clone()) + .collect(), + return_type: Some(crate::ir::Type::from_ast( + scoped_type(handle, declaration_env), + &const_functions::Environment { + constants: &*item.env, + functions: &tree.state.const_functions, + }, + )), + params: Vec::new(), + return_var: Some(this), + body, + sensitivity_body: Vec::new(), + }; + for stmt in &mut subroutine.body { + qualify_stmt(item, stmt); + substitute_stmt_constants(&tree.state, stmt, declaration_env, literals); + } + subroutines.push(subroutine); + } + Ok(subroutines) +} + /// Qualify the module-scope names of a statement for its generate scope. pub(super) fn qualify_stmt(item: &generate::Item, stmt: &mut Stmt) { stmt.visit_mut( @@ -1672,11 +2120,13 @@ pub(super) fn initial_processes_from_scope( return Err(unsupported("opaque declaration initializer")); } }; - for variable in declaration - .variables - .iter() - .filter(|variable| type_binding::ordinary_variable(variable, tree.declarations())) - { + for variable in declaration.variables.iter().filter(|variable| { + type_binding::ordinary_variable( + variable, + declaration.data_type, + tree.declarations(), + ) + }) { if let Some(value) = variable.value { assignments.push(( instances::normalize_identifier(&variable.name.spelling), diff --git a/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs b/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs index 2a50c0507af..cdfb474c9dd 100644 --- a/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs +++ b/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs @@ -45,7 +45,10 @@ pub(super) fn item(id: BodyItemId, tree: &SyntaxTree) -> Converted bool { !variable.dimensions.iter().any(|dimension|matches!(dimension.kind,celox_sv_syntax::DimensionKind::Unsized)) - && !variable.value.is_some_and(|id|matches!(&native.expression(id).kind,celox_sv_syntax::ExprKind::Name(name) if name.spelling=="new")) + && (!variable.value.is_some_and(|id|matches!(&native.expression(id).kind,celox_sv_syntax::ExprKind::Name(name) if name.spelling=="new")) + || names_class(data_type, native)) +} + +/// Whether `data_type` names a class declared in the source. +fn names_class(data_type: celox_sv_syntax::TypeId, native: &celox_sv_syntax::Declarations) -> bool { + let celox_sv_syntax::DataTypeKind::Named(segments) = &native.data_type(data_type).kind else { + return false; + }; + let [segment] = segments.as_slice() else { + return false; + }; + let name = normalize_identifier(&segment.name.spelling); + native + .classes + .iter() + .any(|class| normalize_identifier(&class.name.spelling) == name) } pub(super) fn port_direction(direction: celox_sv_syntax::Direction) -> PortDirection { @@ -71,7 +91,7 @@ pub(super) fn local_signals( }; let mut signals = Vec::new(); for variable in &declaration.variables { - if !ordinary_variable(variable, tree.declarations()) { + if !ordinary_variable(variable, declaration.data_type, tree.declarations()) { continue; } let name = normalize_identifier(&variable.name.spelling); 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 e1bde36666e..1b9de91aa9d 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -67,6 +67,10 @@ pub(in crate::ast) fn bind_in( _ => return Ok(None), }; let Some(ty) = context.type_aliases.get(&name) else { + if let Some(class) = super::super::classes::handle_type(tree, &name) { + values.push(class); + continue; + } return Ok(None); }; values.push(types::enclose_aliased_packed_type(ty.clone(), ranges)); diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index c2b3647396a..4264e6c8dd4 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -7,8 +7,8 @@ pub use crate::procedural::{ CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, SourceSpan, StmtBase, SystemTaskArg, }; pub use crate::system_functions::{ - ArrayQuery, Callee, MemoryFormat, Radix, Severity, StringOp, SystemFunction, SystemTask, - VcdTask, + ArrayQuery, Callee, HandleProperty, MemoryFormat, ObjectField, ObjectOp, Radix, Severity, + StringOp, SystemFunction, SystemTask, VcdTask, }; /// A procedural statement of the analyzed IR. @@ -619,6 +619,7 @@ pub struct Type { packed_ranges: Vec, unpacked_ranges: Vec, resolved_width: Option, + class: Option, } impl Type { @@ -626,6 +627,11 @@ impl Type { self.kind } + /// The class of an object handle type. + pub fn class(&self) -> Option<&str> { + self.class.as_deref() + } + pub fn is_signed(&self) -> bool { self.is_signed } @@ -683,6 +689,8 @@ pub enum TypeKind { Shortreal, /// IEEE 1800-2023 6.16: a dynamically sized string, held as a heap handle. String, + /// IEEE 1800-2023 8.4: a handle of a class object. + Object, Bit, Logic, Reg, @@ -696,6 +704,7 @@ impl Type { ) -> Self { let kind = r#type.kind().into(); let is_signed = r#type.is_signed(); + let class = r#type.class().map(str::to_owned); let (packed_ranges, unpacked_ranges, resolved_width) = convert_type(r#type, constants); Self { kind, @@ -703,6 +712,7 @@ impl Type { packed_ranges, unpacked_ranges, resolved_width, + class, } } } @@ -747,6 +757,7 @@ impl From for TypeKind { ast::TypeKind::Real => TypeKind::Real, ast::TypeKind::Shortreal => TypeKind::Shortreal, ast::TypeKind::String => TypeKind::String, + ast::TypeKind::Object => TypeKind::Object, ast::TypeKind::Bit => TypeKind::Bit, ast::TypeKind::Logic => TypeKind::Logic, ast::TypeKind::Reg => TypeKind::Reg, diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 4ac61e6bf56..4418f7f1ab5 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -743,6 +743,72 @@ impl fmt::Display for StringOp { } } +/// Where a property lives in an object and how it is read. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ObjectField { + /// Byte offset of the value. + pub offset: u32, + pub width: u32, + pub signed: bool, + /// What a handle property refers to. + pub handle: Option, +} + +/// What a handle property refers to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum HandleProperty { + String, + Object, +} + +impl ObjectField { + /// Bytes of the value. + pub fn bytes(self) -> u32 { + self.width.div_ceil(8) + } +} + +/// An operation on class objects (IEEE 1800-2023 clause 8). The analyzer +/// lays out each class and writes the layout into the operation, so the +/// frontend needs no class table. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ObjectOp { + /// A new object of `class` with `size` zeroed bytes, whose handle + /// properties are at the given offsets. + New { + class: u32, + size: u32, + handles: Vec<(u32, HandleProperty)>, + }, + /// Read a property of the object in the argument. + Load(ObjectField), + /// Write the second argument into a property of the object in the first. + Store(ObjectField), + /// The run-time class of the object in the argument, 0 for `null`. + ClassOf, +} + +impl ObjectOp { + /// The width and signedness of the result. + pub fn result_type(&self) -> (usize, bool) { + match self { + Self::Load(field) => (field.width as usize, field.signed), + Self::New { .. } | Self::ClassOf | Self::Store(_) => (32, false), + } + } +} + +impl fmt::Display for ObjectOp { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::New { .. } => "new", + Self::Load(_) => "property read", + Self::Store(_) => "property write", + Self::ClassOf => "class query", + }) + } +} + /// The subroutine a call expression calls. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Callee { @@ -751,6 +817,9 @@ pub enum Callee { System(SystemFunction), /// A string operation, see [`StringOp`]. String(StringOp), + /// A class object operation, see [`ObjectOp`]. + /// Boxed to keep call expressions small. + Object(Box), } impl Callee { @@ -758,14 +827,14 @@ impl Callee { pub fn subroutine(&self) -> Option<&str> { match self { Self::Subroutine(name) => Some(name), - Self::System(_) | Self::String(_) => None, + Self::System(_) | Self::String(_) | Self::Object(_) => None, } } /// The system function, if this is one. pub fn system(&self) -> Option { match self { - Self::Subroutine(_) | Self::String(_) => None, + Self::Subroutine(_) | Self::String(_) | Self::Object(_) => None, Self::System(function) => Some(*function), } } @@ -775,6 +844,7 @@ impl Callee { pub fn result_type(&self) -> Option<(usize, bool)> { match self { Self::String(op) => Some(op.result_type()), + Self::Object(op) => Some(op.result_type()), _ => self.system()?.result_type(), } } @@ -785,6 +855,7 @@ impl Callee { Self::Subroutine(name) => Self::Subroutine(rename(name)), Self::System(function) => Self::System(function), Self::String(op) => Self::String(op), + Self::Object(op) => Self::Object(op), } } @@ -802,6 +873,7 @@ impl fmt::Display for Callee { Self::Subroutine(name) => f.write_str(name), Self::System(function) => f.write_str(function.name()), Self::String(op) => op.fmt(f), + Self::Object(op) => op.fmt(f), } } } diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 1ff7f6667bb..48d1d741fe0 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -218,7 +218,7 @@ pub(crate) fn eval_const_expr_in_env( crate::ast::const_functions::eval_call(name, args, constants) } Callee::System(function) => eval_system_function(*function, args, constants), - Callee::String(_) => None, + Callee::String(_) | Callee::Object(_) => None, }, ConstExpr::Unary { op, expr: operand } => { if let Some(result) = integral_literal_from_const_expr(expr) diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index f46a39df4ad..f857274c2ca 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -943,6 +943,56 @@ pub struct VariableDeclaration { pub tokens: TokenRange, } +/// A class declaration (IEEE 1800-2023 8.3). Its body also remains an +/// unconverted body item covering the same tokens. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassDeclaration { + pub name: Name, + /// `virtual class`: abstract (8.21). + pub virtual_class: bool, + /// `interface class` (8.26). + pub interface: bool, + /// `extends` of a class, not of an interface class. + pub base: Option, + pub properties: Vec, + pub methods: Vec, + pub tokens: TokenRange, +} + +/// The class a class extends, with the arguments of its constructor when +/// they are given in the `extends` clause (8.17). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassBase { + pub data_type: TypeId, + pub arguments: Option>, +} + +/// Qualifiers of a class item (8.3, 8.18, 8.20). +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct ClassQualifiers { + pub is_static: bool, + pub is_virtual: bool, + pub is_pure: bool, + pub is_extern: bool, + pub local: bool, + pub protected: bool, + pub rand: bool, +} + +/// A property declaration of a class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassProperty { + pub qualifiers: ClassQualifiers, + pub declaration: VariableDeclaration, +} + +/// A method of a class: a function, a task or the constructor `new`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassMethod { + pub qualifiers: ClassQualifiers, + pub subroutine: SubroutineId, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub struct SubroutineId(pub(crate) usize); diff --git a/crates/celox-sv-syntax/src/parser.rs b/crates/celox-sv-syntax/src/parser.rs index ec308b3d89b..9d66cd41a71 100644 --- a/crates/celox-sv-syntax/src/parser.rs +++ b/crates/celox-sv-syntax/src/parser.rs @@ -79,6 +79,7 @@ pub struct Declarations { pub statements: Vec, pub timing_controls: Vec, pub subroutines: Vec, + pub classes: Vec, } impl Declarations { @@ -128,6 +129,8 @@ impl Declarations { statements: Vec::new(), timing_controls: Vec::new(), subroutines: Vec::new(), + class_stack: Vec::new(), + classes: Vec::new(), }; let units = parser.units()?; let source_items = parser.source_items; @@ -151,6 +154,7 @@ impl Declarations { let statements = parser.statements; let timing_controls = parser.timing_controls; let subroutines = parser.subroutines; + let classes = parser.classes; Ok(Self { source_items, expressions, @@ -173,6 +177,7 @@ impl Declarations { statements, timing_controls, subroutines, + classes, sources, tokens, units, @@ -272,6 +277,11 @@ impl Declarations { &self.statements[id.0] } + /// Every subroutine, in declaration order. + pub fn subroutine_ids(&self) -> impl Iterator + use<> { + (0..self.subroutines.len()).map(SubroutineId) + } + pub fn subroutine(&self, id: SubroutineId) -> &Subroutine { &self.subroutines[id.0] } @@ -334,6 +344,9 @@ struct Parser<'a> { statements: Vec, timing_controls: Vec, subroutines: Vec, + /// Classes whose `endclass` is still ahead, innermost last. + class_stack: Vec, + classes: Vec, } impl Parser<'_> { diff --git a/crates/celox-sv-syntax/src/parser/classes.rs b/crates/celox-sv-syntax/src/parser/classes.rs index 1e3e6f34e97..0de82cbbff9 100644 --- a/crates/celox-sv-syntax/src/parser/classes.rs +++ b/crates/celox-sv-syntax/src/parser/classes.rs @@ -1,4 +1,5 @@ -//! Class header grammar; class execution and opaque body validation are separate. +//! Class grammar: the header, properties and method qualifiers are recorded +//! as a [`ClassDeclaration`]; the body also remains an unconverted item. use super::*; impl Parser<'_> { @@ -46,12 +47,8 @@ impl Parser<'_> { } pub(super) fn class_property(&mut self) -> Result<()> { - while matches!( - self.peek(), - "static" | "protected" | "local" | "rand" | "randc" - ) { - self.at += 1; - } + let mut qualifiers = ClassQualifiers::default(); + while self.class_qualifier(&mut qualifiers) {} let qualified_const = self.peek() == "const" && matches!(self.nth(1), "protected" | "local" | "static"); let mut special_const = false; @@ -59,11 +56,11 @@ impl Parser<'_> { self.at += 1; while matches!(self.peek(), "static" | "protected" | "local") { special_const |= matches!(self.peek(), "protected" | "local"); - self.at += 1; + self.class_qualifier(&mut qualifiers); } } let declaration = self.local_declaration()?; - if special_const && let LocalDeclaration::Variables(value) = declaration { + if special_const && let LocalDeclaration::Variables(value) = &declaration { if value.variables.len() != 1 || !value.variables[0].dimensions.is_empty() { return Err( self.error("qualified const class property requires one scalar declarator") @@ -73,19 +70,91 @@ impl Parser<'_> { self.validate_constant_operators(value)?; } } + if let (Some(class), LocalDeclaration::Variables(mut declaration)) = + (self.class_stack.last_mut(), declaration) + { + declaration.constant |= qualified_const; + class.properties.push(ClassProperty { + qualifiers, + declaration, + }); + } Ok(()) } + /// Consume one property or method qualifier, recording it. + fn class_qualifier(&mut self, qualifiers: &mut ClassQualifiers) -> bool { + let flag = match self.peek() { + "static" => &mut qualifiers.is_static, + "virtual" => &mut qualifiers.is_virtual, + "pure" => &mut qualifiers.is_pure, + "extern" => &mut qualifiers.is_extern, + "local" => &mut qualifiers.local, + "protected" => &mut qualifiers.protected, + "rand" | "randc" => &mut qualifiers.rand, + _ => return false, + }; + *flag = true; + self.at += 1; + true + } + + /// The qualifiers written before the method keyword at `keyword`. + fn method_qualifiers(&self, keyword: usize) -> ClassQualifiers { + let mut qualifiers = ClassQualifiers::default(); + let mut at = keyword; + while at > 0 { + at -= 1; + let flag = match self.tokens[self.indices[at]].text.as_str() { + "static" => &mut qualifiers.is_static, + "virtual" => &mut qualifiers.is_virtual, + "pure" => &mut qualifiers.is_pure, + "extern" => &mut qualifiers.is_extern, + "local" => &mut qualifiers.local, + "protected" => &mut qualifiers.protected, + _ => break, + }; + *flag = true; + } + qualifiers + } + + /// Record subroutine `id`, which starts at token `keyword`, as a method + /// of the innermost open class. + pub(super) fn class_method(&mut self, keyword: usize, id: SubroutineId) { + let qualifiers = self.method_qualifiers(keyword); + if let Some(class) = self.class_stack.last_mut() { + class.methods.push(ClassMethod { + qualifiers, + subroutine: id, + }); + } + } + + /// Complete the innermost open class at its `endclass`. + pub(super) fn finish_class(&mut self) { + if let Some(mut class) = self.class_stack.pop() { + class.tokens = TokenRange { + start: class.tokens.start, + end: self.indices[self.at - 1] + 1, + }; + self.classes.push(class); + } + } + pub(super) fn class_header(&mut self) -> Result> { let mut items = Vec::new(); let interface = self.at > 0 && self.tokens[self.indices[self.at - 1]].text == "interface"; + let virtual_class = self.at > 0 && self.tokens[self.indices[self.at - 1]].text == "virtual"; + let start = self.indices[self.at]; self.expect("class")?; // Preserve the original parser's accepted pre-2023 class lifetime form. // IEEE 1800-2023 A.1.2 instead introduces a final specifier here. if !interface && matches!(self.peek(), "static" | "automatic") { self.at += 1; } - self.name()?; + let name = self.name()?; + let mut base = None; if self.eat("#") { let start = self.at; self.expect("(")?; @@ -102,13 +171,24 @@ impl Parser<'_> { )?); } if self.eat("extends") { - self.class_base(interface)?; + let data_type = self.class_base(interface)?; if interface { while self.eat(",") { self.class_base(true)?; } - } else if self.peek() == "(" { - self.expression_machine(super::expressions::Job::Arguments)?; + } else { + let arguments = if self.peek() == "(" { + match self.expression_machine(super::expressions::Job::Arguments)? { + super::expressions::Value::Arguments(arguments) => Some(arguments), + _ => return Err(self.error("class base constructor arguments")), + } + } else { + None + }; + base = Some(ClassBase { + data_type, + arguments, + }); } } if !interface && self.eat("implements") { @@ -118,10 +198,19 @@ impl Parser<'_> { } } self.expect(";")?; + self.class_stack.push(ClassDeclaration { + name, + virtual_class, + interface, + base, + properties: Vec::new(), + methods: Vec::new(), + tokens: TokenRange { start, end: start }, + }); Ok(items) } - fn class_base(&mut self, interface: bool) -> Result<()> { + fn class_base(&mut self, interface: bool) -> Result { let id = self.data_type()?; let datatype = &self.types[id.0]; let DataTypeKind::Named(path) = &datatype.kind else { @@ -136,6 +225,6 @@ impl Parser<'_> { { return Err(self.error("invalid class inheritance type")); } - Ok(()) + Ok(id) } } diff --git a/crates/celox-sv-syntax/src/parser/declarations.rs b/crates/celox-sv-syntax/src/parser/declarations.rs index f0912815b4e..7e2293ace91 100644 --- a/crates/celox-sv-syntax/src/parser/declarations.rs +++ b/crates/celox-sv-syntax/src/parser/declarations.rs @@ -251,7 +251,9 @@ impl Parser<'_> { && blocked_subroutines == 0 && matches!(self.peek(), "function" | "task") { + let keyword = self.at; let id = self.subroutine(prototype)?; + self.class_method(keyword, id); prototype = false; Some(BodyItemKind::Subroutine(id)) } else if root @@ -393,6 +395,9 @@ impl Parser<'_> { } self.at += 1; if closing && let Some((start, category, items)) = captured.pop() { + if category == "class" { + self.finish_class(); + } if let Some((_, _, parent)) = captured.last_mut() { parent.push(super::generate::Builder::node( self, @@ -747,6 +752,7 @@ impl Parser<'_> { let assigns = self.assign_statements.len(); let start = self.at; let id = self.subroutine(frame.prototype)?; + self.class_method(start, id); frame.unit.subroutines.push(id); frame.record(self, start, BodyItemKind::Subroutine(id))?; frame.unit.parameter_declarations.extend( @@ -1031,6 +1037,7 @@ impl Parser<'_> { let semicolon = word == ";"; self.at += 1; if closing_class { + self.finish_class(); let class = frame .classes .pop() diff --git a/crates/celox-sv-syntax/src/parser/procedures.rs b/crates/celox-sv-syntax/src/parser/procedures.rs index 882a2a152f8..7d872398e62 100644 --- a/crates/celox-sv-syntax/src/parser/procedures.rs +++ b/crates/celox-sv-syntax/src/parser/procedures.rs @@ -857,7 +857,20 @@ impl Parser<'_> { self.expect(")")?; } } else if self.peek() == "(" { - self.expression_machine(super::expressions::Job::Arguments)?; + // A class constructor call keeps its arguments (8.7). + let callee = self.node(start, ExprKind::Name(name))?; + let super::expressions::Value::Arguments(arguments) = + self.expression_machine(super::expressions::Job::Arguments)? + else { + return Err(self.error("constructor arguments")); + }; + return self.node( + start, + ExprKind::Call { + expression: callee, + arguments, + }, + ); } else if !matches!(self.peek(), ";" | "," | "") { self.expression(0)?; } diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index 84e19a5eb78..f5aea670507 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2736,3 +2736,53 @@ fn module_deferred_assertions_do_not_become_final_procedures() { } } } + +#[test] +fn class_declarations_record_names_bases_properties_and_method_qualifiers() { + for wrap in [ + ("module M;", "endmodule"), + ("package P;", "endpackage"), + ("", ""), + ] { + let syntax = parse(&format!( + "{} virtual class B; int b; pure virtual function int f(); endclass \ + class C extends B(3); static int count = 1; local logic [3:0] x, y; \ + function new(int v); x = v; endfunction \ + virtual function int f(); return x; endfunction \ + static task t(); endtask extern function void g(); endclass:C {}", + wrap.0, wrap.1 + )); + let [base, class] = &syntax.classes[..] else { + panic!("{wrap:?}: {:?}", syntax.classes) + }; + assert_eq!(base.name.spelling, "B"); + assert!(base.virtual_class && base.base.is_none()); + assert!(base.methods[0].qualifiers.is_pure && base.methods[0].qualifiers.is_virtual); + assert_eq!(class.name.spelling, "C"); + assert!(!class.virtual_class); + let extends = class.base.as_ref().unwrap(); + assert_eq!(extends.arguments.as_ref().unwrap().len(), 1); + assert_eq!(class.properties.len(), 2); + assert!(class.properties[0].qualifiers.is_static); + assert!(class.properties[1].qualifiers.local); + assert_eq!(class.properties[1].declaration.variables.len(), 2); + let methods: Vec<_> = class + .methods + .iter() + .map(|method| { + let subroutine = syntax.subroutine(method.subroutine); + (subroutine.name.spelling.as_str(), method.qualifiers) + }) + .collect(); + assert_eq!(methods.len(), 4); + assert_eq!(methods[0].0, "new"); + assert!(methods[1].1.is_virtual && !methods[1].1.is_static); + assert!(methods[2].1.is_static); + assert!(methods[3].1.is_extern); + let text = syntax.token_text(class.tokens); + assert!( + text.starts_with("class C") && text.ends_with("endclass"), + "{text}" + ); + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 47ee5ba6b55..327510f98d3 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -481,6 +481,9 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_packed_inner_index_range` | execute | icarus | 1 | Icarus 13.0 flattens an out-of-range inner index of a multidimensional packed array into the neighbouring element: a read gives a known value instead of X, and a write lands in that element; IEEE 1800-2023 7.4.6 and 11.5.1 make the select out of range. Verilator cannot check four-state values, and it truncates out-of-range packed indices. | | `sv_icarus_string_methods` | compile | icarus | 3 | Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa ("Method getc is not a string method"), and requires a constant replication count for a string ("A reference to a net or variable is not allowed in a constant expression"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases. | | `sv_icarus_unpacked_subroutine_ports` | compile | icarus | 2 | Icarus 13.0 reports that subroutine ports with unpacked dimensions are not yet supported. Verilator passes the valid case. | +| `sv_icarus_classes` | compile | icarus | 5 | Icarus 13.0 does not support extern methods ("sorry: External methods are not yet supported") or string methods called on a class property ("Can't find task itoa in class Named") or comparisons of class handles ("SORRY: Compare class handles not implemented"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods. | +| `sv_icarus_nested_class_members` | execute | icarus | 1 | Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting "sorry: Nested member path not yet supported for class properties" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case. | +| `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. | | `sv_verilator_constant_unknown_bits` | execute | verilator | 1 | Verilator 5.052 is two-state: unknown bits in constant system function arguments ($onehot(2'bx1)) are not kept unknown, so a generate condition differs from IEEE 1800-2023 20.9. Icarus agrees with the expected values. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest new file mode 100644 index 00000000000..e0a62bceba1 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -0,0 +1,231 @@ +(group class (category types)) + +(case objects_properties_and_methods + (source "class.sv" #" +module Top(output bit done); + class Counter; + int count = 5; + string label; + function new(string name); + label = name; + endfunction + function void bump(int by); + count += by; + endfunction + function int get(); + return count; + endfunction + endclass + Counter c, d; + initial begin + if (c == null) $display("null"); + c = new("first"); + c.bump(3); + d = c; + d.bump(1); + $display("count=%0d get=%0d label=%s", c.count, d.get(), c.label); + c.count = 1; + $display("after=%0d", d.count); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "null\ncount=9 get=9 label=first\nafter=1\n")) + +(case implicit_constructors_and_this + (source "class.sv" #" +module Top(output int sum, output bit done); + class Point; + int x, y = 2; + function void set(int x, int y); + this.x = x; + this.y = y; + endfunction + function int total(); + return x + this.y; + endfunction + endclass + Point p; + initial begin + p = new; + sum = p.total(); + p.set(10, 20); + sum = sum * 100 + p.total(); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq sum 230)) + +(case objects_referring_to_objects + (source "class.sv" #" +module Top(output int total, output bit done); + class Node; + int value; + Node next; + function new(int value, Node next = null); + this.value = value; + this.next = next; + endfunction + endclass + Node head, n; + initial begin + head = new(1); + head = new(2, head); + head = new(3, head); + n = head; + while (n != null) begin + total = total * 10 + n.value; + n = n.next; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq total 321)) + +(case extern_methods_and_tasks + (source "class.sv" #" +module Top(output int result, output bit done); + class Accumulator; + int total; + extern function void add(int value); + task twice(int value); + add(value); + add(value); + endtask + function new(); + total = 100; + return; + endfunction + endclass + function void Accumulator::add(int value); + total += value; + endfunction + Accumulator a; + initial begin + a = new; + a.twice(4); + a.add(1); + result = a.total; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq result 109)) + +(case objects_survive_heap_collections + (source "class.sv" #" +module Top(output int n); + class Box; + string text; + Box inner; + endclass + logic clk = 0; + always #1 clk = ~clk; + Box kept, last; + string number; + initial begin + kept = new; + kept.inner = new; + kept.inner.text = "inner"; + end + always @(posedge clk) begin + last = new; + number.itoa(n); + last.text = number; + n = n + 1; + end + initial #6000 $display("[%s] [%s] %0d", kept.inner.text, last.text, n); +endmodule +"#) + (top Top) + (run_until 6000) + (expect_output "[inner] [2999] 3000\n")) + + +(case string_methods_on_properties + (source "class.sv" #" +module Top(output bit done); + class Named; + string name; + function string greeting(); + return {"hi ", name}; + endfunction + endclass + Named n; + initial begin + n = new; + n.name.itoa(42); + n.name = {n.name, "!"}; + n.name.putc(0, "7"); + $display("[%s] %0d %s", n.name, n.name.len(), n.name.toupper()); + $display("%s %0d", {n.greeting(), "?"}, n.greeting() == "hi 72!"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "[72!] 3 72!\nhi 72!? 1\n")) + +(case derived_properties_hide_base_properties + (source "class.sv" #" +module Top(output bit done); + class Base; + int a = 1; + function int base_a(); + return a; + endfunction + endclass + class Derived extends Base; + int a = 2; + function int own_a(); + return a; + endfunction + endclass + Derived d; + Base b; + initial begin + d = new; + b = d; + d.a = 5; + $display("%0d %0d %0d %0d", d.a, b.a, d.own_a(), d.base_a()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "5 1 5 1\n")) + +(case inherited_properties_and_methods + (source "class.sv" #" +module Top(output int result, output bit same, output bit done); + class Base; + int a = 1; + function int twice(); + return a * 2; + endfunction + function int describe(); + return 10; + endfunction + endclass + class Derived extends Base; + int b = 5; + function int describe(); + return 20 + a + b; + endfunction + endclass + Derived d; + Base b; + initial begin + d = new; + d.a = 3; + b = d; + same = b == d; + result = d.twice() * 1000 + d.describe() * 10 + b.describe() / 10; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq same 1) (assert_eq result 6281)) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index cb9983f5f92..8adeddf9279 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -43,6 +43,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/string.vtest", text: include_str!("string.vtest"), }, + Group { + file: "src/sv/cases/class.vtest", + text: include_str!("class.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index 66f057ba71e..da5488b278d 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -2,6 +2,7 @@ "case_files": [ "icarus/aggregate_regressions.json", "icarus/always_comb.json", + "icarus/class.json", "icarus/generate.json", "icarus/hierarchy.json", "icarus/indexed_select.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json new file mode 100644 index 00000000000..3d6ebc71698 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -0,0 +1,164 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::derived_properties_hide_base_properties", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "upstream": [] + }, + "name": "class::extern_methods_and_tasks", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "upstream": [] + }, + "name": "class::implicit_constructors_and_this", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "upstream": [] + }, + "name": "class::inherited_properties_and_methods", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::objects_properties_and_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "upstream": [] + }, + "name": "class::objects_referring_to_objects", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting \"sorry: Nested member path not yet supported for class properties\" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_nested_class_members", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting \"sorry: Nested member path not yet supported for class properties\" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case.", + "upstream": [] + }, + "name": "class::objects_survive_heap_collections", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "upstream": [] + }, + "name": "class::string_methods_on_properties", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 8f1682978c8..446134fc726 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1749,5 +1749,60 @@ "hierarchy::named_array_parameters_keep_four_state_values" ] } + }, + { + "id": "sv_icarus_classes", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::extern_methods_and_tasks", + "class::implicit_constructors_and_this", + "class::inherited_properties_and_methods", + "class::objects_referring_to_objects", + "class::string_methods_on_properties" + ] + } + }, + { + "id": "sv_icarus_nested_class_members", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting \"sorry: Nested member path not yet supported for class properties\" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::objects_survive_heap_collections" + ] + } + }, + { + "id": "sv_verilator_class_property_string_methods", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "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.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::string_methods_on_properties" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 3656017a5ed..d976c61d989 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -7,9 +7,9 @@ "passed": 0, "rejected": 0, "unexpected_accept": 1, - "mismatch": 14, + "mismatch": 15, "emission_error": 0, - "compile_error": 107, + "compile_error": 112, "runtime_error": 7, "unsupported": 0, "ignored": 0 @@ -1223,6 +1223,54 @@ "name": "string::methods", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:5: sorry: External methods are not yet supported.\n/source_0.sv:15: syntax error\n/source_0.sv:15: error: I give up on this function definition.\n", + "expectation": "Simulation", + "name": "class::extern_methods_and_tasks", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", + "expectation": "Simulation", + "name": "class::implicit_constructors_and_this", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:6: assert: dup_expr.cc:209: failed assertion 0\nAborted (core dumped)\n", + "expectation": "Simulation", + "name": "class::objects_referring_to_objects", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "class::objects_survive_heap_collections at 145:3: expect_output: expected [91, 105, 110, 110, 101, 114, 93, 32, 91, 50, 57, 57, 57, 93, 32, 51, 48, 48, 48, 10], got [91, 32, 93, 32, 91, 50, 57, 57, 57, 93, 32, 51, 48, 48, 48, 10]", + "expectation": "Simulation", + "name": "class::objects_survive_heap_collections", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:12: error: Can't find task itoa in class Named\n/source_0.sv:12: error: Enable of unknown task ``n.name.itoa''.\n/source_0.sv:14: error: Can't find task putc in class Named\n/source_0.sv:14: error: Enable of unknown task ``n.name.putc''.\n/source_0.sv:15: sorry: Method name nesting is not supported yet.\n/source_0.sv:15: : method path: name.len\n/source_0.sv:15: error: Object celox_suite_tb.dut.n has no method \"name.len(...)\".\n/source_0.sv:15: sorry: Method name nesting is not supported yet.\n/source_0.sv:15: : method path: name.toupper\n/source_0.sv:15: error: Object celox_suite_tb.dut.n has no method \"name.toupper(...)\".\n6 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::string_methods_on_properties", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 1; see /build.log\nSORRY: Compare class handles not implemented\nerror: Code generation had 1 error(s).\n", + "expectation": "Simulation", + "name": "class::inherited_properties_and_methods", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index 3240e2ea1f1..7dde73b816f 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -9,7 +9,7 @@ "unexpected_accept": 0, "mismatch": 21, "emission_error": 0, - "compile_error": 16, + "compile_error": 17, "runtime_error": 1, "unsupported": 0, "ignored": 0 @@ -402,6 +402,14 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Error: Internal Error: /source_0.sv:12:11: ../V3Ast.h:1113: AstNode is not of expected type, but instead has type 'MEMBERSEL'\n 12 | n.name.itoa(42);\n | ^~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n", + "expectation": "Simulation", + "name": "class::string_methods_on_properties", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index 8e66059cf84..5f3051a715c 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -1,6 +1,7 @@ { "case_files": [ "verilator/always_comb.json", + "verilator/class.json", "verilator/generate.json", "verilator/hierarchy.json", "verilator/indexed_select.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json new file mode 100644 index 00000000000..ddf65590565 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -0,0 +1,104 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::derived_properties_hide_base_properties", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::extern_methods_and_tasks", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::implicit_constructors_and_this", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::inherited_properties_and_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::objects_properties_and_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::objects_referring_to_objects", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::objects_survive_heap_collections", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "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.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_class_property_string_methods", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "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.", + "upstream": [] + }, + "name": "class::string_methods_on_properties", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4a6c96beffd..1992acceb2a 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -218,6 +218,7 @@ impl HostBoundary for Simulator { fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { // The time slot is over: no kernel runs, and its updates are in // state memory. + self.take_heap_fault().map_err(Halt::Error)?; self.heap_safepoint(); self.start_sv_vcd(timestamp).map_err(|error| { Halt::Error(RuntimeErrorCode::Runtime { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 07e2c81f497..9651f481f31 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -124,7 +124,7 @@ mod host { pub struct Simulator { pub(crate) backend: B, /// Byte offsets of every handle slot in state memory. - pub(super) handle_slots: std::sync::OnceLock>, + pub(super) handle_slots: std::sync::OnceLock>, /// Set while handles live outside state memory, where no collection /// may run: between the polls of concurrent testbench processes. pub(crate) heap_safepoints_blocked: bool, @@ -1679,7 +1679,7 @@ mod host { pub fn tick(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { let result = self.tick_unit(event); self.heap_safepoint(); - result + result.and(self.take_heap_fault()) } fn tick_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -1992,7 +1992,7 @@ mod host { pub fn tick_events(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { let result = self.tick_events_unit(events); self.heap_safepoint(); - result + result.and(self.take_heap_fault()) } fn tick_events_unit(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { diff --git a/crates/celox/src/simulator/heap.rs b/crates/celox/src/simulator/heap.rs index 47342e5f9fb..162e1d25644 100644 --- a/crates/celox/src/simulator/heap.rs +++ b/crates/celox/src/simulator/heap.rs @@ -2,22 +2,25 @@ use std::sync::Arc; -use celox_heap::{HANDLE_BYTES, Handle}; +use celox_heap::{HANDLE_BYTES, Handle, HandleKind, Root}; use super::host::Simulator; use crate::backend::SimBackend; impl Simulator { - /// Byte offsets of every handle slot in the stable and working regions. - pub(crate) fn handle_slots(&self) -> Arc<[usize]> { + /// Byte offsets of every handle slot in the stable and working regions, + /// with what its handles refer to, sorted by offset. + pub(crate) fn handle_slots(&self) -> Arc<[(usize, HandleKind)]> { self.handle_slots .get_or_init(|| { let layout = self.backend.layout(); let mut slots = Vec::new(); for (address, metadata) in &self.program.design.state_objects { - if !metadata.value_kind.is_handle() { - continue; - } + let kind = match metadata.value_kind { + celox_design::ValueKind::Bits => continue, + celox_design::ValueKind::StrRef => HandleKind::String, + celox_design::ValueKind::ObjRef => HandleKind::Object, + }; debug_assert!( !layout.sparse_offsets.contains_key(address), "handle slots are never sparse FF targets" @@ -30,22 +33,23 @@ impl Simulator { .map(|offset| layout.working_base_offset + offset), ); for base in bases { - slots.extend((0..elements).map(|index| base + index * HANDLE_BYTES)); + slots + .extend((0..elements).map(|index| (base + index * HANDLE_BYTES, kind))); } } - slots.sort_unstable(); + slots.sort_unstable_by_key(|&(offset, _)| offset); slots.into() }) .clone() } /// The handles held by the handle slots of state memory. - pub(crate) fn handle_roots(&self) -> Vec { + pub(crate) fn handle_roots(&self) -> Vec { let (memory, len) = self.backend.memory_as_ptr(); self.handle_slots() .iter() - .filter(|&&offset| offset + HANDLE_BYTES <= len) - .map(|&offset| { + .filter(|&&(offset, _)| offset + HANDLE_BYTES <= len) + .map(|&(offset, kind)| { let mut bytes = [0; HANDLE_BYTES]; // SAFETY: the slot lies inside the `len` bytes of the image. unsafe { @@ -55,11 +59,26 @@ impl Simulator { HANDLE_BYTES, ); } - Handle::from_le_bytes(bytes) + Root { + kind, + handle: Handle::from_le_bytes(bytes), + } }) .collect() } + /// The fault a heap operation of compiled code recorded since the last + /// check, as a runtime error. + pub(crate) fn take_heap_fault(&mut self) -> Result<(), crate::RuntimeErrorCode> { + match self.backend.heap_mut().take_fault() { + None => Ok(()), + Some(fault) => Err(crate::RuntimeErrorCode::Runtime { + message: fault.to_string(), + signals: Vec::new(), + }), + } + } + /// Collect the heap between time slots, if enough was allocated. Runtime /// events still in the backend's buffer are taken first, which reads /// their string arguments. @@ -74,7 +93,7 @@ impl Simulator { /// Collect the heap if enough was allocated since the last collection. /// State memory and `extra_roots` must hold every live handle: the /// caller runs this only where no copy of a handle is anywhere else. - pub(crate) fn maybe_collect_heap(&mut self, extra_roots: impl IntoIterator) { + pub(crate) fn maybe_collect_heap(&mut self, extra_roots: impl IntoIterator) { if !self.backend.heap().should_collect() { return; } diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 706e8dbf34a..50b7218fed1 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -44,6 +44,9 @@ pub enum StateError { /// that matching code keeps compiling. #[error("state files do not support dynamic testbench strings; use a checkpoint instead")] TestbenchStrings, + /// A variable holds a class object, which state files cannot record. + #[error("state files do not record class objects; `{0}` holds one, use a checkpoint instead")] + Objects(String), } /// Differences between a state file and the design it is loaded into. @@ -110,6 +113,8 @@ struct NamedObject { /// Whether the elements are string handles, which a file records as /// references to its strings section. strings: bool, + /// Whether the elements are object handles, which a file cannot record. + objects: bool, } /// The state objects of a built design, with the paths and roles that state @@ -126,7 +131,9 @@ pub struct StateSchema { impl StateSchema { /// Save the value of every state object of `backend` as last evaluated. - pub fn capture(&self, backend: &B) -> StateFile { + /// + /// Fails if a variable holds a class object. + pub fn capture(&self, backend: &B) -> Result { let heap = backend.heap(); let mut strings = Vec::new(); let mut file_ids: HashMap = HashMap::default(); @@ -160,6 +167,9 @@ impl StateSchema { // Number strings by first use in path order, so equal states save // equal files. for (object, named) in objects.iter_mut().zip(&self.objects) { + if named.objects && object.value.iter().any(|&byte| byte != 0) { + return Err(StateError::Objects(named.path.clone())); + } if !named.strings { continue; } @@ -182,12 +192,12 @@ impl StateSchema { element.copy_from_slice(&id.to_le_bytes()); } } - StateFile { + Ok(StateFile { four_state: self.four_state, objects, schedule: None, strings, - } + }) } /// Write the state saved in `file` into `backend`, matching objects by @@ -301,7 +311,7 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - Ok(self.state_schema().capture(&self.backend)) + self.state_schema().capture(&self.backend) } /// Load the state saved in `file`, matching objects by path. @@ -400,6 +410,9 @@ impl Simulator { strings: self.program.design.state_objects.get(address).is_some_and( |metadata| metadata.value_kind == celox_design::ValueKind::StrRef, ), + objects: self.program.design.state_objects.get(address).is_some_and( + |metadata| metadata.value_kind == celox_design::ValueKind::ObjRef, + ), }); } index = end; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 68c261446c6..037d4ad61ac 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -302,15 +302,23 @@ fn collect_testbench_heap( return; } let slots = sim.handle_slots(); - let saved_roots: Vec = private_signals + let saved_roots: Vec = private_signals .iter() .enumerate() - .filter(|(_, signal)| slots.binary_search(&signal.offset).is_ok()) - .flat_map(|(index, signal)| { + .filter_map(|(index, signal)| { + let slot = slots + .binary_search_by_key(&signal.offset, |&(offset, _)| offset) + .ok()?; + Some((index, signal, slots[slot].1)) + }) + .flat_map(|(index, signal, kind)| { let elements = signal.width / celox_design::HANDLE_WIDTH; locals.iter().flat_map(move |process| { let digits = process[index].0.to_u32_digits(); - (0..elements).map(move |element| digits.get(element).copied().unwrap_or(0)) + (0..elements).map(move |element| celox_heap::Root { + kind, + handle: digits.get(element).copied().unwrap_or(0), + }) }) }) .collect(); diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs new file mode 100644 index 00000000000..6b821e0d979 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -0,0 +1,89 @@ +//! Class objects, properties, and methods (IEEE 1800-2023 clause 8). + +use super::*; + +sv_backends! { + fn class_objects_properties_and_methods(sim) { @case "class::objects_properties_and_methods"; } +} + +sv_backends! { + fn class_implicit_constructors_and_this(sim) { @case "class::implicit_constructors_and_this"; } + fn class_objects_referring_to_objects(sim) { @case "class::objects_referring_to_objects"; } + fn class_extern_methods_and_tasks(sim) { @case "class::extern_methods_and_tasks"; } + fn class_objects_survive_heap_collections(sim) { @case "class::objects_survive_heap_collections"; } + fn class_string_methods_on_properties(sim) { @case "class::string_methods_on_properties"; } + fn class_derived_properties_hide_base_properties(sim) { @case "class::derived_properties_hide_base_properties"; } + fn class_inherited_properties_and_methods(sim) { @case "class::inherited_properties_and_methods"; } +} + +sv_backends! { + fn null_dereferences_are_runtime_errors(sim) { + @setup { + let source = r#"module Top(output int value, output bit done); + class C; + int x; + endclass + C c; + initial begin + value = c.x; + done = 1; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("null.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("null object handle"), "{error}"); + } + + fn checkpoints_keep_objects_that_state_files_cannot_record(sim) { + @setup { + let source = r#"module Top(output int value); + timeunit 1ps / 1ps; + class C; + int x; + endclass + C c; + initial begin + c = new; + c.x = 7; + #10 value = c.x; + #10 c.x = 8; + #10 value = c.x; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("checkpoint.sv"))], "Top"); + sim.run_until(5).unwrap(); + let error = sim.save_state().unwrap_err().to_string(); + assert!(error.contains("class objects"), "{error}"); + let checkpoint = sim.checkpoint().unwrap(); + let value = sim.signal("value"); + sim.run_until(40).unwrap(); + assert_eq!(sim.get(value), BigUint::from(8u8)); + sim.restore(&checkpoint).unwrap(); + sim.run_until(15).unwrap(); + assert_eq!(sim.get(value), BigUint::from(7u8)); + sim.run_until(40).unwrap(); + assert_eq!(sim.get(value), BigUint::from(8u8)); + } +} + +#[test] +fn four_state_properties_are_rejected() { + let source = r#" + module Top; + class C; + logic [3:0] x; + endclass + C c; + initial c = new; + endmodule + "#; + let Err(error) = + Simulator::from_sv_sources(vec![(source, Path::new("class.sv"))], "Top").build_cranelift() + else { + panic!("a 4-state class property is unsupported"); + }; + let error = error.to_string(); + assert!(error.contains("4-state class property"), "{error}"); +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 744181760b5..52af4da8702 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -102,6 +102,8 @@ macro_rules! sv_backends { mod always_comb; #[path = "frontends/systemverilog/binary_file_io.rs"] mod binary_file_io; +#[path = "frontends/systemverilog/class.rs"] +mod class; #[path = "frontends/systemverilog/edges.rs"] mod edges; #[path = "frontends/systemverilog/file_core.rs"] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 86daa04776e..fd474d307ab 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -30,6 +30,7 @@ synthesis and is tested at the design level. | 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'{...}`) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | +| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and non-virtual methods from a base class without a constructor. See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -127,7 +128,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Classes. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. +- Class features beyond those [listed](#classes): constructors of base classes and `super`, virtual method calls, static properties and methods, `C::` scope resolution, parameterized classes, shallow copies (`new h`), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. - Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. @@ -219,6 +220,21 @@ Not yet supported: `$sformat` / `$sformatf`, `atoreal` / `realtoa`, string arguments of `$value$plusargs`, file I/O and DPI-C, and string values in VPI, VCD output and the TypeScript API. +### Classes {#classes} + +A class variable holds a handle of an object in the simulator's heap, `null` +until a constructor runs. Like a string, a handle costs the same as a 32-bit +integer to copy or compare; reading or writing a property and creating an +object call into the runtime. Objects that no variable or other object refers +to are collected between time slots and after each `tick`. A method is called +with the object it was called on, so it can be a function or a task, and +calls are bound to the method of the variable's class (IEEE 1800-2023 8.6). +Reading or writing a property or calling a method through `null` is a runtime +error. + +Checkpoints keep objects. State files record strings but not objects, so +saving a state file fails while any variable holds an object. + ### Out-of-range selects A run-time select that reaches past either end of a diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 8292e7e53cb..7ffd559f3bb 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -92,7 +92,7 @@ ports, types, statements or system functions before porting a design. Common reasons a design needs changes are: -- Class-based verification and concurrent assertions. +- Class-based verification beyond [simple classes](./systemverilog-reference#classes) and concurrent assertions. - `fork` / `join`, named events, intra-assignment timing such as `a = #1 b` and `iff` in event controls ([#1444](https://github.com/celox-sim/celox/issues/1444)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 18f18c73a24..9ad661af8e8 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -28,6 +28,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`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'{...}`) | +| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、コンストラクタのない基底クラスからのプロパティと非 virtual メソッドの継承。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -117,7 +118,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- クラス。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:基底クラスのコンストラクタと `super`、virtual メソッドの呼び出し、static プロパティとメソッド、`C::` によるスコープ解決、パラメータ付きクラス、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -164,6 +165,12 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 未対応:`$sformat` / `$sformatf`、`atoreal` / `realtoa`、`$value$plusargs`・ファイル I/O・DPI-C の文字列引数、VPI・VCD 出力・TypeScript API での文字列値。 +### クラス {#classes} + +クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。 + +チェックポイントはオブジェクトを保持します。状態ファイルは文字列を記録しますがオブジェクトは記録しないため、オブジェクトを持つ変数があると状態ファイルの保存は失敗します。 + ### インスタンス配列の要素 要素は宣言どおりの添字で参照します。`Child u[3:2](...)` の diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 085c228482c..0dca57887a3 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -87,7 +87,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 デザインの変更が必要になりやすいのは、次の機能です。 -- クラスを使う検証、並行アサーション。 +- [単純なクラス](./systemverilog-reference#classes)を超えるクラスを使う検証、並行アサーション。 - `fork` / `join`、named event、`a = #1 b` のような代入内のタイミング制御、 イベント制御の `iff`([#1444](https://github.com/celox-sim/celox/issues/1444))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。