From 08bc129afce3ca30e82aac6fb80884bd1cf616aa Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 03:38:47 +0900 Subject: [PATCH 1/2] fix(deps): drop the zstd versions with open RustSec advisories cargo-deny's advisory check has failed on master since 2026-10-27, and on every pull request that changes Cargo.lock: zstd 0.13.3 (RUSTSEC-2026-0391) and zstd-safe 7.2.4 (RUSTSEC-2026-0398, RUSTSEC-2026-0403). zstd 0.13 reached the workspace twice. include-flate (through rust-embed and veryl-std) moves to zstd 0.14.3 in its compatible 0.3.5 release. wasmtime 50 still uses zstd 0.13 for its compilation cache, which Celox never configures, so depend on wasmtime with its default features except `cache` (declared once in the workspace for celox and the WASM backend's tests). Validation: `cargo deny check advisories` passes; workspace check with the WASM and SystemVerilog features; WASM backend tests (7), Veryl counter tests with the WASM runtime and component features (21) and the full SystemVerilog suite (6,555, 20 skipped) pass. Change-Id: Iceb61f93c7efcc6be20ef1e8164aadc6ca4833b8 --- Cargo.lock | 163 +++++++-------------------- Cargo.toml | 6 + crates/celox-backend-wasm/Cargo.toml | 2 +- crates/celox/Cargo.toml | 2 +- 4 files changed, 50 insertions(+), 123 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c62c47dfe3b..426be8bcbd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,12 +220,6 @@ dependencies = [ "backtrace", ] -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - [[package]] name = "base64-simd" version = "0.8.0" @@ -441,7 +435,7 @@ dependencies = [ "serde_json", "tempfile", "test-case", - "thiserror 2.0.21", + "thiserror", "toml", "tracing", "vcd", @@ -502,7 +496,7 @@ dependencies = [ "cranelift-native 0.137.0", "fxhash", "num-bigint", - "thiserror 2.0.21", + "thiserror", "tracing", ] @@ -552,7 +546,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "thiserror 2.0.21", + "thiserror", "toml", "tracing", "tracing-subscriber", @@ -605,7 +599,7 @@ dependencies = [ "miette", "num-bigint", "serde", - "thiserror 2.0.21", + "thiserror", "tracing", ] @@ -617,7 +611,7 @@ dependencies = [ "num-bigint", "serde", "serde_json", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -635,7 +629,7 @@ dependencies = [ "num-bigint", "num-traits", "serde_json", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -653,7 +647,7 @@ dependencies = [ "num-bigint", "num-traits", "tempfile", - "thiserror 2.0.21", + "thiserror", "tracing", "veryl-analyzer", "veryl-metadata", @@ -723,7 +717,7 @@ dependencies = [ "num-bigint", "serde", "tempfile", - "thiserror 2.0.21", + "thiserror", "tracing", "vcd", ] @@ -753,7 +747,7 @@ dependencies = [ "itertools 0.15.0", "num-bigint", "num-traits", - "thiserror 2.0.21", + "thiserror", "tracing", ] @@ -769,7 +763,7 @@ dependencies = [ "num-traits", "serde", "serde_json", - "thiserror 2.0.21", + "thiserror", "tracing", ] @@ -792,7 +786,7 @@ dependencies = [ "fxhash", "miette", "num-bigint", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -863,7 +857,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "thiserror 2.0.21", + "thiserror", "toml", "tracing-subscriber", "veryl-metadata", @@ -989,7 +983,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" dependencies = [ - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -1726,7 +1720,7 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" dependencies = [ - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -1796,16 +1790,6 @@ dependencies = [ "dirs-sys", ] -[[package]] -name = "directories-next" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "339ee130d97a610ea5a5872d2bbb130fdf68884ff09d3028b81bec8a1ac23bbc" -dependencies = [ - "cfg-if", - "dirs-sys-next", -] - [[package]] name = "dirs-sys" version = "0.5.0" @@ -1814,21 +1798,10 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.2", + "redox_users", "windows-sys 0.61.2", ] -[[package]] -name = "dirs-sys-next" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" -dependencies = [ - "libc", - "redox_users 0.4.6", - "winapi", -] - [[package]] name = "displaydoc" version = "0.2.6" @@ -2008,7 +1981,7 @@ checksum = "77be37fdc968866fa4f0cee73e42185e6d4699a761a51a54e6ebc9a3d73ed537" dependencies = [ "lz4_flex", "miniz_oxide", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -2455,9 +2428,9 @@ checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb" [[package]] name = "include-flate" -version = "0.3.4" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48f173716febb1ad596c16ea5637b5f1790ea32de8e627493ff82bc73b0876ce" +checksum = "f677e494e19ac4aa62375916f64b496f6b2655964c7313231c959858608cd9eb" dependencies = [ "include-flate-codegen", "include-flate-compress", @@ -2465,22 +2438,22 @@ dependencies = [ [[package]] name = "include-flate-codegen" -version = "0.3.4" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a7875b62a72ad3f3203cdd8950d4cf9947db036030b974b8b37ceae90c8d8c0" +checksum = "51d3749676b6129ea4cf1e75adfb280a2148f03113806cb68cd7775fdfc65edf" dependencies = [ "include-flate-compress", "proc-macro-error3", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "include-flate-compress" -version = "0.3.4" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44fbb9c5ccb9a5b67b4afa2974c27e5507ea1bf6d22828cef418e4dfaeca51dd" +checksum = "476a7e4feb3325e85ca85565893517e283a1e59d3c9b695c162791dead7f004d" dependencies = [ "libflate", "zstd", @@ -3168,7 +3141,7 @@ dependencies = [ "syntree", "syntree_layout", "tempfile", - "thiserror 2.0.21", + "thiserror", "ts-rs", "ume", ] @@ -3196,7 +3169,7 @@ dependencies = [ "scnr2", "syntree", "syntree_layout", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -3551,17 +3524,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "redox_users" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" -dependencies = [ - "getrandom 0.2.17", - "libredox", - "thiserror 1.0.69", -] - [[package]] name = "redox_users" version = "0.5.2" @@ -3570,7 +3532,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.17", "libredox", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -4077,7 +4039,7 @@ checksum = "24d027955f5f14d526450b6a11ef5aa962761e924dcd092298dd0d1466570565" dependencies = [ "anyhow", "syntree", - "thiserror 2.0.21", + "thiserror", "xml_writer", ] @@ -4174,33 +4136,13 @@ dependencies = [ "unicode-width 0.2.2", ] -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.21", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "thiserror-impl", ] [[package]] @@ -4346,7 +4288,7 @@ version = "12.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8" dependencies = [ - "thiserror 2.0.21", + "thiserror", "ts-rs-macros", ] @@ -4510,7 +4452,7 @@ dependencies = [ "strnum_bitwidth", "strum", "strum_macros", - "thiserror 2.0.21", + "thiserror", "toml", "vcd", "veryl-component-sys", @@ -4553,7 +4495,7 @@ dependencies = [ "serde_json", "serde_regex", "spdx", - "thiserror 2.0.21", + "thiserror", "toml", "url", "uuid", @@ -4581,7 +4523,7 @@ dependencies = [ "regex", "scnr2", "serde", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -4595,7 +4537,7 @@ dependencies = [ "log", "miette", "tempfile", - "thiserror 2.0.21", + "thiserror", "walkdir", ] @@ -4630,7 +4572,7 @@ dependencies = [ "serde_json", "smallvec", "target-lexicon", - "thiserror 2.0.21", + "thiserror", "toml", "twox-hash", "vcd", @@ -4651,7 +4593,7 @@ dependencies = [ "miette", "relative-path", "sourcemap", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -4663,7 +4605,7 @@ dependencies = [ "merkle_hash", "miette", "rust-embed", - "thiserror 2.0.21", + "thiserror", "veryl-path", ] @@ -4934,7 +4876,6 @@ dependencies = [ "wasm-encoder 0.261.0", "wasmparser 0.261.0", "wasmtime-environ 50.0.0", - "wasmtime-internal-cache", "wasmtime-internal-component-macro", "wasmtime-internal-component-util 50.0.0", "wasmtime-internal-core 50.0.0", @@ -5010,26 +4951,6 @@ dependencies = [ "wasmtime-internal-core 50.0.0", ] -[[package]] -name = "wasmtime-internal-cache" -version = "50.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "067440fa60ddd5145840e0335ffe0ab4d908a021932b6844c3ad61570abddfef" -dependencies = [ - "base64", - "directories-next", - "log", - "postcard", - "rustix", - "serde", - "serde_derive", - "sha2 0.10.9", - "toml", - "wasmtime-environ 50.0.0", - "windows-sys 0.61.2", - "zstd", -] - [[package]] name = "wasmtime-internal-component-macro" version = "50.0.0" @@ -5098,7 +5019,7 @@ dependencies = [ "pulley-interpreter 49.0.4", "smallvec", "target-lexicon", - "thiserror 2.0.21", + "thiserror", "wasmparser 0.258.3", "wasmtime-environ 49.0.4", "wasmtime-internal-core 49.0.4", @@ -5124,7 +5045,7 @@ dependencies = [ "pulley-interpreter 50.0.0", "smallvec", "target-lexicon", - "thiserror 2.0.21", + "thiserror", "wasmparser 0.261.0", "wasmtime-environ 50.0.0", "wasmtime-internal-core 50.0.0", @@ -5650,18 +5571,18 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zstd" -version = "0.13.3" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.2.4" +version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" dependencies = [ "zstd-sys", ] diff --git a/Cargo.toml b/Cargo.toml index 3acd3d16c6b..21f7f578215 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,12 @@ description = "Celox HDL Simulator" rust-version = "1.99.1" [workspace.dependencies] +# wasmtime's defaults without `cache`: Celox never configures its compilation +# cache, whose zstd 0.13 dependency has open advisories (RUSTSEC-2026-0391, +# RUSTSEC-2026-0398, RUSTSEC-2026-0403). +wasmtime = { version = "50", default-features = false, features = [ + "anyhow", "async", "backtrace", "gc", "gc-copying", "gc-drc", "gc-null", "wat", "profiling", "parallel-compilation", "cranelift", "pooling-allocator", "demangle", "addr2line", "coredump", "debug-builtins", "runtime", "component-model", "component-model-async", "threads", "stack-switching", "std", "debug", "compile-time-builtins", "wit-parser", +] } # Aplite has an independent release version. aplite = { version = "0.1.0", path = "crates/aplite" } celox = { version = "=0.12.0", path = "crates/celox", default-features = false } # x-release-please-version diff --git a/crates/celox-backend-wasm/Cargo.toml b/crates/celox-backend-wasm/Cargo.toml index 0e6a60491f9..738acdfa9e3 100644 --- a/crates/celox-backend-wasm/Cargo.toml +++ b/crates/celox-backend-wasm/Cargo.toml @@ -19,7 +19,7 @@ wasm-encoder = "0.262" [dev-dependencies] celox-backend-cranelift = { workspace = true } num-bigint = { workspace = true } -wasmtime = "50" +wasmtime = { workspace = true } [lints] workspace = true diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index 12deac9c765..8591d88d79d 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -75,7 +75,7 @@ tracing = { workspace = true } celox-macros = { workspace = true, optional = true } celox-backend-cranelift = { workspace = true, optional = true } celox-backend-arm64 = { workspace = true, optional = true } -wasmtime = { version = "50", optional = true } +wasmtime = { workspace = true, optional = true } [target.'cfg(any(target_arch = "x86_64", target_arch = "aarch64"))'.dependencies] celox-backend-x86 = { workspace = true, optional = true } From 85f9c72d1cd4c3cc65e03d1c5150d4f1b76e753e Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 15:34:58 +0900 Subject: [PATCH 2/2] feat(sv): support $sformatf and $sformat Implement formatting to a string (IEEE 1800-2023 21.3.3). The analyzer binds `$sformatf(format, args...)` as a string operation, so it is typed `string` wherever a string value is valid: assignments, function results, arguments, concatenations and conditional operands. `$sformat(output, format, args...)` assigns the same value to a string variable, a function's return variable or a string class property. A call with conversions is a synchronous host request of the scheduled process. The host renders the format with the `$display` renderer, so every conversion, field width, X/Z digit and `%m` scope matches `$display`, and interns the text as the result. A literal format is fixed at compile time and its `%t` values are scaled as the analyzer scales those of `$display`; a `string` or integral format is read when the call runs and the host scales its `%t` values. A literal without conversions or arguments is a constant. Integral outputs, `%p` and the `$swrite` family remain unsupported. A host request in a later input of a subroutine call would otherwise lose the registers computed for earlier inputs across the suspension, so those inputs are kept, converted to their formals, in temporaries; operands of string, object and container operations are materialized as the heap helpers already do. A cached transitive check finds subroutines that make host requests, including in the defaults of omitted arguments. A format read at run time keeps bytes that are not UTF-8. `$display` now resolves every string-valued argument, not only string identifiers, so a string conditional prints its text. The shared string_format cases compare `$sformatf` and `$sformat` with `$display` on all backends and in a native image. Verilator 5.052 passes all of them (the four-state case is unsupported there); Icarus 13.0 limitations (string conditional crash, class-property output, integral format) and an xezim 0.11.3 integral-format bug are retained with evidence. Change-Id: Ife5fd5bc64ccbecb7a73976fc8b68f22e5216d53 --- crates/celox-design/src/lib.rs | 7 +- crates/celox-frontend-sv/src/lowering.rs | 12 +- crates/celox-frontend-sv/src/lowering/comb.rs | 6 +- crates/celox-frontend-sv/src/lowering/ff.rs | 90 ++++- .../src/lowering/ff/format.rs | 202 +++++++++++ .../src/lowering/ff/strings.rs | 5 + .../src/lowering/procedural.rs | 82 +++++ .../src/ast/expression_binding.rs | 2 +- .../src/ast/expression_binding/direct.rs | 36 ++ .../src/ast/expression_binding/strings.rs | 8 +- .../celox-sv-analyzer/src/ast/procedural.rs | 68 ++++ .../celox-sv-analyzer/src/system_functions.rs | 10 + crates/celox-test-suite/LIMITATIONS.md | 14 +- crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../src/sv/cases/string_format.vtest | 343 ++++++++++++++++++ .../repros/sv_associative_index_cast.json | 29 ++ .../verification/sv/icarus.json | 1 + .../verification/sv/icarus/string_format.json | 144 ++++++++ .../verification/sv/limitations.json | 90 ++++- .../sv/limitations/string-format-icarus.json | 40 ++ .../verification/sv/verilator.json | 1 + .../sv/verilator/string_format.json | 38 ++ .../verification/sv/xezim.json | 1 + .../verification/sv/xezim/string_format.json | 26 ++ .../verification/xezim-review.json | 24 ++ crates/celox/src/simulation.rs | 1 + crates/celox/src/simulator.rs | 1 + crates/celox/src/simulator/host/file_io.rs | 41 ++- crates/celox/src/simulator/host/format.rs | 220 +++++++++++ .../frontends/systemverilog/string_format.rs | 85 +++++ crates/celox/tests/sv_dpi.rs | 34 ++ crates/celox/tests/systemverilog.rs | 2 + docs/guide/systemverilog-reference.md | 23 +- 33 files changed, 1637 insertions(+), 53 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/ff/format.rs create mode 100644 crates/celox-test-suite/src/sv/cases/string_format.vtest create mode 100644 crates/celox-test-suite/verification/repros/sv_associative_index_cast.json create mode 100644 crates/celox-test-suite/verification/sv/icarus/string_format.json create mode 100644 crates/celox-test-suite/verification/sv/limitations/string-format-icarus.json create mode 100644 crates/celox-test-suite/verification/sv/verilator/string_format.json create mode 100644 crates/celox-test-suite/verification/sv/xezim/string_format.json create mode 100644 crates/celox/src/simulator/host/format.rs create mode 100644 crates/celox/tests/frontends/systemverilog/string_format.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index a8e65014c28..5835fadc4a1 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -545,6 +545,8 @@ pub enum HostRequestKind { // Append new variants: native images persist Serde variant indices. /// Services owned by an explicitly invoked testbench kernel. Testbench, + /// Formatting to a string (`$sformatf`). + Format, } impl HostRequestKind { @@ -558,6 +560,7 @@ impl HostRequestKind { Self::Distribution => 5, Self::Process => 6, Self::Testbench => 7, + Self::Format => 8, }; (family << 32) | site as u64 } @@ -572,6 +575,7 @@ impl HostRequestKind { 5 => Self::Distribution, 6 => Self::Process, 7 => Self::Testbench, + 8 => Self::Format, _ => return None, }; Some((family, request as u32)) @@ -2271,6 +2275,7 @@ mod tests { HostRequestKind::Distribution, HostRequestKind::Process, HostRequestKind::Testbench, + HostRequestKind::Format, ] { for site in [0, 1, u32::MAX] { assert_eq!( @@ -2279,7 +2284,7 @@ mod tests { ); } } - for invalid in [0, u32::MAX as u64, 8u64 << 32, 1u64 << 63] { + for invalid in [0, u32::MAX as u64, 9u64 << 32, 1u64 << 63] { assert_eq!(HostRequestKind::decode(invalid), None); } assert_eq!( diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 9abb6bc29b9..9893e99d826 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -96,17 +96,6 @@ struct SvVariable { history_of: Option, } -/// Whether `expr` reads a string variable: after its calls are hoisted, a -/// string-valued argument is the identifier of a variable or temporary. -fn reads_string_variable( - expr: &sv::ir::Expr, - variables: &HashMap, - names: &HashMap, -) -> bool { - matches!(expr, sv::ir::Expr::Ident(name) - if names.get(name).and_then(|id| variables.get(id)).is_some_and(|v| v.value_kind == celox_design::ValueKind::StrRef)) -} - impl SvVariable { fn to_symbolic_variable(&self) -> SymbolicVariable { SymbolicVariable { @@ -3555,6 +3544,7 @@ fn needs_host_request( while let Some((callee, args)) = calls.pop() { match callee { sv::ir::Callee::System(function) if function.is_host_request() => return true, + sv::ir::Callee::String(sv::ir::StringOp::Format { .. }) => return true, sv::ir::Callee::Subroutine(name) => { let Some(subroutine) = module.subroutines().iter().find(|sub| sub.name == name) else { diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 311f4f1bce8..cc62339d02d 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3723,11 +3723,7 @@ impl<'p, 'a> Comb<'p, 'a> { expr.clone() }; let signed = self.expr_signed(&expr); - arg_is_handle.push(reads_string_variable( - &expr, - self.m.variables, - self.m.name_to_id, - )); + arg_is_handle.push(self.m.expr_is_string(&expr)); arg_float_precision.push(floating::precision( &expr, self.m.variables, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index d0a962166cc..b4688e9cd7e 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -11,6 +11,7 @@ mod containers; mod file_io; +mod format; mod fread; mod objects; mod process; @@ -1994,8 +1995,17 @@ impl<'p, 'a> Ff<'p, 'a> { } else { arg_order.to_vec() }; + // A register would not survive a host request in a later actual: + // each actual before the last one that can make a request is kept, as + // its C type, in a temporary until the call. + let last_request = positions.iter().rposition(|&position| { + args.get(position) + .and_then(Option::as_ref) + .is_some_and(|arg| self.m.makes_host_request(arg)) + }); + let mut kept = Vec::new(); // Evaluate actuals in source order, then pass registers in C formal order. - for position in positions { + for (index, position) in positions.into_iter().enumerate() { let argument = import.arguments().get(position).ok_or_else(|| { unsupported(format!("argument position of DPI-C function `{name}`")) })?; @@ -2008,6 +2018,24 @@ impl<'p, 'a> Ff<'p, 'a> { let r#type = argument.r#type(); let arg = self.hoist(arg)?; let value = self.eval(&arg, Some((r#type.width(), r#type.is_signed())))?; + let register = self.dpi_register(value, r#type); + if last_request.is_some_and(|last| index < last) { + let four_state = matches!(self.b.register(®ister), RegisterType::Logic { .. }); + let (temp, name) = + self.m + .temp("dpi_input", r#type.width(), r#type.is_signed(), four_state); + self.store(temp, SIROffset::Static(0), r#type.width(), register); + kept.push((position, name)); + } else { + registers[position] = Some(register); + } + } + for (position, name) in kept { + let r#type = import.arguments()[position].r#type(); + let value = self.eval( + &sv::ir::Expr::Ident(name), + Some((r#type.width(), r#type.is_signed())), + )?; registers[position] = Some(self.dpi_register(value, r#type)); } let registers = registers @@ -2890,11 +2918,35 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(sv::ir::Expr::Ident(name)) } + /// The input `value` of formal `id`, or with `keep` the name of a + /// temporary of the formal's type that holds it across a later host + /// request. + fn kept_input( + &mut self, + id: SourceVarId, + value: RegisterId, + keep: bool, + ) -> Result { + if !keep { + return Ok(value); + } + let formal = self.m.var(id); + let (width, signed, value_kind, float) = + (formal.width, formal.signed, formal.value_kind, formal.float); + let four_state = matches!(self.b.register(&value), RegisterType::Logic { .. }); + let (temp, name) = self.m.temp("input", width, signed, four_state); + let variable = self.m.variables.get_mut(&temp).unwrap(); + variable.value_kind = value_kind; + variable.float = float; + self.store(temp, SIROffset::Static(0), width, value); + Err(name) + } + /// The value of `expr` now, in a temporary of its type. fn keep_argument(&mut self, expr: &sv::ir::Expr) -> Result { let signed = self.expr_signed(expr); let float = floating::precision(expr, self.m.variables, self.m.name_to_id); - let handle = reads_string_variable(expr, self.m.variables, self.m.name_to_id); + let handle = self.m.expr_is_string(expr); let value = self.eval(expr, None)?; let register = self.b.register(&value).clone(); let width = register.width(); @@ -4010,11 +4062,7 @@ impl<'p, 'a> Ff<'p, 'a> { sv::ir::SystemTaskArg::Expr(expr) => { let expr = expr.clone(); let signed = self.expr_signed(&expr); - arg_is_handle.push(reads_string_variable( - &expr, - self.m.variables, - self.m.name_to_id, - )); + arg_is_handle.push(self.m.expr_is_string(&expr)); arg_float_precision.push(floating::precision( &expr, self.m.variables, @@ -4645,7 +4693,24 @@ impl<'p, 'a> Ff<'p, 'a> { Reference::Alias(alias) => aliases.push(*alias), } } - for position in positions { + // An input evaluates into a register, which a host request in a later + // input, a default included, would lose: each input before the last + // one that can make a request is kept, converted to its formal, in a + // temporary until the formals are written. + let last_request = positions.iter().rposition(|&position| { + subroutine.params.get(position).is_some_and(|param| { + param.direction.is_read() + && !param.direction.is_reference() + && args + .get(position) + .cloned() + .flatten() + .or_else(|| param.default.clone()) + .is_some_and(|actual| self.m.makes_host_request(&actual)) + }) + }); + for (index, position) in positions.into_iter().enumerate() { + let keep = last_request.is_some_and(|last| index < last); let param = subroutine .params .get(position) @@ -4730,17 +4795,22 @@ impl<'p, 'a> Ff<'p, 'a> { .alloc(SLTNode::Unary(UnaryOp::ToTwoState, node)) .map_err(slt_error)?; } - inputs.push((id, self.lower_slt(&arena, node)?)); + let value = self.lower_slt(&arena, node)?; + inputs.push((id, self.kept_input(id, value, keep))); } else if !subroutine.persistent_locals.contains(¶m.name) && (self.kernel.is_none() || !subroutine.is_task || subroutine.automatic_locals.contains(¶m.name)) { let value = self.default_reg(id); - inputs.push((id, value)); + inputs.push((id, self.kept_input(id, value, keep))); } } for (id, value) in inputs { + let value = match value { + Ok(value) => value, + Err(name) => self.eval(&sv::ir::Expr::Ident(name), None)?, + }; let width = self.m.var(id).width; let offset = sv_memory_offset(self.m.var(id), 0, width); self.store(id, offset, width, value); diff --git a/crates/celox-frontend-sv/src/lowering/ff/format.rs b/crates/celox-frontend-sv/src/lowering/ff/format.rs new file mode 100644 index 00000000000..eb33264e74e --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/format.rs @@ -0,0 +1,202 @@ +//! Formatting data to a string (IEEE 1800-2023 21.3.3). +//! +//! `$sformatf` is a host request: the host renders the format and its +//! arguments with the formatter of `$display` and returns the result as a +//! string. A literal format is known here; any other format is a value that +//! the host reads as text when the call runs. + +use super::*; +use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue, ValueKind}; + +impl Ff<'_, '_> { + /// The string `$sformatf(args[0], args[1..])` returns, as a temporary. + pub(super) fn format_string( + &mut self, + ticks_per_unit: u64, + args: &[sv::ir::Expr], + ) -> Result { + let (format, values) = args + .split_first() + .ok_or_else(|| unsupported("`$sformatf` without a format"))?; + let template = literal_text(format); + // Text without conversions is its own result. + if values.is_empty() && template.as_deref().is_some_and(|text| !text.contains('%')) { + return self.hoist(&sv::ir::Expr::Call { + callee: sv::ir::Callee::String(sv::ir::StringOp::FromBits), + args: vec![Some(format.clone())], + arg_order: Vec::new(), + }); + } + if self.kernel.is_none() { + return Err(unsupported("`$sformatf` outside a scheduled process")); + } + let mut values = values + .iter() + .cloned() + .map(sv::ir::SystemTaskArg::Expr) + .collect::>(); + if let Some(template) = &template { + // As the analyzer does for `$display`, scale each value that a + // `%t` converts to simulation time units. + scale_time_values(template, &mut values, ticks_per_unit); + prepare_time_operands(self.m, Some(template), &mut values)?; + } + // Each value is captured where it is evaluated, so that a later + // argument's call or host request cannot change it. + let mut inputs = Vec::with_capacity(values.len() + 1); + if template.is_none() { + inputs.push(self.format_input(format)?); + } + for value in &values { + let sv::ir::SystemTaskArg::Expr(value) = value else { + unreachable!("format values are expressions"); + }; + inputs.push(self.format_input(value)?); + } + let (result, name) = self + .m + .temp("format", celox_design::HANDLE_WIDTH, false, false); + self.m + .variables + .get_mut(&result) + .expect("format result") + .value_kind = ValueKind::StrRef; + let site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::Format) + .count() as u32; + // A literal format is the site's text; a run-time format is its first + // argument, and the site keeps the time scale of its `%t` values. + let (operation, text) = match template { + Some(template) => (0, template), + None => (1, ticks_per_unit.to_string()), + }; + self.host_request_sites.push(HostRequestSite { + process: 0, + kind: HostRequestKind::Format, + operation, + args: inputs, + results: vec![HostRequestValue { + value_kind: ValueKind::StrRef, + float_precision: None, + id: result, + width: celox_design::HANDLE_WIDTH, + signed: false, + is_string: false, + }], + strings: vec![text], + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Format, site)) + .map_err(kernel_error)?; + Ok(sv::ir::Expr::Ident(name)) + } + + /// `expr` captured in a temporary that the host reads. A string keeps + /// its handle, which also keeps the string alive until the host reads it. + fn format_input( + &mut self, + expr: &sv::ir::Expr, + ) -> Result, sv::AnalyzerError> { + let expr = if self.m.calls(expr) { + self.hoist(expr)? + } else { + expr.clone() + }; + let value_kind = if self.m.expr_is_string(&expr) { + ValueKind::StrRef + } else { + ValueKind::Bits + }; + let float_precision = floating::precision(&expr, self.m.variables, self.m.name_to_id); + let signed = self.expr_signed(&expr); + let value = self.eval(&expr, None)?; + let width = self.b.register(&value).width(); + let four_state = matches!(self.b.register(&value), RegisterType::Logic { .. }); + let (id, _) = self.m.temp("format_arg", width, signed, four_state); + self.m + .variables + .get_mut(&id) + .expect("format argument") + .value_kind = value_kind; + self.store(id, SIROffset::Static(0), width, value); + Ok(HostRequestValue { + value_kind, + float_precision, + id, + width, + signed, + is_string: false, + }) + } +} + +/// The text of a literal format: its bytes, most significant first, without +/// NUL bytes, as a string literal holds them (IEEE 1800-2023 5.9). +fn literal_text(format: &sv::ir::Expr) -> Option { + let sv::ir::Expr::Literal(text) = format else { + return None; + }; + let literal = sv::typecheck::parse_integral_literal(text)?; + if !literal.mask.is_zero() { + return None; + } + let bytes = literal + .value + .to_bytes_be() + .into_iter() + .filter(|&byte| byte != 0) + .collect::>(); + String::from_utf8(bytes).ok() +} + +/// Scale each value that a `%t` of `template` converts by `ticks_per_unit`, +/// as the analyzer scales the values of a `$display` (IEEE 1800-2023 20.4.3). +fn scale_time_values( + template: &str, + values: &mut [sv::ir::SystemTaskArg], + ticks_per_unit: u64, +) { + if ticks_per_unit == 1 { + return; + } + for (index, spec) in format_conversions(template).into_iter().enumerate() { + if !matches!(spec, 't' | 'T') { + continue; + } + if let Some(sv::ir::SystemTaskArg::Expr(value)) = values.get_mut(index) { + *value = sv::ir::Expr::Binary { + left: Box::new(value.clone()), + op: sv::ir::BinaryOp::Mul, + right: Box::new(sv::ir::Expr::Literal(format!("64'sd{ticks_per_unit}"))), + }; + } + } +} + +/// The conversions of `template` that take an argument, in order +/// (IEEE 1800-2023 21.2.1.2): flags, a width and a precision may precede +/// each. +fn format_conversions(template: &str) -> Vec { + let mut conversions = Vec::new(); + let mut chars = template.chars().peekable(); + while let Some(ch) = chars.next() { + if ch != '%' { + continue; + } + while chars + .next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0')) + .is_some() + {} + while chars.next_if(char::is_ascii_digit).is_some() {} + if chars.next_if_eq(&'.').is_some() { + while chars.next_if(char::is_ascii_digit).is_some() {} + } + if let Some(spec) = chars.next() + && "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) + { + conversions.push(spec); + } + } + conversions +} diff --git a/crates/celox-frontend-sv/src/lowering/ff/strings.rs b/crates/celox-frontend-sv/src/lowering/ff/strings.rs index d6d1b0da028..fad6ab76cdd 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/strings.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/strings.rs @@ -24,6 +24,10 @@ impl Ff<'_, '_> { .ok_or_else(|| unsupported(format!("omitted argument of `{op}`"))) }) .collect::, _>>()?; + // A format captures each operand at its own type, in order. + if let StringOp::Format { ticks_per_unit } = op { + return self.format_string(ticks_per_unit, &args); + } if args.iter().any(|arg| self.m.calls(arg)) { for (index, arg) in args.iter_mut().enumerate() { let context = match op { @@ -39,6 +43,7 @@ impl Ff<'_, '_> { } } let result = match op { + StringOp::Format { .. } => unreachable!("formatted above"), StringOp::FromBits => { let buffer = self.heap_call(ops::NEW, &[]); let buffer = self.append_bits(buffer, &args[0])?; diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index b36fe6adf4f..f7cc27e522d 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -75,6 +75,9 @@ pub(super) struct ProcModule<'a> { /// Where the warnings found while lowering go. A process lowered more /// than once repeats its warnings; the frontend reports each once. warnings: &'a mut Vec, + /// Whether a call of each subroutine asked about can make a host + /// request, by name. + requesting_subroutines: std::cell::RefCell>, } /// One word a memory file writes: its bits in the destination, value, and @@ -268,9 +271,88 @@ impl<'a> ProcModule<'a> { event_assignments: Vec::new(), unpacked_bounds, warnings, + requesting_subroutines: Default::default(), } } + /// Whether evaluating `expr` can make a host request, which suspends + /// the process: it calls a function that makes one directly, in the + /// defaults of omitted arguments, or through the subroutines it calls. + pub fn makes_host_request(&self, expr: &sv::ir::Expr) -> bool { + let mut calls = Vec::new(); + collect_calls(expr, &mut calls); + while let Some((callee, args)) = calls.pop() { + match callee { + sv::ir::Callee::System(function) if function.is_host_request() => return true, + sv::ir::Callee::String(sv::ir::StringOp::Format { .. }) => return true, + sv::ir::Callee::Subroutine(name) => { + let Some(subroutine) = self.subroutine(&name) else { + continue; + }; + // An omitted argument evaluates its default at the call. + default_calls(subroutine, &args, &mut calls); + if self.subroutine_makes_host_request(&name) { + return true; + } + } + _ => {} + } + } + false + } + + /// Whether the body of subroutine `name` can make a host request, + /// including through the calls it makes and their omitted defaults. + fn subroutine_makes_host_request(&self, name: &str) -> bool { + if let Some(&known) = self.requesting_subroutines.borrow().get(name) { + return known; + } + let mut pending = vec![name.to_string()]; + let mut visited = HashSet::default(); + let mut found = false; + while let Some(name) = pending.pop() { + if found { + break; + } + if !visited.insert(name.clone()) { + continue; + } + let Some(subroutine) = self.subroutine(&name) else { + continue; + }; + let mut calls = Vec::new(); + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| { + if let sv::ir::Stmt::SystemTask { task, .. } = stmt { + found |= task.is_host_request(); + } + stmt_calls(stmt, &mut calls); + }); + } + while let Some((callee, args)) = calls.pop() { + match callee { + sv::ir::Callee::System(function) => found |= function.is_host_request(), + sv::ir::Callee::String(op) => { + found |= matches!(op, sv::ir::StringOp::Format { .. }) + } + sv::ir::Callee::Subroutine(callee) => { + if let Some(subroutine) = self.subroutine(&callee) { + default_calls(subroutine, &args, &mut calls); + } + pending.push(callee); + } + sv::ir::Callee::Object(_) + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => {} + } + } + } + self.requesting_subroutines + .borrow_mut() + .insert(name.to_string(), found); + found + } + /// Whether a process calls a system function that reads the state of /// the simulation, such as `$urandom` or `$time`, including through user /// subroutines and omitted argument defaults. diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 05cd1da0b89..a05aad62f55 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -13,7 +13,7 @@ mod strings; pub(super) use calls::{statement as call_statement, statement_root as call_statement_root}; pub(super) use direct::{ arguments, bind_value, call_name as native_name, callable_name, cast_target_native, - member_context, real_value, remove_real_division_guards, ungroup, + format_arguments, member_context, real_value, remove_real_division_guards, ungroup, }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ 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 5763db071e8..b44348c89ed 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -692,6 +692,14 @@ pub(in crate::ast) fn bind_value( }, vec![(destination, None), (source, None)], ) + } else if name == "$sformatf" { + let actuals = format_arguments(&name, args)?; + ( + Finish::StringCall(StringOp::Format { + ticks_per_unit: timescales::time_divisor(id, tree)?, + }), + actuals.into_iter().map(|id| (id, None)).collect(), + ) } else if name.starts_with('$') && !name.contains("::") { let presence = args .iter() @@ -1840,6 +1848,34 @@ pub(in crate::ast) fn selected_lvalue( Ok(lvalue) } +/// The actuals of `$sformatf` (IEEE 1800-2023 21.3.3): a format followed by +/// any values, all given and positional. +pub(in crate::ast) fn format_arguments( + name: &str, + args: &[celox_sv_syntax::Argument], +) -> Converted> { + if args.iter().any(|arg| arg.name.is_some()) { + return Err(unsupported(format!("named arguments of `{name}`"))); + } + let actuals = args + .iter() + .enumerate() + .map(|(position, arg)| { + arg.value.ok_or_else(|| AnalyzerError::InvalidSystemTfCall { + name: name.to_string(), + detail: format!("argument {} is omitted", position + 1), + }) + }) + .collect::>>()?; + if actuals.is_empty() { + return Err(AnalyzerError::InvalidSystemTfCall { + name: name.to_string(), + detail: "expected a format argument".into(), + }); + } + Ok(actuals) +} + /// String literals in integral contexts are unsigned packed arrays of bytes /// (IEEE 1800-2023 5.9). Keep the semantic IR integral, including escapes. fn packed_string_literal(text: &str) -> Option { 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 74b0acb2d54..ebde30f4eab 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -113,7 +113,8 @@ pub(in crate::ast) fn operands( dimensions: &PackedDimensions, ) -> Vec { let strings = match op { - StringOp::FromBits | StringOp::Itoa(_) => 0, + // A format keeps its type: the frontend reads a literal one as text. + StringOp::FromBits | StringOp::Itoa(_) | StringOp::Format { .. } => 0, StringOp::Concat => usize::MAX, StringOp::Compare | StringOp::ICompare => 2, _ => 1, @@ -170,7 +171,10 @@ pub(in crate::ast) fn native_string( .is_some_and(|ty| ty.string) } ExprKind::Call { expression, .. } => { - method(tree, *expression, native, dimensions).is_some_and(|(op, _)| op.returns_string()) + matches!(&native.expression(ungroup(*expression, native)).kind, + ExprKind::Name(name) if name.spelling == "$sformatf") + || method(tree, *expression, native, dimensions) + .is_some_and(|(op, _)| op.returns_string()) || enum_name(tree, *expression, native, dimensions) } // `e.name` without parentheses (6.19.5.6, 6.19.5.7). diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 2502af44cd7..d5ff37e914e 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -665,6 +665,38 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .map(Some) } + /// `output = value` for the string `value` of `$sformat`, which assigns + /// its output as a string literal is assigned (IEEE 1800-2023 21.3.3, + /// 5.9). + fn format_assignment( + &self, + output: celox_sv_syntax::ExprId, + value: Expr, + ) -> Result { + let native = self.tree.declarations(); + if let Some((property, receiver)) = + expression_binding::object_property(self.tree, output, native, &self.dims)? + { + if property.field.handle != Some(system_functions::HandleProperty::String) { + return Err(unsupported("`$sformat` output that is not a string")); + } + let handle = + expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + return self.property_store(&property, handle, "=", value); + } + if !expression_binding::native_string(self.tree, output, native, &self.dims) { + return Err(unsupported("`$sformat` output that is not a string")); + } + let (_, lhs) = self.native_lvalue(output)?; + let mut rhs = value; + self.rename_expr(&mut rhs); + Ok(Stmt::Assign { + lhs, + rhs, + nonblocking: false, + }) + } + /// An assignment to a property of a class object: `h.p = v`, or `p = v` /// inside a method of its class (IEEE 1800-2023 8.5). fn property_assignment( @@ -1391,6 +1423,42 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { else_body: vec![error], }]); } + // `$sformat(output, format, args...)` assigns what `$sformatf(format, + // args...)` returns (IEEE 1800-2023 21.3.3). + if name == "$sformat" { + if arguments.iter().any(|arg| arg.name.is_some()) { + return Err(unsupported("named arguments of `$sformat`")); + } + let output = arguments.first().and_then(|arg| arg.value).ok_or_else(|| { + AnalyzerError::InvalidSystemTfCall { + name: name.into(), + detail: "expected an output argument".into(), + } + })?; + let mut values = Vec::new(); + for id in expression_binding::format_arguments(name, &arguments[1..])? { + values.push(expression_binding::bind_value( + id, + declarations, + self.tree, + &self.dims, + None, + )?); + } + let value = expression_binding::string_call( + StringOp::Format { + ticks_per_unit: timescales::time_divisor(root, self.tree)?, + }, + values, + ); + return Ok(vec![self.format_assignment(output, value)?]); + } + if name == "$sformatf" { + let mut value = + expression_binding::bind_value(root, declarations, self.tree, &self.dims, None)?; + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } let task = match system_functions::check_call( name, args.as_deref(), diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 78810f3ad73..d1b6cc97e63 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -735,6 +735,11 @@ pub enum StringOp { Atoi(Radix), /// `str.itoa(i)` and its radix variants (6.16.11-14), as the new string. Itoa(Radix), + /// `$sformatf(format, args...)` (21.3.3): the arguments formatted as + /// `$display` formats them. A `%t` converts a value in the time unit of + /// the calling scope, of which `ticks_per_unit` simulation time units + /// make one. + Format { ticks_per_unit: u64 }, } impl StringOp { @@ -750,6 +755,7 @@ impl StringOp { | Self::ToUpper | Self::ToLower | Self::Itoa(_) + | Self::Format { .. } ) } @@ -816,6 +822,7 @@ impl fmt::Display for StringOp { Self::Itoa(Radix::Hexadecimal) => "hextoa", Self::Itoa(Radix::Octal) => "octtoa", Self::Itoa(Radix::Binary) => "bintoa", + Self::Format { .. } => "$sformatf", }; f.write_str(name) } @@ -1554,6 +1561,9 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$swriteb", Task), unsupported("$swriteo", Task), unsupported("$swriteh", Task), + // The binders convert `$sformat` and `$sformatf` into string operations + // (`StringOp::Format`) before consulting the catalog, which rejects them + // anywhere else, such as in a constant expression. unsupported("$sformat", Task), unsupported("$sformatf", Function), function(SystemFunction::Fgetc, 1, Some(1)), diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 3edb6ada13c..f08dae60b4a 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -535,7 +535,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_internal_error` | compile | icarus | 3 | Icarus 13.0 crashes on these designs: a segmentation fault while compiling, or a vvp assertion (vthread.cc of_DISABLE_FLOW) while running. Verilator passes these cases. | | `sv_icarus_generate_function_scope` | execute | icarus | 1 | Icarus 13.0 evaluates a size query in a generate block with a function from another scope and reaches a $fatal in an active branch. Verilator agrees with the expected value. | | `sv_icarus_unknown_generate_condition` | compile | icarus | 1 | Icarus 13.0 rejects a loop-generate condition with unknown bits; Verilator accepts it, and Celox treats an unknown condition as false, as for if-generate (IEEE 1800-2023 12.4, 27.5). | -| `sv_icarus_function_outputs` | compile | icarus | 9 | Icarus 13.0 rejects output and inout function arguments (function port is not an input port). | +| `sv_icarus_function_outputs` | compile | icarus | 10 | Icarus 13.0 rejects output, inout and ref function arguments (function port is not an input port). | | `sv_icarus_instance_array_unpacked_port` | compile | icarus | 4 | Icarus 13.0 does not distribute an unpacked array connection over the elements of an instance array (IEEE 1800-2023 23.3.3.5) and reports multiple drivers. Verilator passes these cases. | | `sv_icarus_instance_array_fill_literal` | compile | icarus | 1 | Icarus 13.0 accepts a one-bit '0 connected to a wider port of an instance array, which IEEE 1800-2023 23.3.3.5 makes an error. Verilator rejects it. | | `sv_icarus_inside` | compile | icarus | 1 | Icarus 13.0 does not support inside expressions ("sorry: inside expressions not supported yet"). Verilator passes the case. | @@ -622,6 +622,18 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_static_property_wait` | execute | icarus | 1 | Icarus 13.0 compiles a `wait` on a static class property in a class task but vvp cannot load the result ("unresolved vvp_net reference", "Program not runnable"); IEEE 1800-2023 8.9 and 9.4.3 make the property one variable that the wait watches. [Standalone probe](verification/repros/sv_static_property_wait_icarus.json); Verilator 5.052 and xezim 0.11.3 pass the case. | | `sv_verilator_iff_late_conditions` | execute | verilator | 4 | Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. [Standalone probes](verification/repros/sv_iff_late_conditions_verilator.json) print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls. | | `sv_verilator_string_character_signedness` | execute | verilator | 1 | Verilator 5.052 reads a string character (`s[i]`, `s.getc(i)`) as unsigned, so code 255 converts to `int` 255. IEEE 1800-2023 6.16 makes a character a `byte`, which 6.11 makes signed (-1); xezim 0.11.3 agrees, Icarus 13.0 also reads 255. [Standalone probe](verification/repros/sv_string_character_signedness.json). | +| `sv_icarus_string_conditional` | compile | icarus | 1 | Icarus 13.0 aborts with an assertion in `eval_vec4.c` (`draw_eval_vec4`) on a conditional operator whose operands are strings, also with two `string` variables. IEEE 1800-2023 11.4.11 permits operands of equivalent nonintegral types; Verilator 5.052 and xezim 0.11.3 give the expected output. | +| `sv_icarus_sformat_property_output` | execute | icarus | 1 | Icarus 13.0 compiles `$sformat` with a `string` class property as the output, then `vvp` stops: "$sformat's first argument must be a register or SV string." IEEE 1800-2023 21.3.3 permits a string variable as the output; Verilator 5.052 and xezim 0.11.3 give the expected output. | +| `sv_icarus_integral_format_string` | execute | icarus | 1 | Icarus 13.0 compiles `$sformatf` with a `bit` vector variable as the format, then `vvp` stops: "$sformatf's first argument must be a string or a register." IEEE 1800-2023 21.3.3 reads the content of an integral format expression as the format; Verilator 5.052 gives the expected output, xezim 0.11.3 prints the format as a value (`sv_integral_format_string` in the xezim review). | +| `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. | +| `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). | + +The `string_format` cases compare `$sformatf` and `$sformat` with `$display` +of the same format and arguments. The [Icarus observations](verification/sv/limitations/string-format-icarus.json) +retain the three failing runs with reduced adapter-free sources; the remaining +cases pass in all three tools, except that Verilator 5.052 does not run the +four-state case. `%m` is checked only in Celox, as each adapter wraps the +design in its own testbench hierarchy. The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json) retains the failed Icarus runs and minimal sources. Cover comparisons enable diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index e9d2ee6887c..e05343c487d 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -63,6 +63,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/binary_file_io.vtest", text: include_str!("binary_file_io.vtest"), }, + Group { + file: "src/sv/cases/string_format.vtest", + text: include_str!("string_format.vtest"), + }, Group { file: "src/sv/cases/scan.vtest", text: include_str!("scan.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/string_format.vtest b/crates/celox-test-suite/src/sv/cases/string_format.vtest new file mode 100644 index 00000000000..1a28ab9d2a0 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/string_format.vtest @@ -0,0 +1,343 @@ +(group string_format (category types)) + +; IEEE 1800-2023 21.3.3: `$sformatf` returns what `$display` would print +; for the same format and arguments. +(case sformatf_matches_display + (source "sformatf_display.sv" #" +module Top(output bit done); + int i; + bit [7:0] b; + bit [71:0] wide; + string s, name; + real r; + initial begin + i = -5; + b = 8'ha5; + wide = 72'h12_3456_789a_bcde_f012; + name = "cat"; + r = 2.5; + $display("[%d|%0d|%h|%b|%o|%s|%c|%5s|%-5d|%0x|%%]", i, i, b, b, b, name, 8'h41, name, 7, wide); + s = $sformatf("[%d|%0d|%h|%b|%o|%s|%c|%5s|%-5d|%0x|%%]", i, i, b, b, b, name, 8'h41, name, 7, wide); + $display("%s", s); + $display("[%e|%f|%g|%0.2f|%10.3e]", r, r, r, r, -r); + s = $sformatf("[%e|%f|%g|%0.2f|%10.3e]", r, r, r, r, -r); + $display("%s", s); + $display("[%h|%d|%6d|%-3b|]", 4'sb1010, 4'sb1010, 10'd1023, 2'b10); + s = $sformatf("[%h|%d|%6d|%-3b|]", 4'sb1010, 4'sb1010, 10'd1023, 2'b10); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "[ -5|-5|a5|10100101|245|cat|A| cat|7 |123456789abcdef012|%]\n[ -5|-5|a5|10100101|245|cat|A| cat|7 |123456789abcdef012|%]\n[2.500000e+00|2.500000|2.5|2.50|-2.500e+00]\n[2.500000e+00|2.500000|2.5|2.50|-2.500e+00]\n[a|-6| 1023|10 |]\n[a|-6| 1023|10 |]\n")) + +; 21.2.1.5: unknown and high-impedance bits. +(case sformatf_four_state_values + (four_state) + (source "sformatf_unknown.sv" #" +module Top(output bit done); + logic [7:0] v; + logic [11:0] w; + string s; + initial begin + v = 8'b1x0z_0101; + w = 12'hz5x; + $display("[%b|%h|%o|%d|%h|%d]", v, v, v, v, w, 8'bx); + s = $sformatf("[%b|%h|%o|%d|%h|%d]", v, v, v, v, w, 8'bx); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "[1x0z0101|X5|XZ5| X|z5x| x]\n[1x0z0101|X5|XZ5| X|z5x| x]\n")) + +; 21.3.3: `$sformatf` can be used where a string value would be valid, and +; `$sformat` assigns the same text to its output. +(case sformatf_in_expressions + (source "sformatf_expressions.sv" #" +class Item; + int id; + function string name(); + return $sformatf("item%0d", id); + endfunction +endclass + +module Top(output bit done); + function automatic string tag(int n); + return $sformatf("<%0d>", n); + endfunction + function automatic int length(string s); + return s.len(); + endfunction + Item item; + string s, t; + int i, n; + initial begin + item = new; + item.id = 3; + i = -4; + s = {tag(1), "-", $sformatf("%0d", 2), "-", item.name()}; + t = $sformatf("neg%0d", -i); + n = length($sformatf("%0d", 12345)); + $display("%s %s %0d %0d", s, t, n, $sformatf("%0d", 10) == "10"); + $sformat(t, "%0d+%0d=%s", 1, 2, $sformatf("%0d", 3)); + $display("%s", t); + void'($sformatf("%0d", i)); + $sformatf("unused"); + s = $sformatf("plain text"); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "<1>-2-item3 neg4 5 1\n1+2=3\nplain text\n")) + +; 21.3.3: the output of `$sformat` can be a string property of a class +; object, including one of the object whose method calls it. +(case sformat_property_output + (source "sformat_property.sv" #" +class Item; + int id; + string label; + function string name(); + return $sformatf("item%0d", id); + endfunction + function void relabel(int n); + $sformat(label, "L%0d/%s", n, name()); + endfunction +endclass + +module Top(output bit done); + Item item; + initial begin + item = new; + item.id = 3; + item.relabel(9); + $display("%s", item.label); + $sformat(item.label, "%s!", item.name()); + $display("%s", item.label); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "L9/item3\nitem3!\n")) + +; 21.3.3: a format that is not a constant is the text of a string or an +; integral value when the call runs. +(case sformatf_runtime_formats + (source "sformatf_runtime.sv" #" +module Top(output bit done); + string format, s; + initial begin + format = "%0d:%s"; + s = $sformatf(format, 7, "x"); + $display("%s", s); + format = {format, "!%h"}; + s = $sformatf(format, 8, "y", 4'ha); + $display("%s", s); + $sformat(s, format, 1, "z", 4'hb); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "7:x\n8:y!a\n1:z!b\n")) + +; 21.3.3: the format can be an expression of an integral type, whose +; content is the format text. +(case sformatf_packed_runtime_format + (source "sformatf_packed_format.sv" #" +module Top(output bit done); + bit [8*4-1:0] format; + string s; + initial begin + format = "%0d"; + s = $sformatf(format, 42); + $display("%s", s); + format = "<%h"; + $sformat(s, format, 4'hc); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "42\n 0 ? $sformatf("pos%0d", i) : $sformatf("neg%0d", -i); + $display("%s", t); + i = 2; + $display("%s", i > 0 ? $sformatf("pos%0d", i) : $sformatf("neg%0d", -i)); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "neg4\npos2\n")) + +; 20.4.3: `%t` converts a time value of the calling scope in the units of +; `$timeformat`, the smallest time precision by default. Timed cases run at +; 1 ns / 1 ps. +(case sformatf_time_values + (source "sformatf_time.sv" #" +module Top(output bit done); + string format, s; + initial begin + #1.5; + $display("[%t|%0t]", $time, $realtime); + s = $sformatf("[%t|%0t]", $time, $realtime); + $display("%s", s); + format = "[%t|%0t]"; + s = $sformatf(format, $time, $realtime); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 10) (assert_eq done 1) + (expect_output "[ 2000|1500]\n[ 2000|1500]\n[ 2000|1500]\n")) + +; 13.5.3: an omitted argument evaluates its default at the call, here a +; `$sformatf` inside a string concatenation; an explicit `$sformatf` actual +; follows a constant one. +(case sformatf_in_omitted_default + (source "sformatf_default.sv" #" +module Top(output bit done); + function automatic string label(int n, string prefix = $sformatf("<%0d>", 7)); + return {prefix, $sformatf("%0d", n)}; + endfunction + string s; + initial begin + s = {"a", label(1), "-", label(2, "["), "-", label(3, $sformatf("{%0d}", 4)), "b"}; + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "a<7>1-[2-{4}3b\n")) + +; 21.3.3, 6.16: a run-time format keeps bytes that are not ASCII text. +(case sformatf_runtime_format_bytes + (source "sformatf_bytes.sv" #" +module Top(output bit done); + string format, s; + initial begin + format = string'(8'hff); + s = $sformatf(format); + $display("%0d %0d", s.len(), $unsigned(s[0])); + format = {format, "%0d", string'(8'h80)}; + s = $sformatf(format, 5); + $display("%0d %0d %0d %0d", s.len(), $unsigned(s[0]), s[1], $unsigned(s[2])); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "1 255\n3 255 53 128\n")) + +; 13.5.1: an input is converted to its formal before a later input runs a +; `$sformatf`; the addition is evaluated at the formal's 64 bits. +(case sformatf_after_wider_input + (source "sformatf_input_width.sv" #" +module Top(output bit done); + function automatic string show(bit [63:0] w, string text); + return $sformatf("%h %s", w, text); + endfunction + int unsigned x; + string s; + initial begin + x = 32'hffffffff; + s = show(x + 32'd1, $sformatf("%0d", 5)); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "0000000100000000 5\n")) + +; 7.10.2: a container method's operands are evaluated before it updates the +; container, also when an operand formats a string. +(case sformatf_in_container_operands + (source "sformatf_containers.sv" #" +class Log; + string lines[$]; +endclass + +module Top(output bit done); + string q[$]; + string m[string]; + Log log; + int i, n; + initial begin + log = new; + q = {"a", "c"}; + i = 1; + n = 7; + q.insert(i, $sformatf("b%0d", n)); + q.push_back($sformatf("d%0d", n + 1)); + m[$sformatf("k%0d", i)] = $sformatf("v%0d", n); + log.lines.push_back($sformatf("x%0d", i)); + log.lines.insert(0, $sformatf("w%0d", n)); + $display("%s %s %s %s %0d|%s|%s %s", q[0], q[1], q[2], q[3], q.size(), m["k1"], + log.lines[0], log.lines[1]); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "a b7 c d8 4|v7|w7 x1\n")) + +; 7.8.4: an integral associative index is evaluated as a cast to the index +; type (6.24.1), here at 64 bits, also when the stored value formats a string. +(case sformatf_with_associative_index + (source "sformatf_index.sv" #" +module Top(output bit done); + string wide[bit [63:0]]; + int unsigned x; + initial begin + x = 32'hffffffff; + wide[x + 32'd1] = $sformatf("%0d", 7); + $display("%0d %0d", wide.exists(64'h100000000), wide.exists(0)); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "1 0\n")) + +; 13.5.2: a `ref` formal refers to its actual while another input runs a +; `$sformatf`, before and after a constant input. +(case sformatf_with_reference_argument + (source "sformatf_ref.sv" #" +module Top(output bit done); + function automatic void append(ref string s, input int n, input string t); + s = $sformatf("%s%0d%s", s, n, t); + endfunction + string text; + initial begin + text = "a"; + append(text, 1, $sformatf("<%0d>", 2)); + append(text, 3, "-"); + $display("%s", text); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "a1<2>3-\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_associative_index_cast.json b/crates/celox-test-suite/verification/repros/sv_associative_index_cast.json new file mode 100644 index 00000000000..2aa8ecff543 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_associative_index_cast.json @@ -0,0 +1,29 @@ +{ + "case": "string_format::sformatf_with_associative_index", + "source": "src/sv/cases/string_format.vtest", + "standard": "IEEE 1800-2023 7.8.4: an integral index expression is evaluated in terms of a cast to the index type; 6.24.1: a size cast returns the value after an assignment to that width, so x + 32'd1 is evaluated at 64 bits.", + "method": "The shared case runs unchanged in verify-sv-verilator, verify-sv-icarus and verify-sv-xezim.", + "reduced_source": "module Top(output bit done);\n string wide[bit [63:0]];\n int unsigned x;\n initial begin\n x = 32'hffffffff;\n wide[x + 32'd1] = $sformatf(\"%0d\", 7);\n $display(\"%0d %0d\", wide.exists(64'h100000000), wide.exists(0));\n done = 1;\n end\nendmodule\n", + "observations": [ + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "stdout": "0 1\n" + }, + { + "tool": "xezim", + "version": "xezim 0.11.3", + "stdout": "0 1\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog 13.0", + "status": "compile_error", + "stderr": "source_0.sv:3: error: Type names are not valid expressions here.\n" + }, + { + "tool": "celox", + "stdout": "1 0\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index d59bfb262de..fe9e438501d 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -21,6 +21,7 @@ "icarus/review_regressions.json", "icarus/scan.json", "icarus/string.json", + "icarus/string_format.json", "icarus/synthesizable.json", "icarus/system_functions.json", "icarus/tagged_unions.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/string_format.json b/crates/celox-test-suite/verification/sv/icarus/string_format.json new file mode 100644 index 00000000000..ab9e5eb08ff --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/string_format.json @@ -0,0 +1,144 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "Icarus 13.0 compiles $sformat with a string class property as its output, but vvp stops with \"$sformat's first argument must be a register or SV string.\" IEEE 1800-2023 21.3.3 permits a string variable as the output, and a class property is one (8.5). Verilator 5.052 and xezim pass the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_runtime_limitation", + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_sformat_property_output", + "observed_version": "Icarus Verilog 13.0", + "phase": "execute", + "reason": "Icarus 13.0 compiles $sformat with a string class property as its output, but vvp stops with \"$sformat's first argument must be a register or SV string.\" IEEE 1800-2023 21.3.3 permits a string variable as the output, and a class property is one (8.5). Verilator 5.052 and xezim pass the case.", + "upstream": [] + }, + "name": "string_format::sformat_property_output", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 aborts with an assertion in eval_vec4.c (draw_eval_vec4) on a conditional operator whose operands are strings, also with two string variables. IEEE 1800-2023 11.4.11 permits operands of equivalent nonintegral types such as string. Verilator 5.052 and xezim pass the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_internal_error", + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_string_conditional", + "observed_version": "Icarus Verilog 13.0", + "phase": "compile", + "reason": "Icarus 13.0 aborts with an assertion in eval_vec4.c (draw_eval_vec4) on a conditional operator whose operands are strings, also with two string variables. IEEE 1800-2023 11.4.11 permits operands of equivalent nonintegral types such as string. Verilator 5.052 and xezim pass the case.", + "upstream": [] + }, + "name": "string_format::sformatf_in_conditional_expressions", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects associative arrays with string and bit [63:0] indices (\"Type names are not valid expressions here\") and queue methods called on a class property (\"Can't find task push_back in class Log\"). IEEE 1800-2023 7.8 and 7.10 define both; Verilator 5.052 and xezim 0.11.3 compile the cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_associative_index_cast.json" + ], + "id": "sv_icarus_string_associative_arrays_and_property_queue_methods", + "observed_version": "Icarus Verilog 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects associative arrays with string and bit [63:0] indices (\"Type names are not valid expressions here\") and queue methods called on a class property (\"Can't find task push_back in class Log\"). IEEE 1800-2023 7.8 and 7.10 define both; Verilator 5.052 and xezim 0.11.3 compile the cases.", + "upstream": [] + }, + "name": "string_format::sformatf_in_container_operands", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 compiles $sformatf with a bit-vector variable as the format, but vvp stops with \"$sformatf's first argument must be a string or a register.\" IEEE 1800-2023 21.3.3 permits an expression of integral type whose content is the format. Verilator 5.052 passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_runtime_limitation", + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_integral_format_string", + "observed_version": "Icarus Verilog 13.0", + "phase": "execute", + "reason": "Icarus 13.0 compiles $sformatf with a bit-vector variable as the format, but vvp stops with \"$sformatf's first argument must be a string or a register.\" IEEE 1800-2023 21.3.3 permits an expression of integral type whose content is the format. Verilator 5.052 passes the case.", + "upstream": [] + }, + "name": "string_format::sformatf_packed_runtime_format", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects associative arrays with string and bit [63:0] indices (\"Type names are not valid expressions here\") and queue methods called on a class property (\"Can't find task push_back in class Log\"). IEEE 1800-2023 7.8 and 7.10 define both; Verilator 5.052 and xezim 0.11.3 compile the cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_associative_index_cast.json" + ], + "id": "sv_icarus_string_associative_arrays_and_property_queue_methods", + "observed_version": "Icarus Verilog 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects associative arrays with string and bit [63:0] indices (\"Type names are not valid expressions here\") and queue methods called on a class property (\"Can't find task push_back in class Log\"). IEEE 1800-2023 7.8 and 7.10 define both; Verilator 5.052 and xezim 0.11.3 compile the cases.", + "upstream": [] + }, + "name": "string_format::sformatf_with_associative_index", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects output and inout function arguments (function port is not an input port).", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_function_outputs", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects output and inout function arguments (function port is not an input port).", + "upstream": [] + }, + "name": "string_format::sformatf_with_reference_argument", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 6f0af362d25..28a1966ca95 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -338,7 +338,8 @@ "procedural::select_indices_call_functions", "synthesizable::function_output_and_inout_arguments_are_written_back", "system_functions::unpacked_dimensions_accepts_function_result_arguments", - "system_functions::unpacked_dimensions_validates_writable_function_arguments" + "system_functions::unpacked_dimensions_validates_writable_function_arguments", + "string_format::sformatf_with_reference_argument" ] } }, @@ -2881,5 +2882,92 @@ "string::characters_are_signed_bytes" ] } + }, + { + "id": "sv_icarus_string_conditional", + "category": "simulator_internal_error", + "phase": "compile", + "observed_version": "Icarus Verilog 13.0", + "reason": "Icarus 13.0 aborts with an assertion in eval_vec4.c (draw_eval_vec4) on a conditional operator whose operands are strings, also with two string variables. IEEE 1800-2023 11.4.11 permits operands of equivalent nonintegral types such as string. Verilator 5.052 and xezim pass the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "string_format::sformatf_in_conditional_expressions" + ] + } + }, + { + "id": "sv_icarus_sformat_property_output", + "category": "simulator_runtime_limitation", + "phase": "execute", + "observed_version": "Icarus Verilog 13.0", + "reason": "Icarus 13.0 compiles $sformat with a string class property as its output, but vvp stops with \"$sformat's first argument must be a register or SV string.\" IEEE 1800-2023 21.3.3 permits a string variable as the output, and a class property is one (8.5). Verilator 5.052 and xezim pass the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "string_format::sformat_property_output" + ] + } + }, + { + "id": "sv_icarus_integral_format_string", + "category": "simulator_runtime_limitation", + "phase": "execute", + "observed_version": "Icarus Verilog 13.0", + "reason": "Icarus 13.0 compiles $sformatf with a bit-vector variable as the format, but vvp stops with \"$sformatf's first argument must be a string or a register.\" IEEE 1800-2023 21.3.3 permits an expression of integral type whose content is the format. Verilator 5.052 passes the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "string_format::sformatf_packed_runtime_format" + ] + } + }, + { + "id": "sv_icarus_string_associative_arrays_and_property_queue_methods", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog 13.0", + "reason": "Icarus 13.0 rejects associative arrays with string and bit [63:0] indices (\"Type names are not valid expressions here\") and queue methods called on a class property (\"Can't find task push_back in class Log\"). IEEE 1800-2023 7.8 and 7.10 define both; Verilator 5.052 and xezim 0.11.3 compile the cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_associative_index_cast.json" + ], + "cases": { + "icarus": [ + "string_format::sformatf_in_container_operands", + "string_format::sformatf_with_associative_index" + ] + } + }, + { + "id": "sv_verilator_associative_index_cast", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 evaluates the index x + 32'd1 of an associative array with a bit [63:0] index at the expression's own 32 bits, so the element is stored under key 0. IEEE 1800-2023 7.8.4 evaluates an integral index as a cast to the index type, and 6.24.1 gives a size cast the value after an assignment to that width, so the key is 64'h100000000; xezim 0.11.3 also stores key 0.", + "upstream": [], + "evidence": [ + "verification/repros/sv_associative_index_cast.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "string_format::sformatf_with_associative_index" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/string-format-icarus.json b/crates/celox-test-suite/verification/sv/limitations/string-format-icarus.json new file mode 100644 index 00000000000..a657743945b --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/string-format-icarus.json @@ -0,0 +1,40 @@ +{ + "tool": "icarus", + "version": "Icarus Verilog 13.0", + "source": "src/sv/cases/string_format.vtest", + "method": "Each unchanged shared case fails in the verify-sv-icarus run. The reduced sources below, run with iverilog -g2012 -s Top and vvp -n, reproduce each failure without the adapter.", + "cases": [ + { + "case": "string_format::sformatf_in_conditional_expressions", + "status": "compile_error", + "phase": "compile", + "stderr": "ivl: eval_vec4.c:1359: draw_eval_vec4: Assertion `ivl_expr_value(expr) == IVL_VT_BOOL || ivl_expr_value(expr) == IVL_VT_VECTOR' failed.\nAborted (core dumped)\n", + "exit_status": 134, + "reduced_source": "module Top;\n string a, b, t;\n int i;\n initial begin\n a = \"x\"; b = \"y\"; i = 1;\n t = i > 0 ? a : b;\n $display(\"%s\", t);\n end\nendmodule\n" + }, + { + "case": "string_format::sformat_property_output", + "status": "runtime_error", + "phase": "execute", + "stderr": "ERROR:prop_r.sv:8: $sformat's first argument must be a register or SV string.\n", + "exit_status": 1, + "reduced_source": "class Item;\n string label;\nendclass\nmodule Top;\n Item item;\n initial begin\n item = new;\n $sformat(item.label, \"L%0d\", 9);\n $display(\"%s\", item.label);\n end\nendmodule\n" + }, + { + "case": "string_format::sformatf_packed_runtime_format", + "status": "runtime_error", + "phase": "execute", + "stderr": "ERROR:packed_r.sv:6: $sformatf's first argument must be a string or a register.\n", + "exit_status": 1, + "reduced_source": "module Top;\n bit [8*4-1:0] format;\n string s;\n initial begin\n format = \"%0d\";\n s = $sformatf(format, 42);\n $display(\"%s\", s);\n end\nendmodule\n" + }, + { + "case": "string_format::sformatf_in_container_operands", + "status": "compile_error", + "phase": "compile", + "stderr": "source_0.sv:8: error: Type names are not valid expressions here.\nsource_0.sv:8: internal error: I do not know how to elaborate this expression.\nsource_0.sv:8: error: Dimensions must be constant.\nsource_0.sv:19: error: Can't find task push_back in class Log\nsource_0.sv:20: error: Can't find task insert in class Log\n", + "exit_status": 1, + "reduced_source": "class Log;\n string lines[$];\nendclass\nmodule Top;\n string m[string];\n Log log;\n initial begin\n log = new;\n m[\"k\"] = \"v\";\n log.lines.push_back(\"x\");\n $display(\"%s %s\", m[\"k\"], log.lines[0]);\n end\nendmodule\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index c684981b25b..182e769d1f0 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -22,6 +22,7 @@ "verilator/review_regressions.json", "verilator/scan.json", "verilator/string.json", + "verilator/string_format.json", "verilator/synthesizable.json", "verilator/system_functions.json", "verilator/tagged_unions.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/string_format.json b/crates/celox-test-suite/verification/sv/verilator/string_format.json new file mode 100644 index 00000000000..0ccd46d0f86 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/string_format.json @@ -0,0 +1,38 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "string_format::sformatf_four_state_values", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Verilator 5.052 evaluates the index x + 32'd1 of an associative array with a bit [63:0] index at the expression's own 32 bits, so the element is stored under key 0. IEEE 1800-2023 7.8.4 evaluates an integral index as a cast to the index type, and 6.24.1 gives a size cast the value after an assignment to that width, so the key is 64'h100000000; xezim 0.11.3 also stores key 0.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_associative_index_cast.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_associative_index_cast", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 evaluates the index x + 32'd1 of an associative array with a bit [63:0] index at the expression's own 32 bits, so the element is stored under key 0. IEEE 1800-2023 7.8.4 evaluates an integral index as a cast to the index type, and 6.24.1 gives a size cast the value after an assignment to that width, so the key is 64'h100000000; xezim 0.11.3 also stores key 0.", + "upstream": [] + }, + "name": "string_format::sformatf_with_associative_index", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/xezim.json b/crates/celox-test-suite/verification/sv/xezim.json index a5aa0a73791..1d89248a43f 100644 --- a/crates/celox-test-suite/verification/sv/xezim.json +++ b/crates/celox-test-suite/verification/sv/xezim.json @@ -30,6 +30,7 @@ "xezim/review_regressions.json", "xezim/scan.json", "xezim/string.json", + "xezim/string_format.json", "xezim/synthesizable.json", "xezim/system_functions.json", "xezim/tagged_unions.json", diff --git a/crates/celox-test-suite/verification/sv/xezim/string_format.json b/crates/celox-test-suite/verification/sv/xezim/string_format.json new file mode 100644 index 00000000000..2a30cfb32a7 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/xezim/string_format.json @@ -0,0 +1,26 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "string_format::sformatf_packed_runtime_format at 170:3: expect_output: expected [52, 50, 10, 60, 99, 10], got [32, 32, 32, 50, 52, 51, 55, 50, 50, 48, 32, 32, 32, 32, 32, 32, 32, 32, 32, 52, 50, 10, 32, 32, 32, 51, 57, 52, 49, 55, 51, 54, 49, 50, 10]", + "expectation": "Simulation", + "name": "string_format::sformatf_packed_runtime_format", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "string_format::sformatf_with_associative_index at 322:3: expect_output: expected [49, 32, 48, 10], got [48, 32, 49, 10]", + "expectation": "Simulation", + "name": "string_format::sformatf_with_associative_index", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index 9d9c88284b5..b0873058275 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -754,6 +754,14 @@ "sv_class_foreign_package_constructor": { "title": "Constructing a package-class type argument through a generic in another package leaves initialized instance fields unknown", "standard": "IEEE 1800-2023 8.7, 8.25" + }, + "sv_integral_format_string": { + "title": "An integral format of $sformatf or $sformat is displayed as a value instead of being read as the format", + "standard": "IEEE 1800-2023 21.3.3" + }, + "sv_associative_index_cast": { + "title": "An associative index is evaluated at its own width instead of as a cast to the index type", + "standard": "IEEE 1800-2023 7.8.4, 6.24.1" } }, "cases": [ @@ -4523,6 +4531,22 @@ "classification": "xezim_bug", "bug": "sv_class_foreign_package_constructor", "note": "q::Factory#(p::Item)::create() calls Item::new(), which must assign value=42. The result contains unknown bits; a standalone prints X,7,1 for result/tag/count instead of 42,7,1. The static tag and factory counter are explicitly initialized. See verification/repros/sv_foreign_generic.json." + }, + { + "suite": "sv", + "name": "string_format::sformatf_packed_runtime_format", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_integral_format_string", + "note": "With bit [31:0] format = \"%0d\", $sformatf(format, 42) gives \" 2437220 42\" in xezim 0.11.3: the format's bits are printed as a decimal value followed by the argument. IEEE 1800-2023 21.3.3 interprets the content of an integral format expression as the format, so the result is \"42\"; Verilator 5.052 prints 42." + }, + { + "suite": "sv", + "name": "string_format::sformatf_with_associative_index", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_associative_index_cast", + "note": "With int unsigned x = 32'hffffffff and string wide[bit [63:0]], wide[x + 32'd1] = ... stores key 0 in xezim 0.11.3 (prints 0 1); 7.8.4 evaluates the index as a cast to bit [63:0], so the key is 64'h100000000 (expected 1 0). See verification/repros/sv_associative_index_cast.json." } ] } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 3db664b6964..eefd8e71a25 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -214,6 +214,7 @@ impl UnitExecutor for Simulator { celox_design::HostRequestKind::FileIo => self.run_file_io_request(request, timestamp), celox_design::HostRequestKind::Vcd => self.run_vcd_request(request, timestamp), celox_design::HostRequestKind::Scan => self.run_scan_request(request, timestamp), + celox_design::HostRequestKind::Format => self.run_format_request(request, timestamp), } } } diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index ca90b98db52..f386554d3b5 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -42,6 +42,7 @@ mod host { mod deferred_tests; mod distribution; mod file_io; + mod format; mod fread; mod scan; use super::*; diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index b57e8901db0..e31c231f2de 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -3,6 +3,28 @@ use celox_design::HostRequestSite; use celox_runtime::{Halt, SimulatorErrorCode}; impl Simulator { + /// The hierarchical name of the instance that runs `process`, which a + /// `%m` of its host requests prints. + pub(super) fn process_scope(&self, process: usize) -> Option { + let process = &self.program.runtime_schema.processes[process]; + self.program + .design + .instance(process.status.instance_id) + .map(|instance| { + let top = self + .program + .design + .root_instance() + .map(|root| root.module_name.as_str()) + .unwrap_or(""); + std::iter::once(top) + .chain(instance.display_path.iter().map(String::as_str)) + .filter(|part| !part.is_empty()) + .collect::>() + .join(".") + }) + } + pub(crate) fn run_file_io_request( &mut self, site: &HostRequestSite, @@ -78,24 +100,7 @@ impl Simulator { handle: false, }) .collect(); - let process = &self.program.runtime_schema.processes[site.process]; - let scope = self - .program - .design - .instance(process.status.instance_id) - .map(|instance| { - let top = self - .program - .design - .root_instance() - .map(|root| root.module_name.as_str()) - .unwrap_or(""); - std::iter::once(top) - .chain(instance.display_path.iter().map(String::as_str)) - .filter(|part| !part.is_empty()) - .collect::>() - .join(".") - }); + let scope = self.process_scope(site.process); let format = RuntimeEventSite { kind: RuntimeEventKind::Write, template: site.strings.first().cloned(), diff --git a/crates/celox/src/simulator/host/format.rs b/crates/celox/src/simulator/host/format.rs new file mode 100644 index 00000000000..52d4a773784 --- /dev/null +++ b/crates/celox/src/simulator/host/format.rs @@ -0,0 +1,220 @@ +use super::*; +use celox_design::{FloatPrecision, HostRequestSite, ValueKind}; +use celox_runtime::Halt; + +impl Simulator { + /// `$sformatf` (IEEE 1800-2023 21.3.3): the result is what `$write` + /// prints for the same format and arguments. + pub(crate) fn run_format_request( + &mut self, + site: &HostRequestSite, + timestamp: u64, + ) -> Result<(), Halt> { + let mut args: Vec<_> = site + .args + .iter() + .map(|arg| { + let (value, mask) = if arg.id.is_4state { + self.backend.get_four_state(arg.id) + } else { + (self.backend.get(arg.id), BigUint::default()) + }; + let mut value = RuntimeEventArgValue { + values: value.to_u64_digits(), + masks: mask.to_u64_digits(), + width: arg.width, + signed: arg.signed, + is_string: false, + float_precision: arg.float_precision, + handle: arg.value_kind == ValueKind::StrRef, + }; + value.resolve_handle(self.backend.heap()); + value + }) + .collect(); + let template = if site.operation == 0 { + site.strings[0].clone().into_bytes() + } else { + // A run-time format is the text of its value: the bytes of a + // string, or of an integral value without its NUL bytes, unknown + // bits reading as zero. Bytes that are not UTF-8 stay as they are. + let format = args.remove(0); + let bytes = runtime_event_words_to_biguint(&format.values, format.width) + .to_bytes_be() + .into_iter() + .filter(|&byte| byte != 0) + .collect::>(); + let ticks_per_unit = site.strings[0].parse::().unwrap_or(1); + scale_time_arguments(&String::from_utf8_lossy(&bytes), &mut args, ticks_per_unit); + bytes + }; + let format = RuntimeEventSite { + kind: RuntimeEventKind::Write, + template: None, + sizing: DisplaySizing::Ieee, + scope: self.process_scope(site.process), + location: None, + assertion: None, + deferred: None, + timestamp_arg: false, + arg_widths: Vec::new(), + arg_signed: Vec::new(), + arg_is_string: Vec::new(), + arg_float_precision: Vec::new(), + arg_is_handle: Vec::new(), + }; + let message = render_bytes( + &template, + format, + &args, + RuntimeFormatContext { + tb_time: Some(timestamp), + ..Default::default() + }, + ); + let handle = self.backend.heap_mut().intern(&message); + self.backend.set(site.results[0].id, handle); + self.dirty = true; + Ok(()) + } +} + +/// What `$write` prints for `template` and `args`. Text outside conversions +/// is copied byte for byte, and each conversion, which is ASCII, is rendered +/// as `$display` renders it. +fn render_bytes( + template: &[u8], + mut site: RuntimeEventSite, + args: &[RuntimeEventArgValue], + ctx: RuntimeFormatContext<'_>, +) -> Vec { + let mut out = Vec::with_capacity(template.len()); + let mut position = 0; + let mut index = 0; + while position < template.len() { + if template[position] != b'%' { + let end = template[position..] + .iter() + .position(|&byte| byte == b'%') + .map_or(template.len(), |offset| position + offset); + out.extend_from_slice(&template[position..end]); + position = end; + continue; + } + // The flags, width and precision `FieldSpec::parse` reads, then the + // conversion character. + let start = position; + position += 1; + while template + .get(position) + .is_some_and(|byte| b"-+ #0".contains(byte)) + { + position += 1; + } + while template.get(position).is_some_and(u8::is_ascii_digit) { + position += 1; + } + if template.get(position) == Some(&b'.') { + position += 1; + while template.get(position).is_some_and(u8::is_ascii_digit) { + position += 1; + } + } + let spec = template.get(position).copied(); + if spec.is_some_and(|spec| !spec.is_ascii()) { + // An unknown conversion prints `%` and its character, as + // `$display` prints one. + out.push(b'%'); + continue; + } + if spec.is_some() { + position += 1; + } + // A conversion without its character converts an argument as `%d`. + let converts = spec.is_none_or(|spec| b"bBoOhHxXdDiIcCsStTeEfFgGpP".contains(&spec)); + site.template = Some( + String::from_utf8(template[start..position].to_vec()).expect("a conversion is ASCII"), + ); + out.extend(render_runtime_event_message( + &site, + args.get(index..).unwrap_or_default(), + ctx, + )); + if converts { + index += 1; + } + } + out +} + +/// Scale each value that a `%t` of a run-time `template` converts from the +/// time unit of the calling scope to simulation time units, as the analyzer +/// scales the values of a literal format: the product of the value and a +/// signed 64-bit factor (IEEE 1800-2023 11.6.1, 20.4.3). +fn scale_time_arguments(template: &str, args: &mut [RuntimeEventArgValue], ticks_per_unit: u64) { + if ticks_per_unit == 1 { + return; + } + let mut chars = template.chars().peekable(); + let mut index = 0; + while let Some(ch) = chars.next() { + if ch != '%' { + continue; + } + while chars + .next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0')) + .is_some() + {} + while chars.next_if(char::is_ascii_digit).is_some() {} + if chars.next_if_eq(&'.').is_some() { + while chars.next_if(char::is_ascii_digit).is_some() {} + } + let Some(spec) = chars.next() else { + break; + }; + if !"bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) { + continue; + } + if matches!(spec, 't' | 'T') + && let Some(arg) = args.get_mut(index) + { + scale_time_argument(arg, ticks_per_unit); + } + index += 1; + } +} + +fn scale_time_argument(arg: &mut RuntimeEventArgValue, ticks_per_unit: u64) { + let bits = runtime_event_words_to_biguint(&arg.values, arg.width); + match arg.float_precision { + Some(FloatPrecision::F64) => { + let value = f64::from_bits(bits.iter_u64_digits().next().unwrap_or(0)); + arg.values = vec![(value * ticks_per_unit as f64).to_bits()]; + } + Some(FloatPrecision::F32) => { + let value = f32::from_bits(bits.iter_u32_digits().next().unwrap_or(0)); + arg.values = vec![u64::from((value * ticks_per_unit as f32).to_bits())]; + } + None => { + // The product has the larger width of its operands and is signed + // only if the value is (11.8.1); an unknown bit makes it unknown. + let width = arg.width.max(64); + let modulus = BigUint::from(1u8) << width; + let mask = runtime_event_words_to_biguint(&arg.masks, arg.width); + if mask.bits() > 0 { + arg.values = vec![0; width.div_ceil(64)]; + arg.masks = (&modulus - 1u8).to_u64_digits(); + } else { + let negative = arg.signed && arg.width > 0 && bits.bit(arg.width as u64 - 1); + let extended = if negative { + bits + (&modulus - (BigUint::from(1u8) << arg.width)) + } else { + bits + }; + arg.values = ((extended * ticks_per_unit) % &modulus).to_u64_digits(); + arg.masks = Vec::new(); + } + arg.width = width; + } + } +} diff --git a/crates/celox/tests/frontends/systemverilog/string_format.rs b/crates/celox/tests/frontends/systemverilog/string_format.rs new file mode 100644 index 00000000000..8647f7943c1 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/string_format.rs @@ -0,0 +1,85 @@ +use super::*; + +sv_backends! { + fn sformatf_matches_display(sim) { @case "string_format::sformatf_matches_display"; } + fn sformatf_four_state_values(sim) { @case "string_format::sformatf_four_state_values"; } + fn sformatf_in_expressions(sim) { @case "string_format::sformatf_in_expressions"; } + fn sformat_property_output(sim) { @case "string_format::sformat_property_output"; } + fn sformatf_runtime_formats(sim) { @case "string_format::sformatf_runtime_formats"; } + fn sformatf_packed_runtime_format(sim) { @case "string_format::sformatf_packed_runtime_format"; } + fn sformatf_in_conditional_expressions(sim) { @case "string_format::sformatf_in_conditional_expressions"; } + fn sformatf_time_values(sim) { @case "string_format::sformatf_time_values"; } + fn sformatf_in_omitted_default(sim) { @case "string_format::sformatf_in_omitted_default"; } + fn sformatf_runtime_format_bytes(sim) { @case "string_format::sformatf_runtime_format_bytes"; } + fn sformatf_after_wider_input(sim) { @case "string_format::sformatf_after_wider_input"; } + fn sformatf_in_container_operands(sim) { @case "string_format::sformatf_in_container_operands"; } + fn sformatf_with_associative_index(sim) { @case "string_format::sformatf_with_associative_index"; } + fn sformatf_with_reference_argument(sim) { @case "string_format::sformatf_with_reference_argument"; } + // External testbenches wrap the design, so the hierarchical name `%m` + // prints differs between simulators; Celox prints the same for both. + fn sformatf_scope_matches_display(sim) { + @setup { + let source = r#" + module Child; + string s; + initial begin + $display("[%m]"); + s = $sformatf("[%m]"); + $display("%s", s); + end + endmodule + module Top; Child first(); endmodule + "#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("format_scope.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![ + celox::RuntimeEvent::Display { message: b"[Top.first]".to_vec() }, + celox::RuntimeEvent::Display { message: b"[Top.first]".to_vec() }, + ]); + } +} + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn sformatf_native_image() { + for case in [ + "string_format::sformatf_in_expressions", + "string_format::sformatf_runtime_formats", + ] { + crate::suite::run_case(case, "native-image"); + } +} + +/// A property's owner is captured before the operands of a container method +/// run, as without a formatting operand. IEEE 1800-2023 leaves this order to +/// the implementation, so the case is Celox's own contract. +#[test] +fn container_owner_is_captured_before_formatting_operands() { + let source = r#" + class Log; string lines[$]; endclass + module Top(output int first_size, other_size); + Log log, first, other; + function automatic string retarget(); + log = other; + return $sformatf("r%0d", 1); + endfunction + initial begin + first = new; + other = new; + log = first; + log.lines.push_back(retarget()); + first_size = first.lines.size(); + other_size = other.lines.size(); + end + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources(vec![(source, Path::new("owner.sv"))], "Top") + .build() + .unwrap(); + sim.run_until(0).unwrap(); + let first = sim.signal("first_size"); + let other = sim.signal("other_size"); + assert_eq!(sim.get(first), BigUint::from(1u8)); + assert_eq!(sim.get(other), BigUint::from(0u8)); +} diff --git a/crates/celox/tests/sv_dpi.rs b/crates/celox/tests/sv_dpi.rs index c29213b3495..4c482693614 100644 --- a/crates/celox/tests/sv_dpi.rs +++ b/crates/celox/tests/sv_dpi.rs @@ -433,6 +433,40 @@ void_call_test!( parallel_partition(celox::ParallelPartition::Always) ); +// An actual evaluated before one that formats a string keeps its value +// across the formatting host request. +#[test] +fn actuals_survive_a_later_formatting_request() { + let source = r#" + module Top(output int result); + import "DPI-C" function int digits(input int first, input int second); + function automatic int formatted_length(input int v); + string s = $sformatf("%0d", v); + return s.len(); + endfunction + int a = 7; + initial result = digits(a, formatted_length(123)); + endmodule + "#; + let builder = || unsafe { + celox::Simulation::from_sv_sources(vec![(source, Path::new("dpi.sv"))], "Top") + .dpi_function("digits", dpi_digits as *const ()) + }; + macro_rules! check { + ($build:ident) => {{ + let mut sim = builder().$build().unwrap(); + sim.run_until(0).unwrap(); + let result = sim.signal("result"); + assert_eq!(sim.get(result), BigUint::from(73u32), stringify!($build)); + }}; + } + check!(build_cranelift); + check!(build_interpreter); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); +} + #[test] fn logic_arguments_keep_unknown_bits_in_four_state_simulation() { let source = r#" diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index c2dee963cd6..e9875cc9f8c 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -145,6 +145,8 @@ mod review_regressions; mod scan; #[path = "frontends/systemverilog/string.rs"] mod string; +#[path = "frontends/systemverilog/string_format.rs"] +mod string_format; #[path = "frontends/systemverilog/suite.rs"] mod suite; #[path = "frontends/systemverilog/synthesizable.rs"] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index f181d2e0150..a762a2f78b9 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -32,7 +32,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | 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) | +| 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; text formatted by `$sformatf` / `$sformat`. See [strings](#strings) | | Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types up to 64 bits (4-state properties start as X and keep X/Z bits), `string` and class handle types, plus dynamic arrays, queues and associative arrays, 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 | @@ -318,7 +318,7 @@ waits zero. | Simulation time | `$time`, `$stime` and `$realtime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | | Sampled values | `$sampled` in processes, combinational logic and the subroutines they call; `$past`, `$rose`, `$fell`, `$stable` and `$changed` in edge-triggered processes whose clock they infer and the subroutines those call; see [Sampled values](#sampled-values) | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | -| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | +| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, `$sformatf` / `$sformat` (see [Formatted output to strings](#formatted-output-to-strings)), and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -436,7 +436,7 @@ string, and an integral value assigned or cast to a string contributes its bytes from the most significant one. A character read as `s[i]` or `s.getc(i)` is a `byte`, which is signed (6.16, 6.11): a code above 127 reads as a negative value. -Not yet supported: `$sformat` / `$sformatf`, `atoreal` / `realtoa`, string +Not yet supported: `atoreal` / `realtoa`, string arguments of `$value$plusargs`, file I/O and DPI-C, and string values in VPI, VCD output and the TypeScript API. @@ -1143,6 +1143,23 @@ destinations. `%s` string outputs and `%t` time scaling are unsupported. Both functions require timed `Simulation` execution. Pure `$sscanf` state can be checkpointed; `$fscanf` uses external file state and prevents checkpoints. +### Formatted output to strings {#formatted-output-to-strings} + +`$sformatf(format, args...)` returns, as a `string`, the text `$write` prints +for the same format and arguments, and `$sformat(output, format, args...)` +assigns it to `output` (IEEE 1800-2023 21.3.3). Every conversion of `$display` +is available, with the same field widths, X/Z digits and `%t` scaling. +`$sformatf` can appear in any expression of a procedural statement, including +function results, arguments, concatenations and conditional operands. The format +can be a string literal or, evaluated when the call runs, a `string` or integral +value. The output of `$sformat` must be a `string` variable or class property; +integral outputs, `%p` and the `$swrite` family are unsupported. + +Each call with conversions is a host request of a timed `Simulation`, like the +file output tasks below; a format without conversions and arguments is a +constant. Calls from combinational processes and continuous assignments are +unsupported. + ### Runtime file output `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and their `b` / `o` / `h`