From 390259050275db83bbf6a7f5e981bc0b2cb3f0ae Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 21:21:25 +0900 Subject: [PATCH] feat(sv)!: support dynamic arrays queues and associative arrays ## Summary SystemVerilog declarations such as `int values[]`, `int queue[$]` and `int lookup[string]` now bind to runtime container values. Preserve `new[]` operands in declaration initializers and lower element accesses, value copies, queue methods, associative traversal, equality and foreach through the heap ABI. Track the receiver and traversal output as process writes, preserve X/Z, and keep string and object elements reachable during collection and checkpoint restore. The initial subset is one-dimensional containers with packed elements up to 64 bits, strings or class handles, and integral/string associative keys. The reference guide documents unsupported forms. Shared cases cover ordinary and bounded queues, resize/copy/default behavior, signed and string keys, string-key foreach, invalid indices, equality and unchanged-value event waits. Celox API tests cover serialized checkpoints and negative allocation sizes. ## Validation - `cargo test --locked -p celox --features systemverilog,cranelift,wasm-runtime --test systemverilog`: 5,516 passed, 20 existing ignores. - `cargo test --locked -p celox --features systemverilog,cranelift,wasm-runtime --test systemverilog containers::`: 88 passed, including 10 new nested-argument regressions. - `cargo test --locked -p celox-sv-analyzer -p celox-sv-syntax -p celox-frontend-sv --lib`: 829 analyzer, 131 syntax and 7 frontend tests passed. - Clippy passed for the affected frontend, syntax, analyzer, Celox and shared-suite crates with all targets and native/Cranelift/WASM features. - NAPI rebuilt successfully; its 34 unit tests and 435 JavaScript tests passed. - `cargo fmt --all -- --check` and `git diff --check` passed. External verification was run with `verify-sv-verilator`, `verify-sv-icarus` and `verify-sv-xezim` using focused `containers::` filters. The pinned xezim is 0.11.3 (flake revision `058f2bba58648452e5799d17572356ebcae7d163`). Reproduce its 16-case run with: ```sh nix develop .#xezim -c cargo run --locked -p celox-test-suite --features xezim --bin verify-sv-xezim -- --filter containers:: ``` These independent checks are not fully passing: | Tool | Passed | Compile errors | Mismatches | Unsupported four-state cases | | --- | ---: | ---: | ---: | ---: | | Verilator 5.052 | 7 | 4 | 2 | 3 | | Icarus 13.0 | 3 | 12 | 1 | 0 | | xezim 0.11.3 | 6 | 0 | 10 | 0 | xezim compiles all 16 cases. It independently passes signed and string associative-key traversal, integer/string foreach, string elements across GC, and unchanged-value event waits. The remaining assertion differences are: | Case in `containers::` | Expected | xezim | | --- | ---: | ---: | | `dynamic_resize_and_copy` | `0xff` | `0xef` | | `queue_methods` | `0xff` | `0xdf` | | `declaration_initializers_and_locals` | `1` | `0` | | `four_state_elements_and_indices` | `0xff` | `0xcf` | | `bounded_queue_and_equality` | `0xff` | `0xcc` | | `four_state_container_equality` | `0xf` | `0xd` | | `object_elements_keep_handle_semantics` | `0xf` | `0x7` | | `runtime_queries_and_traversal_conversion` | `0xff` | `0xd7` | | `queue_argument_side_effects` | `0xff` | `0x38` | | `queue_argument_four_state` | `1` | `0` | Standalone diagnostic probes observe retained out-of-range stores, untruncated bounded-queue assignment, zero/default mismatches for four-state missing entries, logical array equality returning 0 with X/Z operands, `first(byte_index)` returning 1 after truncation, and `$dimensions` returning 2 for a dynamic array of class handles. Queue-append and declaration-initializer results vary with hierarchy or instrumentation and remain unresolved comparisons. Expectations were checked against IEEE 1800-2023 7.4.5/Table 7-1, 7.5.1, 7.9.8, 7.10.1/7.10.5, 11.2.2/11.4.5 and 20.7. The runtime-query fixture uses `bit [31:0]` elements so its zero-default assertions describe a two-state type; its assertions were preserved. The revised case passes Celox's backend matrix, while both Verilator and Icarus still reject its narrowed traversal call or other unsupported syntax. Verilator differs on signed associative-key traversal/foreach and rejects or fails to generate C++ for queue `$+1`, mixed-bound queue equality, aggregate event expressions and narrowed traversal outputs. Icarus lacks the required associative-array support and has other compile failures; unchanged-value event waits also differ. Four-state cases remain enabled in Celox's backend matrix. The external-comparison failures require review before this stack is merge-ready; no retained verification JSON or exclusion manifests were refreshed. ## P2 review correction Evaluate container indices and element arguments before reading the receiver's immutable heap handle and deriving the append position. For example, `q = {1, 2}; q.push_back(q.pop_front());` now leaves `{2, 1}` and preserves the inner mutation. The same ordering applies to front insertion, indexed insert/delete and indexed reads. IEEE 1800-2023 7.10.2 and 13.5 describe the queue operations and input argument passing; the tests do not depend on an ordering between multiple side-effecting arguments. Two portable regression cases cover integer, bounded, string and four-state queues. All 10 backend registrations failed before the fix and pass afterward; the complete focused container matrix passes 88 tests. Frontend unit tests, affected-crate Clippy, formatting, the NAPI rebuild and 435 JS tests also pass. Icarus passes both new cases; Verilator passes the ordinary case and its adapter cannot execute the four-state case. xezim compiles both but differs on both. An isolated xezim probe produces `{2, 2, 1}` after the nested push/pop example, and also retains an extra element for front/insert and string variants. External totals above combine the previously validated 14 cases with these two new cases. Existing external discrepancies remain unresolved. ## sv-tests expectation review Update exactly 22 retained `fail -> pass` verdicts for the new container support: nine associative-array cases, dynamic-array `new[]` and the queue declaration case, each in both state modes. Review the pinned upstream sources and official logs from CI run 40323383639: eight cases execute and pass simulation assertions; three cases pass elaboration only. Document those coverage boundaries in the conformance README. The byte-key traversal case already truncates its key at insertion and correctly returns 1 for its equally wide output. Reconcile all 3,300 artifact verdicts with the updated expectations and official runner logs: no remaining differences and no passing-case regression. The pinned revision is unchanged; 1,201 cases pass in 2state and 1,212 in 4state. The five runner aggregation/schema tests and `git diff --check` pass. This expectation-only follow-up reuses the reviewed CI execution evidence; it does not rerun the full upstream corpus locally or change simulator code, external-comparison exclusions or retained verification JSON. BREAKING CHANGE: the public analyzer `ObjectOp` enum gains a `Container` variant; consumers with exhaustive matches must handle it. Change-Id: I864df12b30e1b7154418b3017341c898742f997d --- conformance/sv-tests/README.md | 14 + conformance/sv-tests/expected.tsv | 44 +- crates/celox-frontend-sv/src/lowering.rs | 17 + crates/celox-frontend-sv/src/lowering/ff.rs | 20 +- .../src/lowering/ff/containers.rs | 414 ++++++++++ .../src/lowering/ff/objects.rs | 2 + .../src/lowering/procedural.rs | 20 +- crates/celox-sv-analyzer/src/ast.rs | 17 +- .../src/ast/array_compatibility.rs | 1 + .../src/ast/bound_patterns.rs | 3 + crates/celox-sv-analyzer/src/ast/case.rs | 6 +- crates/celox-sv-analyzer/src/ast/classes.rs | 9 +- .../src/ast/classes/specializations.rs | 4 +- .../celox-sv-analyzer/src/ast/containers.rs | 729 ++++++++++++++++++ .../celox-sv-analyzer/src/ast/declarations.rs | 3 + .../celox-sv-analyzer/src/ast/dimensions.rs | 11 +- .../src/ast/dimensions/discovery.rs | 7 +- .../src/ast/expression_binding.rs | 3 + .../src/ast/expression_binding/direct.rs | 4 + .../src/ast/expression_binding/objects.rs | 10 +- .../src/ast/expression_binding/strings.rs | 17 +- .../src/ast/generate/memo/sites.rs | 2 + .../src/ast/packed_structs/selects.rs | 1 + .../src/ast/parameters/skipped.rs | 3 + crates/celox-sv-analyzer/src/ast/patterns.rs | 3 + .../src/ast/patterns/binding.rs | 4 + .../celox-sv-analyzer/src/ast/procedural.rs | 93 ++- .../src/ast/procedural/control.rs | 2 +- .../src/ast/procedural/foreach.rs | 52 +- .../celox-sv-analyzer/src/ast/type_binding.rs | 32 +- .../src/ast/type_binding/binding.rs | 2 +- .../src/ast/type_binding/subroutines.rs | 3 + crates/celox-sv-analyzer/src/ast/types.rs | 10 +- crates/celox-sv-analyzer/src/ir.rs | 4 +- .../celox-sv-analyzer/src/system_functions.rs | 88 +++ .../celox-sv-syntax/src/parser/expressions.rs | 9 + .../celox-sv-syntax/src/parser/procedures.rs | 30 +- .../src/sv/cases/containers.vtest | 388 ++++++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + crates/celox/src/simulator/state_file.rs | 4 +- .../frontends/systemverilog/containers.rs | 60 ++ crates/celox/tests/systemverilog.rs | 3 + docs/guide/systemverilog-reference.md | 40 + 43 files changed, 2104 insertions(+), 88 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/ff/containers.rs create mode 100644 crates/celox-sv-analyzer/src/ast/containers.rs create mode 100644 crates/celox-test-suite/src/sv/cases/containers.vtest create mode 100644 crates/celox/tests/frontends/systemverilog/containers.rs diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index a9a6d48c360..aeb7df2da7b 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -131,6 +131,20 @@ class with constraints is rejected. `18.5.8.1--foreach-iterative-constraints_0`, static random properties. Full official runs at the pinned revision report 1112 passing cases in 2state and 1123 in 4state, with no passing case regressing. +Dynamic container support updates 22 rows: both state modes of eleven chapter 7 +cases change from fail to pass. Eight cases execute simulations and their +`:assert:` output passes: associative assignment, `exists`, `first`, `last`, +`next`, `prev`, traversal with a byte key, and dynamic-array `new[]`. The traversal +case declares both its key and output as `byte`; the stored key is already +truncated before traversal, so returning 1 is correct. The integral-key and +string-key associative declaration cases and `queues/basic` pass elaboration +only; they do not establish runtime behavior. Queue mutations and other container +behavior are exercised by the shared container simulation cases. +The [reviewed CI run](https://github.com/celox-sim/celox/actions/runs/40323383639) +contains 3,300 case/mode verdicts at the pinned revision. These are its only +changed rows, with no passing case regressing: 1,201 cases pass in 2state and +1,212 in 4state. Only these reviewed expectations are updated. + ## Running locally Use the locked development shell and install the pinned [`requirements.txt`](requirements.txt) in a Python environment. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 3a8ec649374..c44b2cb2f33 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1259,12 +1259,12 @@ chapter-7/arrays/associative/alloc.sv 2state fail chapter-7/arrays/associative/alloc.sv 4state fail chapter-7/arrays/associative/arguments.sv 2state fail chapter-7/arrays/associative/arguments.sv 4state fail -chapter-7/arrays/associative/assignment.sv 2state fail -chapter-7/arrays/associative/assignment.sv 4state fail +chapter-7/arrays/associative/assignment.sv 2state pass +chapter-7/arrays/associative/assignment.sv 4state pass chapter-7/arrays/associative/class.sv 2state fail chapter-7/arrays/associative/class.sv 4state fail -chapter-7/arrays/associative/integral.sv 2state fail -chapter-7/arrays/associative/integral.sv 4state fail +chapter-7/arrays/associative/integral.sv 2state pass +chapter-7/arrays/associative/integral.sv 4state pass chapter-7/arrays/associative/literals.sv 2state fail chapter-7/arrays/associative/literals.sv 4state fail chapter-7/arrays/associative/locator-methods/find-first-index.sv 2state fail @@ -1289,36 +1289,36 @@ chapter-7/arrays/associative/locator-methods/unique.sv 2state fail chapter-7/arrays/associative/locator-methods/unique.sv 4state fail chapter-7/arrays/associative/methods/delete.sv 2state fail chapter-7/arrays/associative/methods/delete.sv 4state fail -chapter-7/arrays/associative/methods/exists.sv 2state fail -chapter-7/arrays/associative/methods/exists.sv 4state fail -chapter-7/arrays/associative/methods/first.sv 2state fail -chapter-7/arrays/associative/methods/first.sv 4state fail -chapter-7/arrays/associative/methods/last.sv 2state fail -chapter-7/arrays/associative/methods/last.sv 4state fail -chapter-7/arrays/associative/methods/next.sv 2state fail -chapter-7/arrays/associative/methods/next.sv 4state fail +chapter-7/arrays/associative/methods/exists.sv 2state pass +chapter-7/arrays/associative/methods/exists.sv 4state pass +chapter-7/arrays/associative/methods/first.sv 2state pass +chapter-7/arrays/associative/methods/first.sv 4state pass +chapter-7/arrays/associative/methods/last.sv 2state pass +chapter-7/arrays/associative/methods/last.sv 4state pass +chapter-7/arrays/associative/methods/next.sv 2state pass +chapter-7/arrays/associative/methods/next.sv 4state pass chapter-7/arrays/associative/methods/num.sv 2state fail chapter-7/arrays/associative/methods/num.sv 4state fail -chapter-7/arrays/associative/methods/prev.sv 2state fail -chapter-7/arrays/associative/methods/prev.sv 4state fail +chapter-7/arrays/associative/methods/prev.sv 2state pass +chapter-7/arrays/associative/methods/prev.sv 4state pass chapter-7/arrays/associative/methods/size.sv 2state fail chapter-7/arrays/associative/methods/size.sv 4state fail -chapter-7/arrays/associative/methods/traversal.sv 2state fail -chapter-7/arrays/associative/methods/traversal.sv 4state fail +chapter-7/arrays/associative/methods/traversal.sv 2state pass +chapter-7/arrays/associative/methods/traversal.sv 4state pass chapter-7/arrays/associative/nonexistent.sv 2state fail chapter-7/arrays/associative/nonexistent.sv 4state fail chapter-7/arrays/associative/other.sv 2state fail chapter-7/arrays/associative/other.sv 4state fail -chapter-7/arrays/associative/string.sv 2state fail -chapter-7/arrays/associative/string.sv 4state fail +chapter-7/arrays/associative/string.sv 2state pass +chapter-7/arrays/associative/string.sv 4state pass chapter-7/arrays/associative/wildcard.sv 2state fail chapter-7/arrays/associative/wildcard.sv 4state fail chapter-7/arrays/dynamic/basic.sv 2state pass chapter-7/arrays/dynamic/basic.sv 4state pass chapter-7/arrays/dynamic/op-delete.sv 2state fail chapter-7/arrays/dynamic/op-delete.sv 4state fail -chapter-7/arrays/dynamic/op-new.sv 2state fail -chapter-7/arrays/dynamic/op-new.sv 4state fail +chapter-7/arrays/dynamic/op-new.sv 2state pass +chapter-7/arrays/dynamic/op-new.sv 4state pass chapter-7/arrays/dynamic/op-size.sv 2state fail chapter-7/arrays/dynamic/op-size.sv 4state fail chapter-7/arrays/multidimensional/basic.sv 2state pass @@ -1407,8 +1407,8 @@ chapter-7/memories/basic.sv 2state pass chapter-7/memories/basic.sv 4state pass chapter-7/memories/read-write.sv 2state pass chapter-7/memories/read-write.sv 4state pass -chapter-7/queues/basic.sv 2state fail -chapter-7/queues/basic.sv 4state fail +chapter-7/queues/basic.sv 2state pass +chapter-7/queues/basic.sv 4state pass chapter-7/queues/bounded.sv 2state fail chapter-7/queues/bounded.sv 4state fail chapter-7/queues/delete.sv 2state fail diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 9997aab84cf..d7029c83308 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1446,6 +1446,13 @@ fn kernel_written_names( }); } while let Some((callee, args)) = calls.pop() { + if let sv::ir::Callee::Object(op) = &callee { + names.extend( + procedural::written_object_arguments(op, &args) + .iter() + .map(|lhs| lhs.name().to_string()), + ); + } let name = match callee { sv::ir::Callee::System(function) => { names.extend( @@ -1647,6 +1654,11 @@ impl DriverScan<'_> { }); } while let Some((callee, args)) = calls.pop() { + if let sv::ir::Callee::Object(op) = &callee { + for lhs in procedural::written_object_arguments(op, &args) { + record(&lhs); + } + } let name = match callee { sv::ir::Callee::System(function) => { for lvalue in procedural::written_system_arguments(function, &args) { @@ -10556,6 +10568,11 @@ mod tests { }); } while let Some((callee, args)) = calls.pop() { + if let sv::ir::Callee::Object(op) = &callee { + for lhs in procedural::written_object_arguments(op, &args) { + record(drivers, &lhs); + } + } let name = match callee { sv::ir::Callee::System(function) => { for lvalue in procedural::written_system_arguments(function, &args) { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index bdc54ff5324..17a1305b6a0 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -9,6 +9,7 @@ //! Expressions are lowered through SLT, which keeps their width and //! four-state semantics identical to the combinational lowering. +mod containers; mod file_io; mod fread; mod objects; @@ -807,6 +808,13 @@ impl<'p, 'a> Ff<'p, 'a> { let mut assigned = HashSet::default(); let mut visited = HashSet::default(); while let Some((callee, args)) = calls.pop() { + if let sv::ir::Callee::Object(op) = &callee { + assigned.extend( + written_object_arguments(op, &args) + .iter() + .filter_map(|lhs| self.m.id(lhs.name())), + ); + } let sv::ir::Callee::Subroutine(name) = callee else { continue; }; @@ -867,6 +875,11 @@ impl<'p, 'a> Ff<'p, 'a> { stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); } while let Some((callee, args)) = calls.pop() { + if let sv::ir::Callee::Object(op) = &callee { + for lhs in written_object_arguments(op, &args) { + self.record_target(&lhs, true); + } + } let name = match callee { sv::ir::Callee::System(function) => { use sv::ir::SystemFunction; @@ -1595,7 +1608,12 @@ impl<'p, 'a> Ff<'p, 'a> { callee: sv::ir::Callee::Object(op), args, .. - } => self.object_call(op, args)?, + } => match &**op { + sv::ir::ObjectOp::Container { op, layout } => { + self.container_call(*op, *layout, args)? + } + _ => self.object_call(op, args)?, + }, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fopen), args, diff --git a/crates/celox-frontend-sv/src/lowering/ff/containers.rs b/crates/celox-frontend-sv/src/lowering/ff/containers.rs new file mode 100644 index 00000000000..b4cb6765076 --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/containers.rs @@ -0,0 +1,414 @@ +//! Procedural container operations use the same heap ABI on every backend. +use super::*; +use celox_heap::{containers as heap, ops::encode}; +use sv::ir::{ContainerKind, ContainerLayout, ContainerOp, HandleProperty}; + +impl Ff<'_, '_> { + pub(super) fn container_call( + &mut self, + op: ContainerOp, + layout: ContainerLayout, + args: &[Option], + ) -> Result { + use ContainerOp::*; + let args = args + .iter() + .map(|arg| { + arg.clone() + .ok_or_else(|| unsupported("omitted container operand")) + }) + .collect::, _>>()?; + let (kind, capacity, signed_key, string_key) = match layout.kind { + ContainerKind::Dynamic => (0, 0, false, false), + ContainerKind::Queue { capacity } => (1, capacity, false, false), + ContainerKind::Associative { signed, string, .. } => (2, 0, signed, string), + }; + let parameter = heap::parameter( + layout.width, + layout.two_state || !self.m.four_state, + match layout.handle { + None => 0, + Some(HandleProperty::String) => 1, + Some(HandleProperty::Object) => 2, + }, + kind, + capacity, + signed_key, + string_key, + ); + let code = |opcode| encode(opcode, parameter); + let zero = self.constant64(0); + let (width, signed) = op.result_type(layout); + let element_result = matches!(op, Get | PopFront | PopBack); + let four_state = (element_result || op == Equal) && !layout.two_state && self.m.four_state; + let (temp, name) = self.m.temp("container", width, signed, four_state); + if matches!(op, New | Literal | Convert) + || element_result && layout.handle == Some(HandleProperty::Object) + { + self.m.variables.get_mut(&temp).unwrap().value_kind = celox_design::ValueKind::ObjRef; + } else if element_result && layout.handle == Some(HandleProperty::String) { + self.m.variables.get_mut(&temp).unwrap().value_kind = celox_design::ValueKind::StrRef; + } + let result = match op { + Equal | CaseEqual => { + let left = self.handle(&args[0])?; + let right = self.handle(&args[1])?; + let raw = self.heap_call( + code(if op == Equal { + heap::EQUAL + } else { + heap::CASE_EQUAL + }), + &[left, right], + ); + let one = self.constant64(1); + let mask = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Binary(mask, raw, BinaryOp::Shr, one)); + let value = self.container_join(raw, mask, 1, four_state); + self.store(temp, SIROffset::Static(0), 1, value); + return Ok(sv::ir::Expr::Ident(name)); + } + New => { + let size = self.integer_of_width(&args[0], 64, true)?; + let source = self.handle(&args[1])?; + self.heap_call(code(heap::NEW), &[size, source]) + } + Convert if matches!(layout.kind, ContainerKind::Associative { .. }) => { + self.handle(&args[0])? + } + Convert => { + let source = self.handle(&args[0])?; + let size = self.heap_call(code(heap::LEN), &[source]); + self.heap_call(code(heap::NEW), &[size, source]) + } + Literal => { + let size = self.constant64(args.len() as u64); + let mut handle = self.heap_call(code(heap::NEW), &[size, zero]); + for (i, arg) in args.iter().enumerate() { + let (value, mask) = self.container_element(arg, layout)?; + let index = self.constant64(i as u64); + handle = self.heap_call(code(heap::SET), &[handle, index, value]); + handle = self.heap_call(code(heap::SET_MASK), &[handle, index, mask]); + } + handle + } + _ => { + let mut index_mask = zero; + let index = match op { + Size | Clear | PushFront | PopFront | PushBack | PopBack => zero, + _ if string_key => self.handle(&args[1])?, + _ => { + let (width, signed) = match layout.kind { + ContainerKind::Associative { + key_width, signed, .. + } => (key_width as usize, signed), + _ if matches!(op, Get | Set) => (64, true), + _ => (32, true), + }; + let value = self.hoist(&args[1])?; + let reg = self.eval(&value, Some((width, signed)))?; + let (raw, mask) = self.container_split(reg); + index_mask = mask; + let narrow = self.b.alloc_bit(width, signed); + self.b.emit(SIRInstruction::Slice(narrow, raw, 0, width)); + let index = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Unary(index, UnaryOp::Ident, narrow)); + if signed && width < 64 { + let shift = self.constant64((64 - width) as u64); + let shifted = self.b.alloc_bit(64, false); + self.b.emit(SIRInstruction::Binary( + shifted, + index, + BinaryOp::Shl, + shift, + )); + let extended = self.b.alloc_bit(64, false); + self.b.emit(SIRInstruction::Binary( + extended, + shifted, + BinaryOp::Sar, + shift, + )); + extended + } else { + index + } + } + }; + let (value, mask) = if matches!(op, Set | Insert | PushFront | PushBack) { + self.container_element(args.last().unwrap(), layout)? + } else { + (zero, zero) + }; + // Arguments can mutate the receiver (e.g. q.push_back(q.pop_front())). + // Read its current contents and derive positions only after evaluating them. + let handle = self.handle(&args[0])?; + let index = match op { + PushBack => self.heap_call(code(heap::LEN), &[handle]), + PopBack => { + let size = self.heap_call(code(heap::LEN), &[handle]); + let one = self.constant64(1); + let index = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Binary(index, size, BinaryOp::Sub, one)); + index + } + _ => index, + }; + if matches!(op, First | Last | Next | Prev) { + let traversal = match op { + First => heap::FIRST, + Last => heap::LAST, + Next => heap::NEXT, + _ => heap::PREV, + }; + let traversal_reg = self.constant64(traversal); + let exists = + self.heap_call(code(heap::ITER_VALID), &[handle, index, traversal_reg]); + let exists = if matches!(op, Next | Prev) { + let valid = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + valid, + index_mask, + BinaryOp::Eq, + zero, + )); + let known = self.b.alloc_bit(64, false); + self.b.emit(SIRInstruction::Mux(known, valid, exists, zero)); + known + } else { + exists + }; + let target = args[1].clone(); + self.when(exists, |this| { + let key = this.heap_call(code(traversal), &[handle, index]); + let key_width = if string_key { + celox_design::HANDLE_WIDTH + } else { + 64 + }; + let (id, key_name) = + this.m.temp("container_key", key_width, signed_key, false); + if string_key { + this.m.variables.get_mut(&id).unwrap().value_kind = + celox_design::ValueKind::StrRef; + } + let value = this.b.alloc_bit(key_width, signed_key); + this.b.emit(SIRInstruction::Slice(value, key, 0, key_width)); + this.store(id, SIROffset::Static(0), key_width, value); + let sv::ir::Expr::Ident(target) = target else { + return Err(unsupported("associative index output")); + }; + this.assign( + &sv::ir::LValue::Ident(target), + &sv::ir::Expr::Ident(key_name), + ) + })?; + let narrow = match layout.kind { + ContainerKind::Associative { + key_width, + string: false, + .. + } => self + .m + .comparison_width(&args[1], &args[1]) + .is_some_and(|width| width < key_width as usize), + _ => false, + }; + if narrow { + let minus_one = self.constant64(u64::MAX); + let status = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Mux(status, exists, minus_one, zero)); + status + } else { + exists + } + } else if op == Size { + self.heap_call(code(heap::LEN), &[handle]) + } else if op == Exists { + let exists = self.heap_call(code(heap::EXISTS), &[handle, index]); + let valid = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + valid, + index_mask, + BinaryOp::Eq, + zero, + )); + let result = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Mux(result, valid, exists, zero)); + result + } else { + if element_result { + let value = self.heap_call(code(heap::GET), &[handle, index, index_mask]); + let mask = + self.heap_call(code(heap::GET_MASK), &[handle, index, index_mask]); + let result = self.container_join(value, mask, width, four_state); + self.store(temp, SIROffset::Static(0), width, result); + } + if op.mutates() { + let valid = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + valid, + index_mask, + BinaryOp::Eq, + zero, + )); + let receiver = args[0].clone(); + self.when(valid, |this| { + let opcode = match op { + Set => heap::SET, + Insert | PushFront | PushBack => heap::INSERT, + Clear => heap::CLEAR, + _ => heap::DELETE, + }; + let mut updated = this.heap_call(code(opcode), &[handle, index, value]); + if matches!(op, Set | Insert | PushFront | PushBack) { + updated = + this.heap_call(code(heap::SET_MASK), &[updated, index, mask]); + } + let (id, updated_name) = + this.m.temp("container_update", 32, false, false); + this.m.variables.get_mut(&id).unwrap().value_kind = + celox_design::ValueKind::ObjRef; + let narrow = this.b.alloc_bit(32, false); + this.b.emit(SIRInstruction::Slice(narrow, updated, 0, 32)); + this.store(id, SIROffset::Static(0), 32, narrow); + let sv::ir::Expr::Ident(receiver) = receiver else { + return Err(unsupported("container receiver must be a variable")); + }; + this.assign( + &sv::ir::LValue::Ident(receiver), + &sv::ir::Expr::Ident(updated_name), + ) + })?; + } + zero + } + } + }; + if !element_result { + let narrow = self.b.alloc_bit(width, signed); + self.b.emit(SIRInstruction::Slice(narrow, result, 0, width)); + self.store(temp, SIROffset::Static(0), width, narrow); + } + Ok(sv::ir::Expr::Ident(name)) + } + + fn container_element( + &mut self, + expr: &sv::ir::Expr, + layout: ContainerLayout, + ) -> Result<(RegisterId, RegisterId), sv::AnalyzerError> { + let expr = self.hoist(expr)?; + let value = self.eval(&expr, Some((layout.width as usize, layout.signed)))?; + if layout.two_state { + let known = self.b.alloc_bit(layout.width as usize, layout.signed); + self.b + .emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, value)); + return Ok(self.container_split(known)); + } + Ok(self.container_split(value)) + } + + // Case equality exposes the planes without changing the SIR or backend ABI. + fn container_split(&mut self, reg: RegisterId) -> (RegisterId, RegisterId) { + let width = self.b.register(®).width(); + if !self.m.four_state + || !matches!(self.b.register(®), celox_sir::RegisterType::Logic { .. }) + { + let value = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Unary(value, UnaryOp::Ident, reg)); + return (value, self.constant64(0)); + } + let one = self.b.alloc_logic(1); + self.b + .emit(SIRInstruction::Imm(one, SIRValue::new(BigUint::from(1u8)))); + let z = self.b.alloc_logic(1); + self.b.emit(SIRInstruction::Imm( + z, + SIRValue::new_four_state(BigUint::zero(), BigUint::from(1u8)), + )); + let x = self.b.alloc_logic(1); + self.b.emit(SIRInstruction::Imm( + x, + SIRValue::new_four_state(BigUint::from(1u8), BigUint::from(1u8)), + )); + let mut values = Vec::new(); + let mut masks = Vec::new(); + for i in (0..width).rev() { + let bit = self.b.alloc_logic(1); + self.b.emit(SIRInstruction::Slice(bit, reg, i, 1)); + let is_one = self.b.alloc_bit(1, false); + let is_z = self.b.alloc_bit(1, false); + let is_x = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(is_one, bit, BinaryOp::EqCase, one)); + self.b + .emit(SIRInstruction::Binary(is_z, bit, BinaryOp::EqCase, z)); + self.b + .emit(SIRInstruction::Binary(is_x, bit, BinaryOp::EqCase, x)); + let value = self.b.alloc_bit(1, false); + let mask = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(value, is_one, BinaryOp::Or, is_x)); + self.b + .emit(SIRInstruction::Binary(mask, is_x, BinaryOp::Or, is_z)); + values.push(value); + masks.push(mask); + } + let mut packed = Vec::new(); + for bits in [values, masks] { + let narrow = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Concat(narrow, bits)); + let wide = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Unary(wide, UnaryOp::Ident, narrow)); + packed.push(wide); + } + (packed[0], packed[1]) + } + + fn container_join( + &mut self, + value: RegisterId, + mask: RegisterId, + width: usize, + four_state: bool, + ) -> RegisterId { + if !four_state { + let reg = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Slice(reg, value, 0, width)); + return reg; + } + let x = self.b.alloc_logic(1); + let z = self.b.alloc_logic(1); + self.b.emit(SIRInstruction::Imm( + x, + SIRValue::new_four_state(BigUint::from(1u8), BigUint::from(1u8)), + )); + self.b.emit(SIRInstruction::Imm( + z, + SIRValue::new_four_state(BigUint::zero(), BigUint::from(1u8)), + )); + let mut bits = Vec::new(); + for i in (0..width).rev() { + let v = self.b.alloc_bit(1, false); + let m = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Slice(v, value, i, 1)); + self.b.emit(SIRInstruction::Slice(m, mask, i, 1)); + let unknown = self.b.alloc_logic(1); + self.b.emit(SIRInstruction::Mux(unknown, v, x, z)); + let bit = self.b.alloc_logic(1); + self.b.emit(SIRInstruction::Mux(bit, m, unknown, v)); + bits.push(bit); + } + let result = self.b.alloc_logic(width); + self.b.emit(SIRInstruction::Concat(result, bits)); + result + } +} diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index 4b83614aa47..b0f44024a44 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -24,6 +24,7 @@ impl Ff<'_, '_> { }) .collect::, _>>()?; let result = match op { + ObjectOp::Container { .. } => unreachable!("handled by container_call"), ObjectOp::New { class, size, @@ -125,6 +126,7 @@ impl Ff<'_, '_> { self.b.emit(SIRInstruction::Slice(value, result, 0, width)); let (temp, name) = self.m.temp("object", width, signed, false); let kind = match op { + ObjectOp::Container { .. } => unreachable!("handled by container_call"), ObjectOp::New { .. } | ObjectOp::Copy => Some(celox_design::ValueKind::ObjRef), ObjectOp::Load(field) => field.handle.map(|handle| match handle { HandleProperty::String => celox_design::ValueKind::StrRef, diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 8db1571dae6..1f445fb33a2 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -101,8 +101,11 @@ impl<'a> ProcModule<'a> { 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)), + } => { + matches!(**op, sv::ir::ObjectOp::Load(field) + if field.handle == Some(sv::ir::HandleProperty::String)) + || matches!(**op, sv::ir::ObjectOp::Container { op: sv::ir::ContainerOp::Get | sv::ir::ContainerOp::PopFront | sv::ir::ContainerOp::PopBack, layout } if layout.handle == Some(sv::ir::HandleProperty::String)) + } sv::ir::Expr::Call { callee: sv::ir::Callee::Subroutine(name), .. @@ -2843,6 +2846,19 @@ pub(super) fn written_system_arguments( .collect() } +/// State writes performed by heap container calls. +pub(super) fn written_object_arguments( + op: &sv::ir::ObjectOp, + args: &[Option], +) -> Vec { + args.iter() + .enumerate() + .filter(|(position, _)| op.writes_argument(*position)) + .filter_map(|(_, arg)| arg.as_ref().and_then(lvalue_from_expr)) + .flatten() + .collect() +} + /// Keep checked member references writable while carrying their live tag checks /// separately. Callers that perform stores must execute these checks. pub(super) fn tagged_actual_guards(expr: &sv::ir::Expr) -> Vec { diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 5cf51a0bdb5..866d9aecdb0 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -120,7 +120,8 @@ impl Deref for AnalysisContext<'_> { } pub use crate::system_functions::{ - ArrayQuery, Callee, ObjectOp, StringOp, SystemFunction, SystemTask, + ArrayQuery, Callee, ContainerKind, ContainerLayout, ContainerOp, ObjectOp, StringOp, + SystemFunction, SystemTask, }; use crate::{AnalyzerError, system_functions, typecheck}; @@ -162,6 +163,7 @@ mod port_owners; mod timing; mod type_binding; pub(crate) use parameters::unbounded_parameter_marker; +mod containers; mod patterns; mod procedural; mod scope; @@ -2111,6 +2113,7 @@ pub enum PortDirection { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Type { + container: Option>, is_enum: bool, /// Resolved legal values for a scalar enum; None if its domain is unsupported. enum_values: Option>, @@ -2124,7 +2127,14 @@ pub struct Type { /// 1800-2023 7.4.1). signed_element_depth: Option, /// The class of an object handle type. - class: Option, + class: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct ContainerType { + key: Option, + layout: system_functions::ContainerLayout, + element: Type, } impl Type { @@ -2139,6 +2149,7 @@ impl Type { members: Vec::new(), signed_element_depth: None, class: None, + container: None, } } @@ -2153,6 +2164,7 @@ impl Type { members: Vec::new(), signed_element_depth: None, class: None, + container: None, } } @@ -2915,6 +2927,7 @@ struct UnpackedDimension { #[derive(Debug, Clone, PartialEq, Eq)] struct VariableDimensions { + container: Option>, randomizable: bool, enum_values: Option>, real: bool, diff --git a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs index 7f9ae36c9cb..8acc1238d0a 100644 --- a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs +++ b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs @@ -51,6 +51,7 @@ pub(super) fn selected_unpacked_shape( .get(indices..) .filter(|rest| !rest.is_empty())?; Some(VariableDimensions { + container: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs index 795f265f5ce..f151c001d4a 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -214,6 +214,7 @@ impl BoundPattern { .map_err(|_| unsupported("assignment pattern target size"))?; shapes = vec![ VariableDimensions { + container: None, real: false, string: false, class: None, @@ -240,6 +241,7 @@ impl BoundPattern { .map_err(|_| unsupported("assignment pattern target size"))?; shapes = vec![ VariableDimensions { + container: None, real: false, string: false, class: None, @@ -287,6 +289,7 @@ impl BoundPattern { .ok_or_else(|| unsupported("pattern target width"))?; shapes = vec![ VariableDimensions { + container: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index 4a9e1598fa8..de0eb38e4c8 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -70,9 +70,11 @@ pub(super) fn expr_is_two_state( .. } => false, Expr::Call { - callee: Callee::Object(_), + callee: Callee::Object(op), .. - } => true, + } => { + !matches!(**op, ObjectOp::Container { op: ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal, layout } if !layout.two_state) + } Expr::Call { callee: Callee::Subroutine(name), .. diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 10eecdbc2b6..471476bbbe7 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -631,7 +631,7 @@ pub(super) fn handle(name: &str) -> Type { ConstExpr::Literal((HANDLE_WIDTH - 1).to_string()), ConstExpr::Literal("0".into()), )); - ty.class = Some(name.to_owned()); + ty.class = Some(Arc::from(name)); ty } @@ -697,7 +697,7 @@ pub(super) fn class( let ty = match recorded { Some(ty) => ty, None => type_binding::procedural_type(base.data_type, native, tree, env, aliases)? - .and_then(|ty| ty.class.clone()) + .and_then(|ty| ty.class().map(str::to_owned)) .ok_or_else(|| unsupported("base class type"))?, }; Some(class(tree, &ty, env, aliases)?) @@ -893,7 +893,7 @@ fn interface_name( ) -> Converted { let native = tree.declarations(); let name = type_binding::procedural_type(interface, native, tree, env, aliases)? - .and_then(|ty| ty.class.clone()) + .and_then(|ty| ty.class().map(str::to_owned)) .ok_or_else(|| unsupported("implemented interface class type"))?; // An interface class of another scope is known by its layout. let interface = match imported(tree, &name) { @@ -1091,6 +1091,9 @@ fn field( env: &HashMap, offset: u32, ) -> Converted { + if ty.container.is_some() { + return Err(unsupported("dynamic container class property")); + } let (width, signed, handle) = match ty.kind() { TypeKind::String => (HANDLE_WIDTH, false, Some(HandleProperty::String)), TypeKind::Object => (HANDLE_WIDTH, false, Some(HandleProperty::Object)), diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index 8ea3ed49ee5..7fddf6b39ec 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -402,7 +402,7 @@ pub(in crate::ast) fn specialize( let mut bases = Vec::new(); for id in inherited { if let Some(base) = type_binding::procedural_type(id, native, tree, &env, &aliases)? - .and_then(|ty| ty.class.clone()) + .and_then(|ty| ty.class().map(str::to_owned)) { bases.push(base); } @@ -706,7 +706,7 @@ fn type_argument( .type_aliases .get(&scope_key(&scope)) .or_else(|| context.type_aliases.get(&scope_key(&class))) - .and_then(|ty| ty.class.clone()) + .and_then(|ty| ty.class().map(str::to_owned)) { Some(specialization) => Some(specialization), None if super::is_declared(tree, &class) => { diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs new file mode 100644 index 00000000000..f30930ee12f --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -0,0 +1,729 @@ +//! Binding of dynamically sized unpacked value containers (clause 7). +use super::*; +use celox_sv_syntax::{Dimension, DimensionKind, ExprId, ExprKind}; +use system_functions::{ContainerKind, ContainerLayout, ContainerOp, HandleProperty}; + +pub(super) fn with_dimensions( + base: Type, + dims: &[Dimension], + tree: &AnalysisContext<'_>, + context: &PackedDimensions, +) -> Converted { + let Some(first) = dims.first() else { + return Ok(base); + }; + let mut index_type = None; + let kind = match first.kind { + DimensionKind::Unsized => Some(ContainerKind::Dynamic), + DimensionKind::Queue(bound) => { + let capacity = match bound { + None => 0, + Some(id) => { + let bound = constant_binding::bind(id, tree, context)? + .and_then(|v| eval_ast_const_expr(&tree.state, &v, &context.const_env)) + .and_then(|v| u32::try_from(v).ok()) + .filter(|v| *v > 0 && *v < u32::MAX) + .ok_or_else(|| { + unsupported("queue bound must be a positive integer below 2^32-1") + })?; + bound + 1 + } + }; + Some(ContainerKind::Queue { capacity }) + } + DimensionKind::Index(id) => { + let key_type = match &tree.declarations().expression(id).kind { + ExprKind::Type(id) => type_binding::bind(*id, tree, context)?, + ExprKind::Name(name) => context + .type_aliases + .get(&instances::normalize_identifier(&name.spelling)) + .cloned(), + _ => None, + }; + match key_type { + None => None, + Some(ty) => { + index_type = Some(ty.clone()); + let string = ty.kind() == TypeKind::String; + let shape = casts::expr_type_from_type(&tree.state, &ty, &context.const_env) + .ok_or_else(|| unsupported("associative index type"))?; + if !string + && (!matches!(ty.kind(), TypeKind::Bit | TypeKind::Logic | TypeKind::Reg) + || shape.width > 64 + || !ty.unpacked_ranges.is_empty()) + { + return Err(unsupported( + "associative indices require strings or integral types up to 64 bits", + )); + } + Some(ContainerKind::Associative { + key_width: shape.width as u32, + signed: shape.signed, + string, + }) + } + } + } + DimensionKind::Wildcard => return Err(unsupported("wildcard associative index type")), + _ => None, + }; + let Some(kind) = kind else { + return Ok(types::type_with_unpacked_ranges( + base, + constant_binding::bind_unpacked_ranges(dims, tree, context)?, + )); + }; + if dims.len() != 1 || base.container.is_some() || !base.unpacked_ranges.is_empty() { + return Err(unsupported("multidimensional dynamic container")); + } + if matches!(base.kind(), TypeKind::Real | TypeKind::Shortreal) { + return Err(unsupported("real dynamic container elements")); + } + let shape = casts::expr_type_from_type(&tree.state, &base, &context.const_env) + .ok_or_else(|| unsupported("dynamic container element type"))?; + if shape.width == 0 || shape.width > 64 { + return Err(unsupported("dynamic container elements wider than 64 bits")); + } + let handle = match base.kind() { + TypeKind::String => Some(HandleProperty::String), + TypeKind::Object => Some(HandleProperty::Object), + _ => None, + }; + let layout = ContainerLayout { + kind, + width: shape.width as u32, + signed: shape.signed, + two_state: base.kind() == TypeKind::Bit || handle.is_some(), + handle, + }; + let mut ty = Type::new(TypeKind::Object); + ty.packed_ranges.push(PackedRange::new( + ConstExpr::Literal("31".into()), + ConstExpr::Literal("0".into()), + )); + ty.container = Some(Arc::new(ContainerType { + key: index_type, + layout, + element: base, + })); + Ok(ty) +} + +pub(super) fn native_type<'a>( + id: ExprId, + native: &celox_sv_syntax::Declarations, + dims: &'a PackedDimensions, +) -> Option<&'a ContainerType> { + let ExprKind::Name(name) = &native + .expression(expression_binding::ungroup(id, native)) + .kind + else { + return None; + }; + dims.get(&instances::normalize_identifier(&name.spelling))? + .container + .as_deref() +} + +pub(super) fn call(op: ContainerOp, layout: ContainerLayout, args: Vec) -> Expr { + classes::object_call(ObjectOp::Container { op, layout }, args) +} + +/// Container assignment is value assignment, whereas object elements are handles. +pub(super) fn assignment( + root: ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, + target: &ContainerType, +) -> Converted { + let native = tree.declarations(); + let root = expression_binding::ungroup(root, native); + let (construct, initializer) = match &native.expression(root).kind { + ExprKind::Call { + expression, + arguments, + } if arguments.len() == 1 && arguments[0].name.is_none() => { + (*expression, arguments[0].value) + } + _ => (root, None), + }; + if let ExprKind::Select { + expression, + dimension, + } = &native.expression(construct).kind + && matches!(&native.expression(*expression).kind, ExprKind::Name(n) if n.spelling == "new") + { + if target.layout.kind != ContainerKind::Dynamic { + return Err(unsupported("new[] requires a dynamic array")); + } + let DimensionKind::Index(size) = dimension.kind else { + return Err(unsupported("dynamic array size")); + }; + let size = expression_binding::value(size, native, tree, dims)?; + let init = match initializer { + Some(id) => { + check_compatible(id, native, dims, target)?; + expression_binding::value(id, native, tree, dims)? + } + None => Expr::Literal("0".into()), + }; + return Ok(call(ContainerOp::New, target.layout, vec![size, init])); + } + let items = match &native.expression(root).kind { + ExprKind::Concatenation(items) => Some(items.clone()), + ExprKind::Pattern { + target: None, + items, + } if items.iter().all(|item| item.key.is_none()) => { + Some(items.iter().map(|item| item.value).collect()) + } + _ => None, + }; + if let Some(items) = items { + if matches!(target.layout.kind, ContainerKind::Associative { .. }) { + return Err(unsupported("associative array assignment pattern")); + } + let values = items + .into_iter() + .map(|id| element_value(id, tree, dims, target)) + .collect::>>()?; + return Ok(call(ContainerOp::Literal, target.layout, values)); + } + check_compatible(root, native, dims, target)?; + Ok(call( + ContainerOp::Convert, + target.layout, + vec![expression_binding::value(root, native, tree, dims)?], + )) +} +fn check_compatible( + id: ExprId, + native: &celox_sv_syntax::Declarations, + dims: &PackedDimensions, + target: &ContainerType, +) -> Converted<()> { + let Some(source) = native_type(id, native, dims) else { + return Err(unsupported( + "container assignment requires a compatible container", + )); + }; + if source.key != target.key + || source.element != target.element + || match (source.layout.kind, target.layout.kind) { + (ContainerKind::Associative { .. }, _) | (_, ContainerKind::Associative { .. }) => { + source.layout.kind != target.layout.kind + } + _ => false, + } + { + return Err(unsupported("incompatible dynamic container assignment")); + } + Ok(()) +} + +fn element_value( + id: ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, + target: &ContainerType, +) -> Converted { + let native = tree.declarations(); + if native_type(id, native, dims).is_some() { + return Err(unsupported("container used as an element")); + } + if let Some(class) = target.element.class.as_deref() { + if let Some(call) = expression_binding::object_constructor(tree, id, native, dims, class)? { + return Ok(call); + } + expression_binding::check_handle_assignment(tree, id, native, dims, class, || { + "container element assignment".into() + })?; + } + let shape = procedural::dimensions_from_type(&target.element); + let value = expression_binding::bind_value(id, native, tree, dims, Some(&shape))?; + Ok(if target.layout.handle == Some(HandleProperty::String) { + expression_binding::string_operand(value, dims) + } else { + value + }) +} +fn index_value( + id: ExprId, + base: ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, + target: &ContainerType, +) -> Converted { + let native = tree.declarations(); + if matches!( + target.layout.kind, + ContainerKind::Associative { string: true, .. } + ) && !expression_binding::native_string(tree, id, native, dims) + && !matches!(&native.expression(expression_binding::ungroup(id, native)).kind, ExprKind::Literal(text) if text.starts_with('"')) + { + return Err(unsupported( + "string associative index requires a string value", + )); + } + let value = match &native + .expression(expression_binding::ungroup(id, native)) + .kind + { + ExprKind::Name(name) + if name.spelling == "$" + && matches!(target.layout.kind, ContainerKind::Queue { .. }) => + { + Expr::Binary { + left: Box::new(call( + ContainerOp::Size, + target.layout, + vec![expression_binding::value(base, native, tree, dims)?], + )), + op: BinaryOp::Sub, + right: Box::new(Expr::Literal("1".into())), + } + } + ExprKind::Binary { + left, + operator, + right, + } if operator == "+" || operator == "-" => Expr::Binary { + left: Box::new(index_value(*left, base, tree, dims, target)?), + op: if operator == "+" { + BinaryOp::Add + } else { + BinaryOp::Sub + }, + right: Box::new(index_value(*right, base, tree, dims, target)?), + }, + _ => expression_binding::value(id, native, tree, dims)?, + }; + Ok( + if matches!( + target.layout.kind, + ContainerKind::Associative { string: true, .. } + ) { + expression_binding::string_operand(value, dims) + } else { + value + }, + ) +} + +pub(super) fn value( + id: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, + statement: bool, +) -> Converted> { + if let Some(query) = query(id, native, tree, dims)? { + return Ok(Some(query)); + } + match &native.expression(id).kind { + ExprKind::Binary { + left, + operator, + right, + } if native_type(*left, native, dims).is_some() + || native_type(*right, native, dims).is_some() => + { + let Some(target) = native_type(*left, native, dims) else { + return Err(unsupported("container comparison requires two containers")); + }; + check_compatible(*right, native, dims, target)?; + let source = native_type(*right, native, dims).expect("checked compatibility"); + if std::mem::discriminant(&source.layout.kind) + != std::mem::discriminant(&target.layout.kind) + { + return Err(unsupported( + "container comparison requires equivalent array kinds", + )); + } + + let op = match operator.as_str() { + "==" | "!=" => ContainerOp::Equal, + "===" | "!==" => ContainerOp::CaseEqual, + _ => return Err(unsupported("integral operator on a dynamic container")), + }; + let value = call( + op, + target.layout, + vec![ + expression_binding::value(*left, native, tree, dims)?, + expression_binding::value(*right, native, tree, dims)?, + ], + ); + Ok(Some(if matches!(operator.as_str(), "!=" | "!==") { + Expr::Unary { + op: UnaryOp::LogicNot, + expr: Box::new(value), + } + } else { + value + })) + } + ExprKind::Select { + expression, + dimension, + } => { + let Some(target) = native_type(*expression, native, dims) else { + return Ok(None); + }; + let index = match dimension.kind { + DimensionKind::Index(index) => Some(index), + DimensionKind::Queue(None) + if matches!(target.layout.kind, ContainerKind::Queue { .. }) => + { + None + } + _ => return Err(unsupported("dynamic container slice")), + }; + Ok(Some(call( + ContainerOp::Get, + target.layout, + vec![ + expression_binding::value(*expression, native, tree, dims)?, + match index { + Some(index) => index_value(index, *expression, tree, dims, target)?, + None => Expr::Binary { + left: Box::new(call( + ContainerOp::Size, + target.layout, + vec![expression_binding::value(*expression, native, tree, dims)?], + )), + op: BinaryOp::Sub, + right: Box::new(Expr::Literal("1".into())), + }, + }, + ], + ))) + } + ExprKind::Call { + expression, + arguments, + } => { + let ExprKind::Member { + expression: base, + separator, + name, + } = &native.expression(*expression).kind + else { + return Ok(None); + }; + let Some(target) = native_type(*base, native, dims) else { + return Ok(None); + }; + if separator != "." { + return Err(unsupported("container scoped call")); + } + let (op, count) = match name.spelling.as_str() { + "size" | "num" + if name.spelling == "size" + || matches!(target.layout.kind, ContainerKind::Associative { .. }) => + { + (ContainerOp::Size, 0) + } + "delete" if arguments.is_empty() => (ContainerOp::Clear, 0), + "delete" if target.layout.kind != ContainerKind::Dynamic => { + (ContainerOp::Delete, 1) + } + "insert" if matches!(target.layout.kind, ContainerKind::Queue { .. }) => { + (ContainerOp::Insert, 2) + } + "push_front" if matches!(target.layout.kind, ContainerKind::Queue { .. }) => { + (ContainerOp::PushFront, 1) + } + "push_back" if matches!(target.layout.kind, ContainerKind::Queue { .. }) => { + (ContainerOp::PushBack, 1) + } + "pop_front" if matches!(target.layout.kind, ContainerKind::Queue { .. }) => { + (ContainerOp::PopFront, 0) + } + "pop_back" if matches!(target.layout.kind, ContainerKind::Queue { .. }) => { + (ContainerOp::PopBack, 0) + } + "exists" if matches!(target.layout.kind, ContainerKind::Associative { .. }) => { + (ContainerOp::Exists, 1) + } + "first" if matches!(target.layout.kind, ContainerKind::Associative { .. }) => { + (ContainerOp::First, 1) + } + "last" if matches!(target.layout.kind, ContainerKind::Associative { .. }) => { + (ContainerOp::Last, 1) + } + "next" if matches!(target.layout.kind, ContainerKind::Associative { .. }) => { + (ContainerOp::Next, 1) + } + "prev" if matches!(target.layout.kind, ContainerKind::Associative { .. }) => { + (ContainerOp::Prev, 1) + } + _ => return Err(unsupported(format!("container method `{}`", name.spelling))), + }; + if op.mutates() + && !matches!(op, ContainerOp::PopFront | ContainerOp::PopBack) + && !statement + { + return Err(unsupported("void container method used as a value")); + } + if arguments.len() != count + || arguments + .iter() + .any(|arg| arg.name.is_some() || arg.value.is_none()) + { + return Err(unsupported(format!( + "arguments of container method `{}`", + name.spelling + ))); + } + let mut args = vec![expression_binding::value(*base, native, tree, dims)?]; + for (index, arg) in arguments.iter().enumerate() { + let id = arg.value.unwrap(); + if matches!( + op, + ContainerOp::First | ContainerOp::Last | ContainerOp::Next | ContainerOp::Prev + ) { + let ExprKind::Name(name) = &native.expression(id).kind else { + return Err(unsupported( + "associative traversal requires an index variable", + )); + }; + let shape = dims + .get(&instances::normalize_identifier(&name.spelling)) + .ok_or_else(|| unsupported("associative traversal index variable"))?; + if let ContainerKind::Associative { string, .. } = target.layout.kind + && (shape.string != string + || shape.container.is_some() + || !shape.unpacked.is_empty()) + { + return Err(unsupported( + "incompatible associative traversal index variable", + )); + } + args.push(expression_binding::value(id, native, tree, dims)?); + } else if matches!(op, ContainerOp::PushFront | ContainerOp::PushBack) + || op == ContainerOp::Insert && index == 1 + { + args.push(element_value(id, tree, dims, target)?); + } else { + args.push(index_value(id, *base, tree, dims, target)?); + } + } + Ok(Some(call(op, target.layout, args))) + } + _ => Ok(None), + } +} + +fn query( + id: ExprId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted> { + let ExprKind::Call { + expression, + arguments, + } = &native.expression(id).kind + else { + return Ok(None); + }; + let ExprKind::Name(name) = &native.expression(*expression).kind else { + return Ok(None); + }; + if !matches!( + name.spelling.as_str(), + "$bits" + | "$size" + | "$left" + | "$right" + | "$low" + | "$high" + | "$increment" + | "$dimensions" + | "$unpacked_dimensions" + ) { + return Ok(None); + } + let Some(base) = arguments.first().and_then(|a| a.value) else { + return Ok(None); + }; + let Some(target) = native_type(base, native, dims) else { + return Ok(None); + }; + if arguments + .iter() + .any(|arg| arg.name.is_some() || arg.value.is_none()) + { + return Err(unsupported("dynamic array query arguments")); + } + if matches!( + name.spelling.as_str(), + "$dimensions" | "$unpacked_dimensions" + ) { + if arguments.len() != 1 { + return Err(unsupported("dynamic array query arguments")); + } + return Ok(Some(Expr::Literal( + if name.spelling == "$unpacked_dimensions" { + 1 + } else { + 1 + if target.layout.handle.is_some() { + 0 + } else { + target.element.packed_ranges.len() + } + } + .to_string(), + ))); + } + if matches!( + target.layout.kind, + ContainerKind::Associative { string: true, .. } + ) { + return Err(unsupported("array query on a string associative dimension")); + } + if name.spelling == "$bits" { + return Err(unsupported("$bits of a dynamic container")); + } + if arguments.len() > 2 { + return Err(unsupported("dynamic array query arguments")); + } + let dimension = match arguments.get(1).and_then(|a| a.value) { + None => 1, + Some(id) => constant_binding::bind(id, tree, dims)? + .and_then(|v| eval_ast_const_expr(&tree.state, &v, &dims.const_env)) + .ok_or_else(|| unsupported("nonconstant dynamic array query dimension"))?, + }; + if dimension != 1 { + return Err(unsupported( + "query of a dynamic container element dimension", + )); + } + if matches!(target.layout.kind, ContainerKind::Associative { .. }) && name.spelling != "$size" { + return Err(unsupported("associative bound query")); + } + let size = || -> Converted { + Ok(call( + ContainerOp::Size, + target.layout, + vec![expression_binding::value(base, native, tree, dims)?], + )) + }; + Ok(Some(match name.spelling.as_str() { + "$size" => size()?, + "$left" | "$low" => Expr::Literal("32'sd0".into()), + "$increment" => Expr::Literal("32'shffffffff".into()), + _ => Expr::Binary { + left: Box::new(size()?), + op: BinaryOp::Sub, + right: Box::new(Expr::Literal("1".into())), + }, + })) +} + +pub(super) fn set( + left: ExprId, + right: ExprId, + op: &str, + nonblocking: bool, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted> { + let native = tree.declarations(); + let ExprKind::Select { + expression, + dimension, + } = &native.expression(left).kind + else { + return Ok(None); + }; + let Some(target) = native_type(*expression, native, dims) else { + return Ok(None); + }; + if op != "=" || nonblocking { + return Err(unsupported( + "compound or nonblocking dynamic element assignment", + )); + } + let index = match dimension.kind { + DimensionKind::Index(index) => index_value(index, *expression, tree, dims, target)?, + DimensionKind::Queue(None) if matches!(target.layout.kind, ContainerKind::Queue { .. }) => { + Expr::Binary { + left: Box::new(call( + ContainerOp::Size, + target.layout, + vec![expression_binding::value(*expression, native, tree, dims)?], + )), + op: BinaryOp::Sub, + right: Box::new(Expr::Literal("1".into())), + } + } + _ => return Err(unsupported("dynamic element slice assignment")), + }; + Ok(Some(Stmt::Eval(call( + ContainerOp::Set, + target.layout, + vec![ + expression_binding::value(*expression, native, tree, dims)?, + index, + element_value(right, tree, dims, target)?, + ], + )))) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn unsupported_container_forms_fail_before_lowering() { + for (source, expected) in [ + ("module Top; bit[127:0] a[]; endmodule", "wider than 64"), + ("module Top; int a[][]; endmodule", "multidimensional"), + ("module Top; int a[*]; endmodule", "wildcard"), + ( + "module Top; int a[string]; initial a[123] = 7; endmodule", + "requires a string", + ), + ( + "module Top; int q[$], value; initial value = q.push_back(7); endmodule", + "void container", + ), + ( + "module Top; int a[], q[$]; bit value; initial value = a == q; endmodule", + "equivalent array kinds", + ), + ( + "module Top; int a[]; initial a[0] <= 7; endmodule", + "nonblocking", + ), + ( + "module Top; int a[]; initial a[0] += 7; endmodule", + "compound", + ), + ] { + let tree = crate::source_tree::parse_source(source, Path::new("rejected_container.sv")) + .unwrap(); + let error = Source::from_syntax(&tree).unwrap_err().to_string(); + assert!(error.contains(expected), "{source}: {error}"); + } + } + + #[test] + fn typedef_container_metadata_survives_discovery() { + let tree = crate::source_tree::parse_source( + "module Top; typedef bit[7:0] queue_t[$]; queue_t q; endmodule", + Path::new("container.sv"), + ) + .unwrap(); + let source = Source::from_syntax(&tree).unwrap(); + let q = source.modules()[0] + .signals() + .iter() + .find(|s| s.name() == "q") + .unwrap(); + assert!(q.r#type().container.is_some(), "{:?}", q.r#type()); + let tree = crate::source_tree::parse_source("module Top; bit[7:0] a[] = new[2]; typedef bit[7:0] queue_t[$]; queue_t q; initial begin automatic bit[7:0] b[] = new[3]; q.push_back(9); a[1]=7; b[2]=8; if(a.size()==2 && b.size()==3 && q[0]==9)begin end end endmodule", Path::new("container.sv")).unwrap(); + Source::from_syntax(&tree).unwrap(); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index faf895bc6d8..9fe31e0b168 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -46,6 +46,9 @@ pub(super) fn ports_from_scope( type_aliases, )?, ); + if ty.container.is_some() { + return Err(unsupported("dynamic container port")); + } let default = native .default .map(|value| { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index a5f17b392a4..a144496dc5d 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -132,7 +132,9 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( port.name().to_string(), VariableDimensions { - randomizable: (!port.r#type().is_enum || port.r#type().enum_values.is_some()) + container: port.r#type().container.clone(), + randomizable: port.r#type().container.is_none() + && (!port.r#type().is_enum || port.r#type().enum_values.is_some()) && port.randomizable, enum_values: port.r#type().enum_values.clone(), real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), @@ -158,7 +160,9 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( signal.name().to_string(), VariableDimensions { - randomizable: (!signal.r#type().is_enum || signal.r#type().enum_values.is_some()) + container: signal.r#type().container.clone(), + randomizable: signal.r#type().container.is_none() + && (!signal.r#type().is_enum || signal.r#type().enum_values.is_some()) && !signal.is_net() && !signal.is_const, enum_values: signal.r#type().enum_values.clone(), @@ -354,6 +358,7 @@ fn extend_variable_dimensions_from_const_env( } let packed_ranges = ranges.split_off(unpacked); let ty = Type { + container: None, is_enum: false, enum_values: None, kind: TypeKind::Logic, @@ -369,6 +374,7 @@ fn extend_variable_dimensions_from_const_env( }; let mut shape = procedural::dimensions_from_type(&ty); if let Some(existing) = context.get(name) { + shape.container = existing.container.clone(); shape.randomizable = existing.randomizable; shape.enum_values = existing.enum_values.clone(); shape.members = existing.members.clone(); @@ -538,6 +544,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP ( parameter.name.clone(), VariableDimensions { + container: None, randomizable: true, enum_values: None, real: false, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index a546b1d4a84..bc9d6de712d 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -138,10 +138,7 @@ fn type_with_dimensions( tree: &AnalysisContext<'_>, context: &PackedDimensions, ) -> Converted { - Ok(types::type_with_unpacked_ranges( - ty, - constant_binding::bind_unpacked_ranges(dimensions, tree, context)?, - )) + containers::with_dimensions(ty, dimensions, tree, context) } fn shape(context: &mut PackedDimensions, name: String, ty: &Type, local: bool) { let value = procedural::dimensions_from_type(ty); @@ -1000,6 +997,6 @@ mod tests { width(&tree.state, context.get("ordinary").unwrap(), &context), Some(32) ); - assert!(context.get("dyn").is_none()); + assert!(context.get("dyn").unwrap().container.is_some()); } } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index dc6bc26f503..f080a738c02 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -44,6 +44,9 @@ pub(super) fn expression( LValue::Ident(name) => dimensions.get(name), _ => None, }; + if let Some(target) = shape.and_then(|shape| shape.container.as_deref()) { + return containers::assignment(root, tree, dimensions, target); + } // `new` creates an object of the class of the variable or of the // element of an array of handles (IEEE 1800-2023 8.7). let class = match lhs { 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 c1865d46b5e..c7416bb7102 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -296,6 +296,10 @@ pub(in crate::ast) fn bind_value( )); } } + if let Some(value) = containers::value(id, native, tree, dimensions, false)? { + values.push(value); + continue; + } if let Some(call) = objects::rand_mode_call(tree, id, native, dimensions, false)? { values.push(call); continue; diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index fddf7e40f44..86aae92e3b1 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -38,7 +38,11 @@ pub(in crate::ast) fn native_class( && let ExprKind::Name(name) = &native.expression(ungroup(*expression, native)).kind { let ty = dimensions.get(&instances::normalize_identifier(&name.spelling))?; - return ty.class.clone().filter(|_| !ty.unpacked.is_empty()); + return ty + .container + .as_ref() + .and_then(|ty| ty.element.class().map(str::to_owned)) + .or_else(|| ty.class.clone().filter(|_| !ty.unpacked.is_empty())); } if let ExprKind::Name(name) = &expression.kind { let name = instances::normalize_identifier(&name.spelling); @@ -136,7 +140,7 @@ fn named_class( if let Some(aliased) = dimensions .type_aliases .get(&class) - .and_then(|ty| ty.class.clone()) + .and_then(|ty| ty.class().map(str::to_owned)) { return Ok(Some(aliased)); } @@ -176,7 +180,7 @@ fn named_class( .get(&classes::specializations::scope_key(&class)) }) .or_else(|| dimensions.type_aliases.get(&name)) - .and_then(|ty| ty.class.clone()) + .and_then(|ty| ty.class().map(str::to_owned)) { return Ok(Some(class)); } 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 d8002410748..746009e9a0d 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -32,8 +32,11 @@ pub(in crate::ast) fn string_value(expr: &Expr, dimensions: &PackedDimensions) - Expr::Call { callee: Callee::Object(op), .. - } => matches!(**op, crate::system_functions::ObjectOp::Load(field) - if field.handle == Some(crate::system_functions::HandleProperty::String)), + } => { + matches!(**op, crate::system_functions::ObjectOp::Load(field) + if field.handle == Some(crate::system_functions::HandleProperty::String)) + || matches!(**op, ObjectOp::Container { op: ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack, layout } if layout.handle == Some(crate::system_functions::HandleProperty::String)) + } Expr::Mux { then_expr, else_expr, @@ -131,6 +134,16 @@ pub(in crate::ast) fn native_string( dimensions: &PackedDimensions, ) -> bool { match &native.expression(ungroup(id, native)).kind { + ExprKind::Select { expression, .. } + if containers::native_type(*expression, native, dimensions).is_some() => + { + containers::native_type(*expression, native, dimensions).is_some_and(|ty| { + ty.layout.handle == Some(crate::system_functions::HandleProperty::String) + }) + } + ExprKind::Call { expression, .. } if matches!(&native.expression(*expression).kind, ExprKind::Member { expression: base, name, .. } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") && containers::native_type(*base, native, dimensions).is_some_and(|ty| ty.layout.handle == Some(crate::system_functions::HandleProperty::String))) => { + true + } ExprKind::Name(name) if dimensions .get(&instances::normalize_identifier(&name.spelling)) diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs index 0804dd07841..d43909e15f2 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs @@ -158,6 +158,7 @@ impl CallSites for Type { members, signed_element_depth: _, class: _, + container: _, } = self; packed_ranges.call_sites(visit); unpacked_ranges.call_sites(visit); @@ -185,6 +186,7 @@ impl CallSites for UnpackedRange { impl CallSites for VariableDimensions { fn call_sites(&self, visit: &mut dyn FnMut(usize)) { let VariableDimensions { + container: _, randomizable: _, enum_values: _, real: _, 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 6a2b2ac2a71..19bba63f9ca 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -74,6 +74,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - result.insert( name.to_string(), VariableDimensions { + container: None, randomizable: true, enum_values: None, real: false, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 38bccf00a86..1853cdc01ad 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -475,6 +475,7 @@ fn pattern_items( left.min(right), left.max(right), VariableDimensions { + container: None, real: false, string: false, class: None, @@ -498,6 +499,7 @@ fn pattern_items( left.min(right), left.max(right), VariableDimensions { + container: None, real: false, string: false, class: None, @@ -512,6 +514,7 @@ fn pattern_items( 0, count as i128 - 1, VariableDimensions { + container: None, randomizable: true, enum_values: None, real: false, diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index b0a1da41272..973cf6b8c23 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -65,6 +65,7 @@ fn pattern_value( if let Some((dimension, rest)) = shape.unpacked.split_first() { let (_, _, count) = dimension_bounds(state, &dimension.left, &dimension.right, dims)?; let element = VariableDimensions { + container: None, real: false, string: false, class: None, @@ -140,6 +141,7 @@ pub(super) fn assignment_value( Some(( &dim.width, VariableDimensions { + container: None, unpacked: rest.to_vec(), ..shape.clone() }, @@ -150,6 +152,7 @@ pub(super) fn assignment_value( Some(( &dim.width, VariableDimensions { + container: None, packed: rest.to_vec(), signed: shape.signed_element_depth == Some(1), signed_element_depth: shape diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 373fe5f90db..8d0254a853d 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -105,6 +105,7 @@ fn select<'a>( if let Some((dim, rest)) = shape.unpacked.split_first() { let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { + container: None, real: false, string: false, class: None, @@ -136,6 +137,7 @@ fn select<'a>( { let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { + container: None, randomizable: true, enum_values: None, real: false, @@ -246,6 +248,7 @@ fn select<'a>( let width = shape_width(state, &shape, dims) .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { + container: None, randomizable: true, enum_values: None, real: false, @@ -391,6 +394,7 @@ pub(in crate::ast) fn bind_native( { let (_, _, count) = dimension_bounds(&tree.state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { + container: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 56bbd57c002..594ed4bed04 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -11,6 +11,7 @@ mod assertions; mod control; mod final_procedures; mod foreach; +use foreach::ForeachLoop; mod randomization; pub(super) mod timed_tasks; mod timing; @@ -75,7 +76,9 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { /// The packed and unpacked shape of a declared type, as selects see it. pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { - randomizable: !r#type.is_enum || r#type.enum_values.is_some(), + container: r#type.container.clone(), + randomizable: r#type.container.is_none() + && (!r#type.is_enum || r#type.enum_values.is_some()), enum_values: r#type.enum_values.clone(), real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(r#type.kind(), TypeKind::String), @@ -117,6 +120,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - /// The `int` type of a loop variable declared by `foreach`. pub(super) fn int_type() -> Type { Type { + container: None, is_enum: false, enum_values: None, kind: TypeKind::Bit, @@ -504,6 +508,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { native: (celox_sv_syntax::ExprId, celox_sv_syntax::ExprId), ) -> Result { let (left, right) = native; + if let Some(mut stmt) = + containers::set(left, right, op, nonblocking, self.tree, &self.dims)? + { + if let Stmt::Eval(expr) = &mut stmt { + self.rename_expr(expr); + } + return Ok(stmt); + } if let Some(parts) = self.concat_lvalue(left)? { if op != "=" { return Err(unsupported("compound assignment to a concatenation")); @@ -1187,6 +1199,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); + if let Some(mut value) = containers::value(root, native, self.tree, &self.dims, true)? { + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } if let celox_sv_syntax::ExprKind::Call { expression, arguments, @@ -1555,7 +1571,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { &mut self, array: String, variables: Vec>, - ) -> Result, AnalyzerError> { + ) -> Result, AnalyzerError> { let dimensions = self .dims .get(&array) @@ -1585,12 +1601,79 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let right = eval_ast_const_expr(&self.tree.state, right, &self.dims.const_env) .ok_or_else(|| unsupported("foreach bound"))?; let name = self.declare(&variable, int_type()); - loops.push((name, left, right)); + loops.push(ForeachLoop::Static(name, left, right)); } Ok(loops) } - fn fold_foreach(loops: Vec<(String, i128, i128)>, mut body: Vec) -> Vec { - for (name, left, right) in loops.into_iter().rev() { + fn fold_foreach(loops: Vec, mut body: Vec) -> Vec { + for bound in loops.into_iter().rev() { + let (name, left, right) = match bound { + ForeachLoop::Static(name, left, right) => (name, left, right), + ForeachLoop::Container { + array, + index, + layout, + status, + } => { + let index_expr = Expr::Ident(index.clone()); + let (init, condition, step) = if let Some(status) = status { + let call = |op| { + containers::call(op, layout, vec![array.clone(), index_expr.clone()]) + }; + ( + vec![ + Stmt::Local { + name: index, + init: None, + }, + Stmt::Local { + name: status.clone(), + init: Some(call(ContainerOp::First)), + }, + ], + Expr::Ident(status.clone()), + vec![Stmt::Assign { + lhs: LValue::Ident(status), + rhs: call(ContainerOp::Next), + nonblocking: false, + }], + ) + } else { + ( + vec![Stmt::Local { + name: index.clone(), + init: Some(Expr::Literal("0".into())), + }], + Expr::Binary { + left: Box::new(index_expr.clone()), + op: BinaryOp::Lt, + right: Box::new(containers::call( + ContainerOp::Size, + layout, + vec![array], + )), + }, + vec![Stmt::Assign { + lhs: LValue::Ident(index), + rhs: Expr::Binary { + left: Box::new(index_expr), + op: BinaryOp::Add, + right: Box::new(Expr::Literal("1".into())), + }, + nonblocking: false, + }], + ) + }; + body = vec![Stmt::Loop { + kind: LoopKind::For, + init, + condition: Some(condition), + step, + body, + }]; + continue; + } + }; let index = Expr::Ident(name.clone()); let (compare, step) = if left <= right { (BinaryOp::Le, BinaryOp::Add) diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index e9807660083..3a593df27fa 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -63,7 +63,7 @@ enum Job { start: usize, }, Foreach { - loops: Vec<(String, i128, i128)>, + loops: Vec, start: usize, }, /// The end of the statement an `@*` controls, which starts at `start` diff --git a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs index 34a4139b078..546d1691293 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs @@ -2,11 +2,21 @@ use super::*; use celox_sv_syntax::{ExprKind, ForeachHeader}; +pub(super) enum ForeachLoop { + Static(String, i128, i128), + Container { + array: Expr, + index: String, + layout: ContainerLayout, + status: Option, + }, +} + impl BodyBuilder<'_, '_, '_> { pub(super) fn native_foreach_indices( &mut self, header: &ForeachHeader, - ) -> Result, AnalyzerError> { + ) -> Result, AnalyzerError> { let native = self.tree.declarations(); let mut array = header.array; let mut unit_member = None; @@ -26,6 +36,46 @@ impl BodyBuilder<'_, '_, '_> { _ => return Err(unsupported("foreach array")), } }; + if let Some(container) = self + .dims + .get(&array) + .and_then(|shape| shape.container.clone()) + { + let [Some(variable)] = header.variables.as_slice() else { + return Err(unsupported("one-dimensional container foreach index")); + }; + let mut array = Expr::Ident(array); + self.rename_expr(&mut array); + let mut index_type = int_type(); + let status = if let ContainerKind::Associative { + key_width, + signed, + string, + } = container.layout.kind + { + index_type = if string { + type_binding::builtin_type("string", None).expect("string is a builtin type") + } else { + let mut ty = int_type(); + ty.is_signed = signed; + ty.packed_ranges[0].left = ConstExpr::Literal((key_width - 1).to_string()); + ty + }; + Some(self.declare("$celox_foreach_status", int_type())) + } else { + None + }; + let index = self.declare( + &instances::normalize_identifier(&variable.spelling), + index_type, + ); + return Ok(vec![ForeachLoop::Container { + array, + index, + layout: container.layout, + status, + }]); + } let variables = header .variables .iter() diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index e327fc8841d..75fa8e64841 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -12,19 +12,14 @@ mod aggregates; pub(super) mod binding; pub(super) use binding::{bind, expression_type}; -/// The historical constructed-declarator path retains ordinary siblings and -/// does not allocate dynamic arrays or construct class objects. -/// Whether a variable of a declaration of `data_type` is stored in state -/// memory: not a dynamic array, and not constructed by `new` unless it is a -/// class handle (IEEE 1800-2023 8.7), such as a covergroup instance. +/// Whether this declarator denotes a supported variable rather than a +/// constructed non-variable declaration (such as a covergroup instance). pub(super) fn ordinary_variable( variable: &celox_sv_syntax::VariableDeclarator, data_type: celox_sv_syntax::TypeId, native: &celox_sv_syntax::Declarations, ) -> 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")) - || names_class(data_type, native)) + !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. @@ -105,10 +100,10 @@ pub(super) fn local_signals( if selected_name.is_some_and(|selected| selected != name) { continue; } - let ty = types::type_with_unpacked_ranges( - base.clone(), - constant_binding::bind_unpacked_ranges(&variable.dimensions, tree, &context)?, - ); + let ty = containers::with_dimensions(base.clone(), &variable.dimensions, tree, &context)?; + if declaration.constant && ty.container.is_some() { + return Err(unsupported("const dynamic container")); + } let mut signal = Signal::new(name, ty); signal.is_const = declaration.constant; signals.push(signal); @@ -144,10 +139,10 @@ pub(super) fn net_signals( if selected_name.is_some_and(|selected| selected != name) { continue; } - let ty = types::type_with_unpacked_ranges( - base.clone(), - constant_binding::bind_unpacked_ranges(&variable.dimensions, tree, &context)?, - ); + let ty = containers::with_dimensions(base.clone(), &variable.dimensions, tree, &context)?; + if ty.container.is_some() { + return Err(unsupported("dynamic container net")); + } signals .push(Signal::new_net(name, ty).with_unresolved_net(declaration.net_type == "uwire")); } @@ -302,10 +297,7 @@ pub(super) fn alias_signals( if selected_name.is_some_and(|selected| selected != name) { continue; } - let ty = types::type_with_unpacked_ranges( - base.clone(), - constant_binding::bind_unpacked_ranges(&variable.dimensions, tree, &context)?, - ); + let ty = containers::with_dimensions(base.clone(), &variable.dimensions, tree, &context)?; signals.push(Signal::new(name, ty)); } Ok(signals) 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 d83a2fee5a8..b3d1adecaaf 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -403,7 +403,7 @@ fn class_scope( .get(&super::super::classes::specializations::scope_key(&class)) }) .or_else(|| context.type_aliases.get(&name)) - .and_then(|ty| ty.class.clone()) + .and_then(|ty| ty.class().map(str::to_owned)) { return Ok(Some(class)); } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs b/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs index 02d2de65314..26786420e84 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs @@ -56,6 +56,9 @@ pub(in crate::ast) fn subroutine_formals( previous_type = Some(ty.clone()); let unpacked = constant_binding::bind_unpacked_ranges(&port.dimensions, tree, context)?; ty = type_with_unpacked_ranges(ty, unpacked); + if ty.container.is_some() { + return Err(unsupported("dynamic container subroutine parameter")); + } result.push(( instances::normalize_identifier(&name.spelling), direction, diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 22ed86204db..44c3f36b55b 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -89,14 +89,8 @@ fn type_aliases_in_scope( continue; }; let context = PackedDimensions::new(HashMap::default(), const_env, &aliases); - let ty = type_with_unpacked_ranges( - base, - constant_binding::bind_unpacked_ranges( - &alias.dimensions, - syntax_tree, - &context, - )?, - ); + let ty = + containers::with_dimensions(base, &alias.dimensions, syntax_tree, &context)?; aliases.insert(instances::normalize_identifier(&alias.name.spelling), ty); } _ => {} diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 86a36d7a8a7..c79ea49eaeb 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -8,8 +8,8 @@ pub use crate::procedural::{ SystemTaskArg, }; pub use crate::system_functions::{ - ArrayQuery, Callee, HandleProperty, MemoryFormat, ObjectField, ObjectOp, Radix, Severity, - StringOp, SystemFunction, SystemTask, VcdTask, + ArrayQuery, Callee, ContainerKind, ContainerLayout, ContainerOp, HandleProperty, MemoryFormat, + ObjectField, ObjectOp, Radix, Severity, StringOp, SystemFunction, SystemTask, VcdTask, }; /// A procedural statement of the analyzed IR. diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 9a1ce737663..0ee78a1655e 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -821,11 +821,85 @@ impl ObjectField { } } +/// Storage and conversion contract for a one-dimensional value container. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ContainerLayout { + pub kind: ContainerKind, + pub width: u32, + pub signed: bool, + pub two_state: bool, + pub handle: Option, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ContainerKind { + Dynamic, + Queue { + capacity: u32, + }, + Associative { + key_width: u32, + signed: bool, + string: bool, + }, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ContainerOp { + Equal, + CaseEqual, + New, + Literal, + Convert, + Size, + Get, + Set, + Clear, + Delete, + Insert, + PushFront, + PushBack, + PopFront, + PopBack, + Exists, + First, + Last, + Next, + Prev, +} +impl ContainerOp { + pub fn mutates(self) -> bool { + matches!( + self, + Self::Set + | Self::Clear + | Self::Delete + | Self::Insert + | Self::PushFront + | Self::PushBack + | Self::PopFront + | Self::PopBack + ) + } + pub fn result_type(self, layout: ContainerLayout) -> (usize, bool) { + match self { + Self::Equal | Self::CaseEqual => (1, false), + Self::Get | Self::PopFront | Self::PopBack => (layout.width as usize, layout.signed), + Self::Size | Self::Exists | Self::First | Self::Last | Self::Next | Self::Prev => { + (32, true) + } + _ => (32, false), + } + } +} + /// 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 { + Container { + op: ContainerOp, + layout: ContainerLayout, + }, /// A new object of `class` with `size` zeroed bytes, whose handle /// properties are at the given offsets. New { @@ -864,9 +938,22 @@ pub enum ObjectOp { } impl ObjectOp { + /// Memory arguments changed by a container operation, including traversal's ref index. + pub fn writes_argument(&self, position: usize) -> bool { + match self { + Self::Container { op, .. } if op.mutates() => position == 0, + Self::Container { + op: ContainerOp::First | ContainerOp::Last | ContainerOp::Next | ContainerOp::Prev, + .. + } => position == 1, + _ => false, + } + } + /// The width and signedness of the result. pub fn result_type(&self) -> (usize, bool) { match self { + Self::Container { op, layout } => op.result_type(*layout), Self::Random | Self::RandomCyclic { .. } => (64, false), Self::Seed | Self::Check(_) @@ -885,6 +972,7 @@ impl ObjectOp { impl fmt::Display for ObjectOp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { + Self::Container { .. } => "container operation", Self::New { .. } => "new", Self::Load(_) => "property read", Self::Store(_) => "property write", diff --git a/crates/celox-sv-syntax/src/parser/expressions.rs b/crates/celox-sv-syntax/src/parser/expressions.rs index 3882f28aa80..1d1ed656c0c 100644 --- a/crates/celox-sv-syntax/src/parser/expressions.rs +++ b/crates/celox-sv-syntax/src/parser/expressions.rs @@ -1354,6 +1354,15 @@ impl Parser<'_> { } Job::Concat { start, minimum } => { self.expect("{")?; + if self.eat("}") { + self.tail( + &mut jobs, + start, + minimum, + ExprKind::Concatenation(Vec::new()), + )?; + continue; + } if matches!(self.peek(), "<<" | ">>") { let operator = self.peek().to_owned(); self.at += 1; diff --git a/crates/celox-sv-syntax/src/parser/procedures.rs b/crates/celox-sv-syntax/src/parser/procedures.rs index 1cee7fd6b3d..1fafa32b459 100644 --- a/crates/celox-sv-syntax/src/parser/procedures.rs +++ b/crates/celox-sv-syntax/src/parser/procedures.rs @@ -871,13 +871,37 @@ impl Parser<'_> { origin: token.origin, }; self.at += 1; - if self.eat("[") { - self.expression(0)?; + if self.peek() == "[" { + let callee = self.node(start, ExprKind::Name(name))?; + let dimension_start = self.at; + self.expect("[")?; + let size = self.expression(0)?; self.expect("]")?; + let array = self.node( + start, + ExprKind::Select { + expression: callee, + dimension: Box::new(Dimension { + kind: DimensionKind::Index(size), + tokens: self.range(dimension_start), + }), + }, + )?; if self.eat("(") { - self.expression(0)?; + let value = self.expression(0)?; self.expect(")")?; + return self.node( + start, + ExprKind::Call { + expression: array, + arguments: vec![Argument { + name: None, + value: Some(value), + }], + }, + ); } + return Ok(array); } else if self.peek() == "(" { // A class constructor call keeps its arguments (8.7). let callee = self.node(start, ExprKind::Name(name))?; diff --git a/crates/celox-test-suite/src/sv/cases/containers.vtest b/crates/celox-test-suite/src/sv/cases/containers.vtest new file mode 100644 index 00000000000..ef81766ee8d --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/containers.vtest @@ -0,0 +1,388 @@ +(group containers (category types)) + +(case dynamic_resize_and_copy + (source "containers.sv" #" +module Top(output bit [7:0] flags); + bit [31:0] a[], b[]; + initial begin + flags[0] = a.size() == 0; + a = new[3]; + a[0] = 11; a[1] = 22; a[2] = 33; + b = a; + a[0] = 99; + flags[1] = b[0] == 11; + a = new[5](a); + flags[2] = a.size() == 5 && a[0] == 99 && a[2] == 33 && a[4] == 0; + a = new[1](b); + flags[3] = a.size() == 1 && a[0] == 11; + a[-1] = 9; a[3] = 8; + flags[4] = a[0] == 11 && a[-1] == 0 && a[3] == 0; + a.delete(); + flags[5] = a.size() == 0 && b.size() == 3; + a = '{4, 5, 6}; + flags[6] = a.size() == 3 && a[2] == 6; + a = new[0]; + flags[7] = a.size() == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case queue_methods + (source "containers.sv" #" +module Top(output bit [7:0] flags); + int q[$], copy_q[$]; + int value; + initial begin + flags[0] = q.size() == 0; + q.push_back(20); q.push_front(10); q.push_back(30); + q.insert(1, 15); + flags[1] = q.size() == 4 && q[0] == 10 && q[1] == 15 && q[$] == 30; + copy_q = q; + value = q.pop_front(); + flags[2] = value == 10 && q[0] == 15; + value = q.pop_back(); + flags[3] = value == 30 && q.size() == 2; + q.delete(0); + flags[4] = q.size() == 1 && q[0] == 20 && copy_q.size() == 4; + q[$+1] = 40; + flags[5] = q.size() == 2 && q[$] == 40; + q = {3, 4, 5}; + flags[6] = q.size() == 3 && q[1] == 4; + q.delete(); + flags[7] = q.size() == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case queue_argument_side_effects + (source "containers.sv" #" +module Top(output bit [7:0] flags); + int q[$], bounded[$:1], value; + string strings[$]; + initial begin + q = {1, 2}; + q.push_back(q.pop_front()); + flags[0] = q.size() == 2 && q[0] == 2 && q[1] == 1; + q = {1, 2}; + q.push_front(q.pop_back()); + flags[1] = q.size() == 2 && q[0] == 2 && q[1] == 1; + q = {1, 2, 3}; + q.insert(1, q.pop_back()); + flags[2] = q.size() == 3 && q[0] == 1 && q[1] == 3 && q[2] == 2; + q = {1, 10, 20}; + q.insert(q.pop_front(), 7); + flags[3] = q.size() == 3 && q[0] == 10 && q[1] == 7 && q[2] == 20; + q = {1, 10, 20}; + q.delete(q.pop_front()); + flags[4] = q.size() == 1 && q[0] == 10; + q = {1, 10, 20}; + value = q[q.pop_front()]; + flags[5] = value == 20 && q.size() == 2 && q[0] == 10; + bounded = {1, 2}; + bounded.push_back(bounded.pop_front()); + flags[6] = bounded.size() == 2 && bounded[0] == 2 && bounded[1] == 1; + strings = {"first", "last"}; + strings.push_back(strings.pop_front()); + flags[7] = strings.size() == 2 && strings[0] == "last" && strings[1] == "first"; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case queue_argument_four_state + (source "containers.sv" #" +module Top(output bit done); + logic [7:0] q[$]; + initial begin + q = {8'b10xz01zx, 8'bz10x01xz}; + q.push_back(q.pop_front()); + done = q.size() == 2 && q[0] === 8'bz10x01xz && q[1] === 8'b10xz01zx; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq done 1)) + +(case associative_integer_keys + (source "containers.sv" #" +module Top(output bit [7:0] flags); + int a[int], b[int]; + int key, ok; + initial begin + flags[0] = a.num() == 0 && !a.exists(3); + a[3] = 30; a[-2] = 20; a[8] = 80; + flags[1] = a.num() == 3 && a.exists(-2) && a[3] == 30; + ok = a.first(key); + flags[2] = ok == 1 && key == -2; + ok = a.next(key); + flags[3] = ok == 1 && key == 3; + ok = a.last(key); + flags[4] = ok == 1 && key == 8; + ok = a.prev(key); + flags[5] = ok == 1 && key == 3; + b = a; a.delete(3); + flags[6] = !a.exists(3) && b[3] == 30; + a.delete(); key = 77; ok = a.first(key); + flags[7] = a.num() == 0 && ok == 0 && key == 77; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case associative_string_keys + (source "containers.sv" #" +module Top(output bit [3:0] flags); + int a[string]; + string key; + int ok; + initial begin + a["beta"] = 2; a["alpha"] = 1; a["gamma"] = 3; + flags[0] = a.num() == 3 && a["alpha"] == 1 && a.exists("beta"); + ok = a.first(key); + flags[1] = ok && key == "alpha"; + ok = a.next(key); + flags[2] = ok && key == "beta"; + ok = a.last(key); ok = a.next(key); + flags[3] = !ok && key == "gamma"; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case four_state_elements_and_indices + (source "containers.sv" #" +module Top(output bit [7:0] flags); + logic [7:0] a[], q[$]; + integer aa[integer]; + logic [31:0] bad; + int value; + initial begin + bad = 'x; + a = new[2]; + flags[0] = a[0] === 8'hxx; + a[0] = 8'b10xz01zx; + flags[1] = a[0] === 8'b10xz01zx; + a[bad] = 0; + flags[2] = a[0] === 8'b10xz01zx && a[bad] === 8'hxx; + q.push_back(8'bz10x01xz); + flags[3] = q.pop_front() === 8'bz10x01xz; + flags[4] = q.pop_back() === 8'hxx && q.size() == 0; + aa[7] = 42; aa[bad] = 99; + flags[5] = aa.num() == 1 && !aa.exists(bad) && aa[bad] === 'x; + flags[6] = a[-1] === 8'hxx && aa[9] === 'x; + a = new[3](a); + flags[7] = a[0] === 8'b10xz01zx && a[2] === 8'hxx; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case declaration_initializers_and_locals + (source "containers.sv" #" +module Top(output bit done); + bit [7:0] a[] = new[2]; + typedef bit [7:0] queue_t[$]; + queue_t q; + initial begin + automatic bit [7:0] b[] = new[3]; + q.push_back(9); + a[1] = 7; b[2] = 8; + done = a.size() == 2 && a[1] == 7 && b.size() == 3 && b[2] == 8 && q[0] == 9; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case foreach_and_control_flow + (source "containers.sv" #" +module Top(output bit [3:0] flags); + int a[], q[$], aa[int]; + int sum; + initial begin + a = '{10, 20, 30}; + sum = 0; + foreach (a[i]) sum += a[i]; + flags[0] = sum == 60; + q = {2, 4, 6}; + sum = 0; + foreach (q[i]) begin + if (i == 1) continue; + sum += q[i]; + end + flags[1] = sum == 8; + aa[-3] = 30; aa[0] = 10; aa[4] = 40; + sum = 0; + foreach (aa[key]) begin + sum += key + aa[key]; + if (key == 0) break; + end + flags[2] = sum == 37; + a.delete(); sum = 0; + foreach (a[i]) sum += 1; + flags[3] = sum == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case string_elements_and_gc + (source "containers.sv" #" +module Top(output bit [3:0] flags); + string a[], q[$], aa[int], value; + int i; + initial begin + a = new[2]; a[0] = "kept"; + q.push_back(a[0]); aa[7] = "mapped"; + for (i = 0; i < 1100; i++) begin + value.itoa(i); + #1; + end + flags[0] = a[0] == "kept" && a[1] == ""; + value = q.pop_front(); + flags[1] = value == "kept" && q.size() == 0; + flags[2] = aa[7] == "mapped" && aa[8] == ""; + value = q.pop_front(); + flags[3] = value == ""; + end +endmodule +"#) + (top Top) (run_until 1100) (assert_eq flags 15)) + +(case bounded_queue_and_equality + (source "containers.sv" #" +module Top(output bit [7:0] flags); + int q[$:2], a[], b[], unbounded[$]; + initial begin + q = {1, 2, 3, 4}; + flags[0] = q.size() == 3 && q[$] == 3; + q.push_back(9); + flags[1] = q.size() == 3 && q[$] == 3; + q.push_front(9); + flags[2] = q[0] == 9 && q[2] == 2; + q.insert(1, 8); + flags[3] = q[0] == 9 && q[1] == 8 && q[2] == 1; + unbounded = {9, 8, 1}; + a = unbounded; b = a; + flags[4] = a == b && unbounded == q; + a[0] = 77; + flags[5] = a != b && a !== b; + q.delete(); q.insert(-1, 4); q.delete(3); + flags[6] = q.size() == 0; + a = {}; b = {}; + flags[7] = a === b; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case four_state_container_equality + (source "containers.sv" #" +module Top(output bit [3:0] flags); + logic [3:0] a[], b[]; + initial begin + a = '{4'b10xz}; b = a; + flags[0] = a === b; + flags[1] = (a == b) === 1'bx; + b[0] = 4'b11xz; + flags[2] = (a == b) === 1'b0; + a = {}; b = {}; + flags[3] = (a == b) === 1'b1; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case equal_updates_preserve_event_waits + (source "containers.sv" #" +module Top(output bit done); + int q[$], a[], count, before_count; + initial begin + q = {1}; a = '{2}; + #1 before_count = count; + q[0] = 1; a[0] = 2; + #1 q = {1}; a = '{2}; + #1 done = count == before_count; + end + always @(q or a) count = count + 1; +endmodule +"#) + (top Top) (run_until 3) (assert_eq done 1)) + +(case runtime_queries_and_traversal_conversion + (source "containers.sv" #" +module Top(output bit [7:0] flags); + bit [31:0] a[]; + int q[$], aa[int]; + byte key; + int status; + initial begin + flags[0] = $size(a) == 0 && $right(a) == -1 && $left(a) == 0; + a = new[3]; q = {1, 2}; + flags[1] = $size(a) == 3 && $high(q) == 1 && $low(q) == 0; + flags[2] = $increment(a) == -1 && $dimensions(a) == 2 && $unpacked_dimensions(a) == 1; + aa[1000] = 7; + status = aa.first(key); + flags[3] = status == -1 && key == -24; + flags[4] = $size(aa) == 1; + a[64'h100000000] = 99; + flags[5] = a[0] == 0 && a[64'h100000000] == 0; + q[$] = 8; + flags[6] = q[1] == 8 && q.size() == 2; + flags[7] = aa.exists(1000) && aa.num() == 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case object_elements_keep_handle_semantics + (source "containers.sv" #" +module Top(output bit [3:0] flags); + class Cell; + int value; + endclass + Cell q[$], a[], original, copy_handle; + initial begin + original = new; original.value = 7; + q.push_back(original); a = new[1]; a[0] = original; + copy_handle = q[0]; copy_handle.value = 9; + flags[0] = original.value == 9; + copy_handle = a[0]; + flags[1] = copy_handle == original && copy_handle.value == 9; + copy_handle = q.pop_front(); + flags[2] = copy_handle == original && q.size() == 0; + a = new[2](a); copy_handle = a[1]; + flags[3] = copy_handle == null && $dimensions(a) == 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case string_associative_foreach + (source "containers.sv" #" +module Top(output bit [2:0] flags); + int entries[string]; + string visited; + int total; + initial begin + entries["beta"] = 2; + entries["alpha"] = 1; + entries["gamma"] = 3; + visited = ""; + total = 0; + foreach (entries[key]) begin + visited = {visited, key}; + total += entries[key]; + end + flags[0] = total == 6; + flags[1] = visited == "alphabetagamma"; + entries.delete(); + foreach (entries[key]) total += 100; + flags[2] = total == 6; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 7)) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 7ef7a5106c3..14c6521163e 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -7,6 +7,10 @@ pub(super) struct Group { } pub(super) const GROUPS: &[Group] = &[ + Group { + file: "src/sv/cases/containers.vtest", + text: include_str!("containers.vtest"), + }, Group { file: "src/sv/cases/fork_control.vtest", text: include_str!("fork_control.vtest"), diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index c65ea6a9156..8fc631769e5 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -44,7 +44,9 @@ pub enum StateError { #[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")] + #[error( + "state files do not record class objects or dynamic containers; `{0}` holds one, use a checkpoint instead" + )] Objects(String), } diff --git a/crates/celox/tests/frontends/systemverilog/containers.rs b/crates/celox/tests/frontends/systemverilog/containers.rs new file mode 100644 index 00000000000..693181a3894 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/containers.rs @@ -0,0 +1,60 @@ +use super::*; + +sv_backends! { + fn queue_argument_side_effects(sim) { @case "containers::queue_argument_side_effects"; } + fn queue_argument_four_state(sim) { @case "containers::queue_argument_four_state"; } + fn string_associative_foreach(sim) { @case "containers::string_associative_foreach"; } + fn object_elements_keep_handle_semantics(sim) { @case "containers::object_elements_keep_handle_semantics"; } + fn runtime_queries_and_traversal_conversion(sim) { @case "containers::runtime_queries_and_traversal_conversion"; } + fn equal_updates_preserve_event_waits(sim) { @case "containers::equal_updates_preserve_event_waits"; } + fn bounded_queue_and_equality(sim) { @case "containers::bounded_queue_and_equality"; } + fn four_state_container_equality(sim) { @case "containers::four_state_container_equality"; } + fn string_elements_and_gc(sim) { @case "containers::string_elements_and_gc"; } + fn foreach_and_control_flow(sim) { @case "containers::foreach_and_control_flow"; } + fn dynamic_resize_and_copy(sim) { @case "containers::dynamic_resize_and_copy"; } + fn queue_methods(sim) { @case "containers::queue_methods"; } + fn associative_integer_keys(sim) { @case "containers::associative_integer_keys"; } + fn associative_string_keys(sim) { @case "containers::associative_string_keys"; } + fn four_state_elements_and_indices(sim) { @case "containers::four_state_elements_and_indices"; } + fn declaration_initializers_and_locals(sim) { @case "containers::declaration_initializers_and_locals"; } +} + +sv_backends! { + fn container_checkpoints_restore_all_three_kinds(sim) { + @setup { + let source = r#"module Top(output int value); + timeunit 1ps / 1ps; + int a[], q[$], aa[int]; + initial begin + a = new[1]; a[0] = 1; q.push_back(2); aa[0] = 3; + #10 value = a[0] + q[0] + aa[0]; + #10 a[0] = 4; q.push_back(5); aa[0] = 6; + #10 value = a[0] + q[1] + aa[0]; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("container_checkpoint.sv"))], "Top"); + sim.run_until(5).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + let bytes = checkpoint.to_bytes().unwrap(); + // SAFETY: bytes came directly from this simulator's checkpoint. + let persisted = unsafe { sim.checkpoint_from_bytes(&bytes) }.unwrap(); + let value = sim.signal("value"); + sim.run_until(40).unwrap(); + assert_eq!(sim.get(value), BigUint::from(15u8)); + sim.restore(&persisted).unwrap(); + sim.run_until(15).unwrap(); + assert_eq!(sim.get(value), BigUint::from(6u8)); + sim.run_until(40).unwrap(); + assert_eq!(sim.get(value), BigUint::from(15u8)); + } +} + +sv_backends! { + fn negative_dynamic_array_size_is_a_runtime_error(sim) { + @setup { let source = "module Top; int a[]; initial a = new[-1]; endmodule"; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("negative_array.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("negative dynamic array size"), "{error}"); + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 541cfe4ae39..43ac52d9cff 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -250,3 +250,6 @@ mod unions; #[path = "frontends/systemverilog/tagged_unions.rs"] mod tagged_unions; + +#[path = "frontends/systemverilog/containers.rs"] +mod containers; diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 1884b55f280..7b5bd6338be 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -31,6 +31,7 @@ synthesis and is tested at the design level. | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | +| Dynamic containers | one-dimensional dynamic arrays, queues (including bounded queues), and associative arrays with integral or string keys; element access, value assignment, equality, `foreach` and built-in container methods. See [dynamic containers](#dynamic-containers) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | | Classes | classes declared in a module, a package or the compilation unit: 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 methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments; shallow copies (`new h`). See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | @@ -328,6 +329,45 @@ 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. +### Dynamic containers + +Dynamic arrays (`T a[]`) support `new[n]`, `new[n](a)`, `size()` and +`delete()` (IEEE 1800-2023 7.5). Queues (`T q[$]`, `T q[$:N]`) support +`size`, `insert`, `delete`, `push_front`, `push_back`, `pop_front` and +`pop_back`, with parentheses. Queue indices may use `$` and `$+1`. +Associative arrays support integral keys up to 64 bits or `string` keys, +`num` / `size`, `exists`, `delete`, and `first` / `last` / `next` / `prev` +(7.8–7.10). Traversal leaves its index unchanged when no key is found. + +Elements may be packed integral values up to 64 bits, strings or class +handles. Positional assignment patterns and element concatenations construct +sequences; assignments between dynamic arrays and queues copy values and +respect the destination queue's bound. Associative assignment requires the +same key type. Equality (`==`, `!=`, `===`, `!==`) between equivalent container types compares contents, +including X/Z for four-state elements. `foreach` visits sequence positions +or associative keys in order. Range errors read the element type's default +and ignore writes; unknown indices never create associative entries. + +Containers work in procedural code as module variables or locals. Automatic +local initializers and module declaration initializers may allocate with +`new[]`. Checkpoints, including serialized checkpoints, preserve contents; +portable state files require a checkpoint instead. Strings and class objects +held in elements remain reachable during heap collection. Array assignment +copies elements while class handles retain their usual reference semantics. + +Multidimensional containers, elements wider than 64 bits, real elements, +wildcard or class keys, slices, array manipulation methods, keyed patterns, +container operands within concatenations, compound or nonblocking element +assignments, container ports / subroutine parameters / class properties and +const containers remain unsupported. A `new[]` initializer currently requires +another compatible dynamic array or queue; fixed-size arrays are unsupported. +Static local initializers retain the existing constant-initializer restriction. +`$size` queries the current outer dimension. Sequence `$left`, `$right`, +`$low`, `$high`, `$increment`, and dimension counts are also supported. +Queries of element dimensions and associative bounds remain unsupported. +For string-indexed associative arrays, use the `size()` method. Native images +and serialized checkpoints from earlier container versions must be regenerated. + ### Classes {#classes} A class variable holds a handle of an object in the simulator's heap, `null`