From 2541022deca95193b6ed26d155808cdbb1dcef9f Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 04:29:25 +0900 Subject: [PATCH 1/3] feat(testbench)!: support Veryl string variables --- crates/celox-frontend-veryl/src/testbench.rs | 122 ++++++++++++++++-- .../src/veryl/cases/tb_string.vtest | 40 ++++++ crates/celox-testbench/src/lib.rs | 19 +++ crates/celox-testbench/src/vm.rs | 69 +++++++++- crates/celox/src/component.rs | 3 + crates/celox/src/simulator.rs | 3 + crates/celox/src/simulator/checkpoint.rs | 8 +- crates/celox/src/simulator/state_file.rs | 8 ++ crates/celox/src/testbench.rs | 34 ++++- crates/celox/tests/component_method.rs | 4 +- crates/celox/tests/testbench_string.rs | 104 +++++++++++++-- packages/celox/src/e2e.test.ts | 29 +++++ 12 files changed, 415 insertions(+), 28 deletions(-) diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 07d25bbf427..9c31392c803 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -1167,6 +1167,13 @@ impl ExprCompiler<'_> { ops: &mut Vec, context: Option, ) -> ValueContext { + // A string's declared width is nominal; its runtime length must never + // pass through integer context sizing or assignment truncation. + let context = if expr.comptime().r#type.is_string() { + None + } else { + context + }; match expr { Expression::Term(f) => { self.emit_factor(f, ops); @@ -1242,6 +1249,19 @@ impl ExprCompiler<'_> { return self.resize_result(ops, casted, context); } + if lhs.comptime().r#type.is_string() && rhs.comptime().r#type.is_string() { + self.emit_in_context(lhs, ops, None); + self.emit_in_context(rhs, ops, None); + ops.push(TbOpcode::BinOp(lower_testbench_operator(*op))); + return self.resize_result( + ops, + ValueContext { + width: 1, + signed: false, + }, + context, + ); + } let lhs_width = self.natural_width(lhs); let rhs_width = self.natural_width(rhs); let semantics = binary_semantics( @@ -1351,6 +1371,40 @@ impl ExprCompiler<'_> { } fn emit_factor(&self, factor: &Factor, ops: &mut Vec) { + if factor.comptime().r#type.is_string() { + match factor { + Factor::Variable(id, index, select, comptime) if !comptime.is_const => { + let (address, info) = + self.local_variable(*id).expect("string variable metadata"); + self.emit_string_access(address, info, index, select, ops); + return; + } + Factor::HierVariable(reference) => { + let (address, info) = self + .hierarchical_variable(reference) + .expect("string variable metadata"); + self.emit_string_access( + address, + info, + &reference.index, + &reference.select, + ops, + ); + return; + } + _ => { + if let Ok(value) = factor.comptime().get_value() { + let len = value.width().div_ceil(8); + let bytes = value.payload().to_bytes_be(); + let mut result = vec![0; len]; + let copied = len.min(bytes.len()); + result[len - copied..].copy_from_slice(&bytes[bytes.len() - copied..]); + ops.push(TbOpcode::ConstString(result)); + return; + } + } + } + } match factor { Factor::Variable(var_id, index, select, comptime) => { if comptime.is_const @@ -1402,6 +1456,36 @@ impl ExprCompiler<'_> { } } + fn emit_string_access( + &self, + address: StateAddr, + info: &VariableInfo, + index: &VarIndex, + select: &VarSelect, + ops: &mut Vec, + ) { + let target = self + .resolve_target_parts( + SemanticSignal { + address, + width: info.width, + }, + info, + index, + select, + ) + .expect("validated string access"); + if let Some(selection) = target.selection { + ops.extend_from_slice(selection.offset.ops()); + } else { + ops.push(TbOpcode::ConstU64(0)); + } + ops.push(TbOpcode::LoadString { + location: Self::state_location_at(address, 0), + elements: info.width, + }); + } + fn emit_constant_value( &self, value: &veryl_analyzer::value::Value, @@ -1452,10 +1536,16 @@ impl ExprCompiler<'_> { signed: expression_signed(arg_expr), }), ); - ops.push(TbOpcode::StoreU64 { - location: self.state_location(arg_var_id, 0), - byte_size: get_byte_size(sig.width), - }); + if arg_expr.comptime().r#type.is_string() { + ops.push(TbOpcode::StoreString { + location: self.state_location(arg_var_id, 0), + }); + } else { + ops.push(TbOpcode::StoreU64 { + location: self.state_location(arg_var_id, 0), + byte_size: get_byte_size(sig.width), + }); + } } } } @@ -1473,10 +1563,16 @@ impl ExprCompiler<'_> { signed: expression_signed(&a.expr), }), ); - ops.push(TbOpcode::StoreU64 { - location: self.state_location(first_dst.id, 0), - byte_size: get_byte_size(dst_sig.width), - }); + if a.expr.comptime().r#type.is_string() { + ops.push(TbOpcode::StoreString { + location: self.state_location(first_dst.id, 0), + }); + } else { + ops.push(TbOpcode::StoreU64 { + location: self.state_location(first_dst.id, 0), + byte_size: get_byte_size(dst_sig.width), + }); + } } } } @@ -1487,7 +1583,15 @@ impl ExprCompiler<'_> { // 3. Load return value if let Some(ret_var_id) = &func_body.ret { if let Some(sig) = self.resolve_var(ret_var_id) { - self.emit_load(*ret_var_id, 0, sig.width, ops); + if fc.comptime.r#type.is_string() { + ops.push(TbOpcode::ConstU64(0)); + ops.push(TbOpcode::LoadString { + location: self.state_location(*ret_var_id, 0), + elements: 1, + }); + } else { + self.emit_load(*ret_var_id, 0, sig.width, ops); + } } else { ops.push(TbOpcode::ConstU64(0)); } diff --git a/crates/celox-test-suite/src/veryl/cases/tb_string.vtest b/crates/celox-test-suite/src/veryl/cases/tb_string.vtest index 39d8d711c12..67d730d6094 100644 --- a/crates/celox-test-suite/src/veryl/cases/tb_string.vtest +++ b/crates/celox-test-suite/src/veryl/cases/tb_string.vtest @@ -77,3 +77,43 @@ module Top { "#) (top Top) (run_testbench)) + +(case array_elements + (source "test.veryl" #"#[test(Top)] +module Top { + var text: string[2]; + var index: u32; + initial { + text[0] = "first"; + text[1] = "second element is longer"; + index = 1; + $assert(text[index] == "second element is longer"); + text[index] = text[0]; + text[0] = ""; + $assert(text[0] == ""); + $assert(text[1] == "first"); + $finish(); + } +} +"#) + (top Top) + (run_testbench)) + +(case function_argument + (source "test.veryl" #"#[test(Top)] +module Top { + var text: string; + function identity(value: input string) -> string { + return value; + } + initial { + text = "function argument longer than eight bytes"; + $assert(identity(text) == text); + text = identity(""); + $assert(text == ""); + $finish(); + } +} +"#) + (top Top) + (run_testbench)) diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 46f14cc98ba..919d6dad3f0 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -16,6 +16,9 @@ pub use format::{ }; pub use vm::{CompiledExpr, TestbenchValue}; +/// Dynamic string values, addressed by a bound variable and flattened array index. +pub type TestbenchStrings = std::collections::BTreeMap<(usize, usize), Vec>; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct StateLocation { pub address: A, @@ -507,6 +510,14 @@ pub enum ExprOpcode { location: L, byte_size: usize, }, + ConstString(Vec), + LoadString { + location: L, + elements: usize, + }, + StoreString { + location: L, + }, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -668,6 +679,14 @@ impl ExprBytecode> { let mut ops = Vec::with_capacity(self.ops.len()); for op in self.ops { let bound = match op { + ExprOpcode::ConstString(value) => ExprOpcode::ConstString(value), + ExprOpcode::LoadString { location, elements } => ExprOpcode::LoadString { + location: bind_location(location, &mut resolve)?, + elements, + }, + ExprOpcode::StoreString { location } => ExprOpcode::StoreString { + location: bind_location(location, &mut resolve)?, + }, ExprOpcode::ConstU64(value) => ExprOpcode::ConstU64(value), ExprOpcode::ConstWide(value) => ExprOpcode::ConstWide(value), ExprOpcode::LoadU64 { diff --git a/crates/celox-testbench/src/vm.rs b/crates/celox-testbench/src/vm.rs index e4abd0015ae..dd965af6d64 100644 --- a/crates/celox-testbench/src/vm.rs +++ b/crates/celox-testbench/src/vm.rs @@ -11,17 +11,24 @@ pub struct CompiledExpr { bytecode: ExprBytecode, } -/// Stack value: either a native u64 or a heap-allocated BigUint. +/// Stack value: integer bits or a dynamically sized byte string. #[derive(Clone, Debug)] pub enum TestbenchValue { U64(u64), Wide(BigUint), + String(Vec), } impl TestbenchValue { #[inline] pub fn to_u64(&self) -> u64 { match self { + TestbenchValue::String(v) => v + .iter() + .rev() + .take(8) + .enumerate() + .fold(0, |value, (i, byte)| value | (u64::from(*byte) << (i * 8))), TestbenchValue::U64(v) => *v, TestbenchValue::Wide(v) => { let digits = v.to_u64_digits(); @@ -33,6 +40,7 @@ impl TestbenchValue { #[inline] pub fn is_zero(&self) -> bool { match self { + TestbenchValue::String(v) => v.is_empty(), TestbenchValue::U64(v) => *v == 0, TestbenchValue::Wide(v) => *v == BigUint::ZERO, } @@ -41,6 +49,7 @@ impl TestbenchValue { #[inline] pub fn to_biguint(&self) -> BigUint { match self { + TestbenchValue::String(v) => BigUint::from_bytes_be(v), TestbenchValue::U64(v) => BigUint::from(*v), TestbenchValue::Wide(v) => v.clone(), } @@ -72,7 +81,9 @@ impl CompiledExpr { if self.bytecode.ops().iter().any(|op| { matches!( op, - TbOpcode::LoadU64 { .. } + TbOpcode::StoreString { .. } + | TbOpcode::LoadString { .. } + | TbOpcode::LoadU64 { .. } | TbOpcode::LoadWide { .. } | TbOpcode::LoadIndexed { .. } | TbOpcode::LoadBitSelect { .. } @@ -97,6 +108,17 @@ impl CompiledExpr { pub fn eval_value_with_write_observer( &self, memory: *mut u8, + on_write: impl FnMut(usize, usize), + ) -> TestbenchValue { + self.eval_with_strings(memory, &mut crate::TestbenchStrings::new(), on_write) + } + + /// Evaluate using the simulator-owned string storage. Values are copied on + /// load so assigning another variable cannot alias a mutable string. + pub fn eval_with_strings( + &self, + memory: *mut u8, + strings: &mut crate::TestbenchStrings, mut on_write: impl FnMut(usize, usize), ) -> TestbenchValue { let mut stack: Vec = Vec::with_capacity(16); @@ -104,7 +126,7 @@ impl CompiledExpr { let ops = self.bytecode.ops(); while pc < ops.len() { - self.exec_at(ops, &mut pc, &mut stack, memory, &mut on_write); + self.exec_at(ops, &mut pc, &mut stack, memory, strings, &mut on_write); } stack.pop().unwrap_or_else(|| { debug_assert!(false, "testbench bytecode: stack empty after evaluation"); @@ -121,9 +143,34 @@ impl CompiledExpr { pc: &mut usize, stack: &mut Vec, memory: *mut u8, + strings: &mut crate::TestbenchStrings, on_write: &mut impl FnMut(usize, usize), ) { match &ops[*pc] { + TbOpcode::ConstString(value) => { + stack.push(TestbenchValue::String(value.clone())); + *pc += 1; + } + TbOpcode::LoadString { location, elements } => { + let index = stack.pop().expect("string index").to_u64() as usize; + let value = if index < *elements { + strings + .get(&(*location, index)) + .cloned() + .unwrap_or_default() + } else { + Vec::new() + }; + stack.push(TestbenchValue::String(value)); + *pc += 1; + } + TbOpcode::StoreString { location } => { + let TestbenchValue::String(value) = stack.pop().expect("string store value") else { + unreachable!("string store requires a string value"); + }; + strings.insert((*location, 0), value); + *pc += 1; + } TbOpcode::ConstU64(v) => { stack.push(TestbenchValue::U64(*v)); *pc += 1; @@ -258,14 +305,14 @@ impl CompiledExpr { if !cond.is_zero() { let then_end = *pc + then_len; while *pc < then_end { - self.exec_at(ops, pc, stack, memory, on_write); + self.exec_at(ops, pc, stack, memory, strings, on_write); } *pc += else_len; // skip else block } else { *pc += then_len; // skip then block let else_end = *pc + else_len; while *pc < else_end { - self.exec_at(ops, pc, stack, memory, on_write); + self.exec_at(ops, pc, stack, memory, strings, on_write); } } } @@ -382,6 +429,18 @@ unsafe fn read_bits(ptr: *const u8, bit_offset: usize, width: usize) -> Testbenc #[inline] fn eval_binop(l: TestbenchValue, op: Op, r: TestbenchValue) -> TestbenchValue { match (&l, &r) { + (TestbenchValue::String(l), TestbenchValue::String(r)) => { + let result = match op { + Op::Eq => l == r, + Op::Ne => l != r, + Op::Less => l < r, + Op::LessEq => l <= r, + Op::Greater => l > r, + Op::GreaterEq => l >= r, + _ => unreachable!("invalid string operator: {op:?}"), + }; + TestbenchValue::U64(u64::from(result)) + } (TestbenchValue::U64(lv), TestbenchValue::U64(rv)) => { TestbenchValue::U64(eval_binop_u64(*lv, op, *rv)) } diff --git a/crates/celox/src/component.rs b/crates/celox/src/component.rs index 7958e262b6b..be5f2b0a622 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -885,6 +885,9 @@ pub(crate) fn host_value_from_argument( width: usize, is_string: bool, ) -> HostValue { + if let TestbenchValue::String(bytes) = &value { + return HostValue::Str(String::from_utf8_lossy(bytes).into_owned()); + } let value = value.to_biguint(); if is_string { let byte_len = width.div_ceil(8); diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index bb8978a3737..72dc4cd86c9 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -97,6 +97,8 @@ mod host { /// cross-codegen builds or unsupported hosts. pub struct Simulator { pub(crate) backend: B, + /// Dynamic testbench strings, keyed by the bound variable location. + pub(crate) testbench_strings: celox_testbench::TestbenchStrings, pub(crate) program: RuntimeProgram, pub(crate) vcd_writer: Option, pub(crate) dirty: bool, @@ -683,6 +685,7 @@ mod host { vcd_writer: None, dirty: false, warnings, + testbench_strings: Default::default(), components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 63afca14953..e4159342014 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -92,14 +92,15 @@ fn state_range(backend: &B) -> std::ops::Range { #[derive(Clone)] pub struct Checkpoint { image: StateImage, + testbench_strings: celox_testbench::TestbenchStrings, comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, } impl Checkpoint { - /// Size of the saved design state in bytes. + /// Bytes in the saved memory image and string contents, excluding allocator overhead. pub fn state_size(&self) -> usize { - self.image.len() + self.image.len() + self.testbench_strings.values().map(Vec::len).sum::() } } @@ -142,6 +143,7 @@ impl Simulator { } Ok(Checkpoint { image: StateImage::capture(&self.backend, self.state_fingerprint()), + testbench_strings: self.testbench_strings.clone(), comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, }) @@ -159,6 +161,8 @@ impl Simulator { checkpoint .image .restore_into(&mut self.backend, fingerprint)?; + self.testbench_strings + .clone_from(&checkpoint.testbench_strings); self.comb_observer_snapshots .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index c51b8ec2ffd..faf5e1714de 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -38,6 +38,8 @@ pub enum StateError { /// cannot record where it resumes. #[error("state files are not supported for simulations with processes")] Processes, + #[error("state files do not support dynamic testbench strings; use a checkpoint instead")] + TestbenchStrings, } /// Differences between a state file and the design it is loaded into. @@ -241,6 +243,9 @@ impl Simulator { /// Combinational values are settled first, so the file shows the values /// a read would return. pub fn save_state(&mut self) -> Result { + if !self.testbench_strings.is_empty() { + return Err(StateError::TestbenchStrings); + } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -261,6 +266,9 @@ impl Simulator { /// ignored. An attached VCD writer records the loaded values as changes /// at the next dump. pub fn load_state(&mut self, file: &StateFile) -> Result<(), StateError> { + if !self.testbench_strings.is_empty() { + return Err(StateError::TestbenchStrings); + } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 8319baa6363..6ba13234cba 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -97,7 +97,20 @@ fn eval_expr( sim: &mut Simulator, expr: &celox_testbench::CompiledExpr, ) -> TbValue { - eval_backend_expr(&mut sim.backend, expr) + let (memory, _) = sim.backend.memory_as_ptr(); + let trace = sim.backend.layout().trace.as_ref(); + expr.eval_with_strings( + memory.cast_mut(), + &mut sim.testbench_strings, + |offset, len| { + if let Some(trace) = trace { + // SAFETY: bytecode is bound to this simulator's memory layout. + unsafe { + trace.mark_range(memory.cast_mut(), offset, len); + } + } + }, + ) } pub(crate) fn eval_backend_expr( @@ -126,12 +139,16 @@ fn format_assert_arg( field: FieldSpec, ) -> Vec { let value = eval_expr(sim, &arg.expr); + let width = match &value { + TbValue::String(bytes) => bytes.len() * 8, + _ => arg.width, + }; let value = value.to_biguint(); format_veryl_display_arg( &DisplayFormatArg { value: &value, mask: None, - width: arg.width, + width, signed: arg.signed, is_string: arg.is_string, }, @@ -223,8 +240,19 @@ fn sim_set_target( target: &TestbenchTarget, value: TbValue, ) { + if let TbValue::String(bytes) = value { + let index = target.selection.as_ref().map_or(0, |selection| { + eval_expr(sim, &selection.offset).to_u64() as usize + }); + if index < target.signal.width { + sim.testbench_strings + .insert((target.signal.offset, index), bytes); + } + return; + } let Some(selection) = &target.selection else { match value { + TbValue::String(_) => unreachable!(), TbValue::U64(value) => sim_set_u64(sim, target.signal, value), TbValue::Wide(value) => sim.set_wide(target.signal, value), } @@ -400,6 +428,7 @@ fn eval_loop_bound( decode_signed_loop_bound(value, *width) } else { match value { + TbValue::String(_) => unreachable!("string loop bound"), TbValue::U64(v) => match usize::try_from(v) { Ok(v) => Ok(EvaluatedLoopBound::Unsigned(v)), Err(_) => Ok(EvaluatedLoopBound::UnsignedWide(BigUint::from(v))), @@ -427,6 +456,7 @@ fn decode_signed_loop_bound( ) -> Result { let width = width.max(1); match value { + TbValue::String(_) => unreachable!("string loop bound"), TbValue::U64(v) => { let raw = if width >= 64 { v as u128 diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 840858afa2e..65c944cffb1 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -2229,11 +2229,13 @@ fn upstream_string_argument_and_host_file_service_roundtrip() { module t { var component: $comp::celox_counter; var value: logic<8>; + var path: string; initial { component.set(42); component.save("state.bin"); component.set(0); - component.load("state.bin"); + path = "state.bin"; + component.load(path); value = component.get(); $assert(value == 42, "file service roundtrip"); $finish(); diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index c9c10bdbdd2..8e14a0e6962 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -4,28 +4,114 @@ mod test_utils; all_backends! { + fn tb_string_array_elements(sim) { + @omit_veryl; + @ignore_on(sv); + @case "tb_string::array_elements"; + } + fn tb_string_function_argument(sim) { + @omit_veryl; + @ignore_on(sv); + @case "tb_string::function_argument"; + } + fn tb_string_assignment(sim) { @omit_veryl; // Veryl does not emit #[test] modules into SystemVerilog. - // Celox currently truncates string assignments to the nominal one-bit width. - // All six Celox configurations fail these cases; the support PR enables them. - @ignore_on(native, cranelift, wasm, interp, sv); + @ignore_on(sv); @case "tb_string::assignment"; } fn tb_string_comparison(sim) { @omit_veryl; // Veryl does not emit #[test] modules into SystemVerilog. - // Celox currently truncates string assignments to the nominal one-bit width. - // All six Celox configurations fail these cases; the support PR enables them. - @ignore_on(native, cranelift, wasm, interp, sv); + @ignore_on(sv); @case "tb_string::comparison"; } fn tb_string_control_flow(sim) { @omit_veryl; // Veryl does not emit #[test] modules into SystemVerilog. - // Celox currently truncates string assignments to the nominal one-bit width. - // All six Celox configurations fail these cases; the support PR enables them. - @ignore_on(native, cranelift, wasm, interp, sv); + @ignore_on(sv); @case "tb_string::control_flow"; } } + +#[test] +fn strings_survive_clock_steps_and_preserve_message_lengths() { + let result = celox::Simulator::builder( + r#" + #[test(Top)] module Top { + var text: string; + inst clk: $tb::clock_gen; + initial { + text = "long string across a clock step"; + clk.next(); + $assert(text == "long string across a clock step", "[%s]", text); + text = ""; + $assert(text == "", "[%s]", text); + $finish(); + } + } + "#, + "Top", + ) + .run_test_detailed() + .unwrap(); + assert!(result.passed); + assert_eq!( + result.assertions[0].message.as_deref(), + Some(b"[long string across a clock step]".as_slice()) + ); + assert_eq!( + result.assertions[1].message.as_deref(), + Some(b"[]".as_slice()) + ); +} + +#[test] +fn checkpoint_restores_string_values() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let mut sim = celox::Simulator::builder( + r#" + #[test(Top)] module Top { + var text: string; + var mode: u32; + initial { + if mode == 0 { text = "saved string"; } + else if mode == 1 { text = "replacement"; } + else { $assert(text == "saved string"); } + $finish(); + } + } + "#, + "Top", + ) + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let mode = sim.signal("mode"); + sim.set(mode, 0u32); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let saved = sim.checkpoint().unwrap(); + assert_eq!(saved.state_size(), empty_size + b"saved string".len()); + assert!( + sim.save_state() + .unwrap_err() + .to_string() + .contains("dynamic testbench strings") + ); + sim.set(mode, 1u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + sim.restore(&saved).unwrap(); + sim.set(mode, 2u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); +} diff --git a/packages/celox/src/e2e.test.ts b/packages/celox/src/e2e.test.ts index 980df01b299..0161bc808b7 100644 --- a/packages/celox/src/e2e.test.ts +++ b/packages/celox/src/e2e.test.ts @@ -3534,6 +3534,35 @@ module CounterTbPassSecond { `; describe("E2E: native testbench (runTest)", () => { + test("dynamic strings retain their length in native testbench assertions", () => { + const result = runTest( + [ + { + path: "strings.veryl", + content: ` + #[test(Top)] module Top { + var text: string; + initial { + text = "a dynamic string longer than eight bytes"; + $assert(text == "a dynamic string longer than eight bytes", "[%s]", text); + text = ""; + $assert(text == "", "[%s]", text); + $finish(); + } + } + `, + }, + ], + "Top", + ); + expect(result.passed).toBe(true); + expect( + result.assertions.map((assertion) => + new TextDecoder().decode(assertion.message!), + ), + ).toEqual(["[a dynamic string longer than eight bytes]", "[]"]); + }); + const addon = loadNativeAddon(); test("passing testbench returns passed=true with all assertions passed", () => { From 1f0c1c0fae3b267e0fc1ab6c082588b071a4f683 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 04:48:29 +0900 Subject: [PATCH 2/3] fix(testbench): preserve string lets and reject unsupported operations --- crates/celox-frontend-veryl/src/schedule.rs | 49 ++++++++ crates/celox-frontend-veryl/src/source.rs | 2 + crates/celox-frontend-veryl/src/testbench.rs | 64 ++++++++++ crates/celox/tests/testbench_string.rs | 124 +++++++++++++++++++ packages/celox/src/e2e.test.ts | 4 +- 5 files changed, 242 insertions(+), 1 deletion(-) diff --git a/crates/celox-frontend-veryl/src/schedule.rs b/crates/celox-frontend-veryl/src/schedule.rs index f9a056536a5..bf56a6fce0d 100644 --- a/crates/celox-frontend-veryl/src/schedule.rs +++ b/crates/celox-frontend-veryl/src/schedule.rs @@ -73,6 +73,53 @@ pub fn schedule_symbolic_rtl( trace, )?; let lookup = &output.scheduled.frontend_lookup; + let mut constant_strings = crate::HashMap::default(); + for (&instance, module_id) in &lookup.instance_module { + let Some(module) = module_ir.get(module_id) else { + continue; + }; + let Some(variables) = source_id_maps.get(module_id) else { + continue; + }; + for declaration in &module.declarations { + let Declaration::Comb(comb) = declaration else { + continue; + }; + for statement in &comb.statements { + let veryl_analyzer::ir::Statement::Assign(assign) = statement else { + continue; + }; + if !assign.expr.comptime().r#type.is_string() + || assign.hier_dst.is_some() + || assign.dst.len() != 1 + { + continue; + } + let dst = &assign.dst[0]; + let Some(variable) = module.variables.get(&dst.id) else { + continue; + }; + if !matches!(variable.kind, veryl_analyzer::ir::VarKind::Let) { + continue; + } + if !assign.expr.comptime().is_const + || assign.expr.comptime().get_value().is_err() + || variable.r#type.is_array() + { + return Err(ParserError::illegal_context( + "string let initializer", + "Celox currently supports only constant scalar string let initializers", + Some(&variable.token), + )); + } + if let Some(id) = variables.get(&dst.id) + && let Some((address, _)) = lookup.instance_variable(instance, *id) + { + constant_strings.insert(address, assign.expr.clone()); + } + } + } + } let mut child_sources = Vec::new(); let mut components = Vec::new(); let mut component_bindings = Vec::new(); @@ -97,6 +144,7 @@ pub fn schedule_symbolic_rtl( .collect(); if blocks.iter().any(|block| !block.is_empty()) { child_sources.push(VerylTestbenchSource { + constant_strings: constant_strings.clone(), id_map: VerylIdMap { module_variables: source_id_maps .get(module_id) @@ -132,6 +180,7 @@ pub fn schedule_symbolic_rtl( component_bindings.append(&mut instance_bindings); } let testbench_source = VerylTestbenchSource { + constant_strings, id_map: VerylIdMap { module_variables: source_id_maps, }, diff --git a/crates/celox-frontend-veryl/src/source.rs b/crates/celox-frontend-veryl/src/source.rs index 3e441520ff5..f27aebc3a86 100644 --- a/crates/celox-frontend-veryl/src/source.rs +++ b/crates/celox-frontend-veryl/src/source.rs @@ -56,6 +56,8 @@ impl VerylIdMap { #[derive(Clone, Default)] pub struct VerylTestbenchSource { pub id_map: VerylIdMap, + /// Constant scalar string lets are continuous assignments, outside initial blocks. + pub constant_strings: HashMap, pub initial_statements: Option>, /// Length of each initial block in `initial_statements`; empty means one block. pub initial_block_lengths: Vec, diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 9c31392c803..1c008f4e210 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -1061,6 +1061,7 @@ struct ExprCompiler<'a> { lookup: &'a FrontendLookup, id_map: &'a VerylIdMap, functions: &'a HashMap, + constant_strings: &'a HashMap, base_instance: InstanceId, } @@ -1464,6 +1465,11 @@ impl ExprCompiler<'_> { select: &VarSelect, ops: &mut Vec, ) { + if let Some(expression) = self.constant_strings.get(&address) { + self.emit(expression, ops); + return; + } + let target = self .resolve_target_parts( SemanticSignal { @@ -2624,6 +2630,7 @@ impl<'a> SemanticTestbenchBuilder<'a> { let ec = ExprCompiler { lookup: self.lookup, id_map: &self.testbench_source.id_map, + constant_strings: &self.testbench_source.constant_strings, functions: &self.testbench_source.functions, base_instance, }; @@ -2653,6 +2660,7 @@ impl<'a> SemanticTestbenchBuilder<'a> { let ec = ExprCompiler { lookup: self.lookup, id_map: &self.testbench_source.id_map, + constant_strings: &self.testbench_source.constant_strings, functions: &component.functions, base_instance: component.parent_instance, }; @@ -3253,6 +3261,37 @@ fn validate_testbench_expression( source: &VerylTestbenchSource, active_functions: &mut FxHashSet<(VarId, Option>)>, ) -> Result<(), ParserError> { + if let Expression::Term(factor) = expression + && factor.comptime().r#type.is_string() + { + let access = match factor.as_ref() { + Factor::Variable(id, index, select, _) => source + .id_map + .instance_var(lookup, source.base_instance(lookup), *id) + .and_then(|id| lookup.instance_variable(source.base_instance(lookup), id)) + .map(|(_, info)| (info, index, select)), + Factor::HierVariable(reference) => Some(( + resolve_hierarchical_reference_from( + lookup, + source.base_instance(lookup), + reference, + )? + .1, + &reference.index, + &reference.select, + )), + _ => None, + }; + if let Some((info, index, select)) = access + && (index.0.len() > info.array_dims.len() || !select.0.is_empty() || select.1.is_some()) + { + return Err(ParserError::illegal_context( + "string character selection", + "character indexing and slicing of strings are not supported in Celox testbenches", + Some(&factor.comptime().token), + )); + } + } match expression { Expression::Term(factor) => match factor.as_ref() { Factor::HierVariable(reference) => { @@ -3309,9 +3348,23 @@ fn validate_testbench_expression( Factor::Value(_) | Factor::Anonymous(_) | Factor::Unknown(_) => Ok(()), }, Expression::Unary(_, inner, _) => { + if inner.comptime().r#type.is_string() { + return Err(ParserError::illegal_context( + "unary string operation", + "unary operations on strings are not supported in Celox testbenches", + Some(&inner.comptime().token), + )); + } validate_testbench_expression(inner, lookup, source, active_functions) } Expression::Binary(lhs, _, rhs, _) => { + if lhs.comptime().r#type.is_string() != rhs.comptime().r#type.is_string() { + return Err(ParserError::illegal_context( + "mixed string operation", + "operations mixing string and non-string operands are not supported in Celox testbenches", + Some(&expression.comptime().token), + )); + } validate_testbench_expression(lhs, lookup, source, active_functions)?; validate_testbench_expression(rhs, lookup, source, active_functions) } @@ -3322,6 +3375,13 @@ fn validate_testbench_expression( } Expression::Concatenation(items, _) => { for (expression, repeat) in items { + if expression.comptime().r#type.is_string() { + return Err(ParserError::illegal_context( + "string concatenation or replication", + "string concatenation and replication are not supported in Celox testbenches", + Some(&expression.comptime().token), + )); + } validate_testbench_expression(expression, lookup, source, active_functions)?; if let Some(repeat) = repeat { validate_testbench_expression(repeat, lookup, source, active_functions)?; @@ -3619,6 +3679,7 @@ fn validate_testbench_hierarchical_destination( let compiler = ExprCompiler { lookup, id_map: &source.id_map, + constant_strings: &source.constant_strings, functions: &source.functions, base_instance: source.base_instance(lookup), }; @@ -3650,6 +3711,7 @@ fn validate_testbench_destination( ExprCompiler { lookup, id_map: &source.id_map, + constant_strings: &source.constant_strings, functions: &source.functions, base_instance: source.base_instance(lookup), } @@ -3841,6 +3903,7 @@ mod tests { let compiler = ExprCompiler { lookup: &lookup, id_map: &source.id_map, + constant_strings: &source.constant_strings, functions: &source.functions, base_instance: lookup.root_instance_and_module().unwrap().0, }; @@ -3860,6 +3923,7 @@ mod tests { let compiler = ExprCompiler { lookup: &lookup, id_map: &source.id_map, + constant_strings: &source.constant_strings, functions: &source.functions, base_instance: lookup.root_instance_and_module().unwrap().0, }; diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index 8e14a0e6962..160df6dc3d5 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -35,6 +35,55 @@ all_backends! { } } +#[test] +fn let_and_var_strings_preserve_display_values() { + // Regression for https://github.com/veryl-lang/veryl/issues/3555. + let result = celox::Simulator::builder( + r#" + #[test(Top)] module Top { + let a: string = "hi"; + var b: string; + const C: string = "const"; + initial { + b = "hello"; + $display("let : %s", a); + $display("var : %s", b); + $display("const: %s", C); + $display(a); + $display(b); + // Assertion messages use the same renderer as $display and + // let the test check the bytes, not just successful execution. + $assert(a == "hi", "let : %s", a); + $assert(b == "hello", "var : %s", b); + $assert(C == "const", "const: %s", C); + $assert(1, a); + $assert(1, b); + $finish(); + } + } + "#, + "Top", + ) + .run_test_detailed() + .unwrap(); + assert!(result.passed); + let messages: Vec<_> = result + .assertions + .iter() + .map(|assertion| assertion.message.as_deref().unwrap()) + .collect(); + assert_eq!( + messages, + [ + b"let : hi".as_slice(), + b"var : hello".as_slice(), + b"const: const".as_slice(), + b"hi".as_slice(), + b"hello".as_slice(), + ] + ); +} + #[test] fn strings_survive_clock_steps_and_preserve_message_lengths() { let result = celox::Simulator::builder( @@ -115,3 +164,78 @@ fn checkpoint_restores_string_values() { celox::TestResult::Pass ); } + +#[test] +fn unsupported_string_concatenation_is_rejected() { + for expression in ["{a, b}", "{a repeat 2}"] { + let source = format!( + r#"#[test(Top)] module Top {{ + var a: string; + var b: string; + initial {{ + a = "hello"; + b = "world"; + $display({expression}); + $finish(); + }} + }}"#, + ); + let error = celox::Simulator::builder(&source, "Top") + .run_test_detailed() + .unwrap_err(); + assert!( + error.to_string().contains("string concatenation"), + "{expression}: {error}" + ); + } +} + +#[test] +fn dynamic_string_let_is_rejected() { + let error = celox::Simulator::builder( + r#"#[test(Top)] module Top { + var text: string; + let mirrored: string = text; + initial { + text = "hello"; + $display(mirrored); + $finish(); + } + }"#, + "Top", + ) + .run_test_detailed() + .unwrap_err(); + assert!( + error.to_string().contains("string let initializer"), + "{error:?}" + ); +} + +#[test] +fn unsupported_string_operations_are_rejected() { + for expression in [ + "~text", + "text == 1'b1", + "text.len()", + "text[0]", + "text.substr(0, 1)", + ] { + let source = format!( + r#"#[test(Top)] module Top {{ + var text: string; + initial {{ + text = "hello"; + $display({expression}); + $finish(); + }} + }}"#, + ); + assert!( + celox::Simulator::builder(&source, "Top") + .run_test_detailed() + .is_err(), + "{expression}" + ); + } +} diff --git a/packages/celox/src/e2e.test.ts b/packages/celox/src/e2e.test.ts index 0161bc808b7..08cbf81d425 100644 --- a/packages/celox/src/e2e.test.ts +++ b/packages/celox/src/e2e.test.ts @@ -3541,8 +3541,10 @@ describe("E2E: native testbench (runTest)", () => { path: "strings.veryl", content: ` #[test(Top)] module Top { + let greeting: string = "hi"; var text: string; initial { + $assert(greeting == "hi", greeting); text = "a dynamic string longer than eight bytes"; $assert(text == "a dynamic string longer than eight bytes", "[%s]", text); text = ""; @@ -3560,7 +3562,7 @@ describe("E2E: native testbench (runTest)", () => { result.assertions.map((assertion) => new TextDecoder().decode(assertion.message!), ), - ).toEqual(["[a dynamic string longer than eight bytes]", "[]"]); + ).toEqual(["hi", "[a dynamic string longer than eight bytes]", "[]"]); }); const addon = loadNativeAddon(); From c03a79cf2363f735562eff345e2d387b53d57d82 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 05:01:16 +0900 Subject: [PATCH 3/3] test(testbench): count supported array and function string cases --- crates/celox-test-suite/tests/external_adapter.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/celox-test-suite/tests/external_adapter.rs b/crates/celox-test-suite/tests/external_adapter.rs index effbd8135cd..abb2a17ced4 100644 --- a/crates/celox-test-suite/tests/external_adapter.rs +++ b/crates/celox-test-suite/tests/external_adapter.rs @@ -93,7 +93,7 @@ fn catalogue_has_unique_stable_names_and_categories() { assert!(names.insert(case.name), "duplicate {}", case.name); assert!(case.name.contains("::")); } - assert_eq!(names.len(), 752); + assert_eq!(names.len(), 754); assert_eq!( case("operators::test_bitwise_operations").unwrap().category, Category::Operators