diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index d7d5900c148..44298ea22e2 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1809,6 +1809,8 @@ fn unify_clock_domains( modules: &HashMap, ) -> HashMap { let mut drive_graph: HashMap> = HashMap::default(); + // The edge each clock is sensed at: `true` rising, `false` falling. + let mut polarities: HashMap = HashMap::default(); for (path, id) in expanded { let module_id = &instance_modules[id]; @@ -1820,6 +1822,20 @@ fn unify_clock_domains( .get(&var) .map(|variable| variable.metadata.width) }; + let mut record_polarity = |module: &SimModule, instance: InstanceId, var: SourceVarId| { + let polarity = + module + .variables + .get(&var) + .and_then(|variable| match variable.metadata.kind { + DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh => Some(true), + DomainKind::ClockNegedge | DomainKind::ResetAsyncLow => Some(false), + _ => None, + }); + if let Some(polarity) = polarity { + polarities.insert(bindings.locate(instance, var), polarity); + } + }; // Internal aliases (e.g. `assign clk_internal = clk_port;`) for logic_path in &sim_module.comb_blocks { @@ -1832,6 +1848,8 @@ fn unify_clock_domains( |target| width(sim_module, target), |source| width(sim_module, source), ) { + record_polarity(sim_module, *id, target); + record_polarity(sim_module, *id, source); drive_graph .entry(bindings.locate(*id, source)) .or_default() @@ -1854,6 +1872,8 @@ fn unify_clock_domains( if let Some((GlueAddr::Child(child_var), GlueAddr::Parent(parent_var))) = whole_variable_copy(&glue_block.arena, logic_path, glue_width, glue_width) { + record_polarity(child_module, child_id, child_var); + record_polarity(sim_module, *id, parent_var); drive_graph .entry(bindings.locate(*id, parent_var)) .or_default() @@ -1872,6 +1892,8 @@ fn unify_clock_domains( |_| parent_width, glue_width, ) { + record_polarity(child_module, child_id, child_var); + record_polarity(sim_module, *id, *parent_var); drive_graph .entry(bindings.locate(child_id, child_var)) .or_default() @@ -1882,6 +1904,68 @@ fn unify_clock_domains( } } + // A copy sensed at the opposite edge of its source is a clock of its own: + // `always_ff @(negedge d)` with `assign c = clk; assign d = c;` runs when + // `clk` falls, not in `clk`'s rising domain. A copy sensed at no edge + // takes the edge of its drivers, and a root sensed at no edge the edge of + // its first copy sensed at one. Copies that join edges of both kinds are + // cut apart. + let drivers = { + let mut drivers: HashMap> = HashMap::default(); + for (src, sinks) in &drive_graph { + for sink in sinks { + drivers.entry(*sink).or_default().push(*src); + } + } + drivers + }; + let root_polarity = |root: AbsoluteAddr| { + polarities.get(&root).copied().or_else(|| { + let mut stack = vec![root]; + let mut visited = HashSet::default(); + while let Some(addr) = stack.pop() { + if !visited.insert(addr) { + continue; + } + if let Some(&polarity) = polarities.get(&addr) { + return Some(polarity); + } + if let Some(sinks) = drive_graph.get(&addr) { + stack.extend(sinks.iter().rev()); + } + } + None + }) + }; + let effective_polarity = |addr: AbsoluteAddr| { + let mut current = addr; + let mut visited = HashSet::default(); + loop { + if let Some(&polarity) = polarities.get(¤t) { + return Some(polarity); + } + match drivers.get(¤t).and_then(|sources| sources.first()) { + Some(&next) if visited.insert(next) => current = next, + _ => return root_polarity(current), + } + } + }; + let drive_graph: HashMap> = drive_graph + .iter() + .map(|(src, sinks)| { + let src_polarity = effective_polarity(*src); + let sinks = sinks + .iter() + .copied() + .filter(|sink| match (src_polarity, effective_polarity(*sink)) { + (Some(a), Some(b)) => a == b, + _ => true, + }) + .collect(); + (*src, sinks) + }) + .collect(); + // Resolve Canonical Clock Domains: Find the root driver for each connected component let mut clock_domains: HashMap = HashMap::default(); 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 07d25bbf427..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, } @@ -1167,6 +1168,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 +1250,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 +1372,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 +1457,41 @@ impl ExprCompiler<'_> { } } + fn emit_string_access( + &self, + address: StateAddr, + info: &VariableInfo, + index: &VarIndex, + 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 { + 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 +1542,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 +1569,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 +1589,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)); } @@ -2520,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, }; @@ -2549,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, }; @@ -3149,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) => { @@ -3205,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) } @@ -3218,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)?; @@ -3515,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), }; @@ -3546,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), } @@ -3737,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, }; @@ -3756,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-runtime/src/parallel.rs b/crates/celox-runtime/src/parallel.rs index 1698dfb68ae..fe2e149e72b 100644 --- a/crates/celox-runtime/src/parallel.rs +++ b/crates/celox-runtime/src/parallel.rs @@ -753,73 +753,6 @@ mod tests { let second_pool = LanePool::new(1).unwrap(); assert_ne!(id, second_pool.diagnostic_id); } - - #[test] - fn traced_failure_and_recovery_record_skips_and_real_waits() { - use std::collections::BTreeMap; - #[derive(Clone)] - struct Capture(Arc>>>); - struct Fields(BTreeMap); - impl tracing::field::Visit for Fields { - fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { - self.0.insert(field.name().into(), format!("{value:?}")); - } - } - impl tracing::Subscriber for Capture { - fn max_level_hint(&self) -> Option { - Some(tracing::metadata::LevelFilter::TRACE) - } - fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { - metadata.target() == "celox::parallel" - } - fn register_callsite( - &self, - _: &'static tracing::Metadata<'static>, - ) -> tracing::subscriber::Interest { - tracing::subscriber::Interest::sometimes() - } - fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { - tracing::span::Id::from_u64(1) - } - fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} - fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} - fn enter(&self, _: &tracing::span::Id) {} - fn exit(&self, _: &tracing::span::Id) {} - fn event(&self, event: &tracing::Event<'_>) { - let mut fields = Fields(BTreeMap::new()); - event.record(&mut fields); - self.0.lock().unwrap().push(fields.0); - } - } - let events = Arc::new(Mutex::new(Vec::new())); - tracing::subscriber::with_default(Capture(events.clone()), || { - let (schedule, predecessors) = chain_schedule(); - let mut pool = LanePool::new(3).unwrap(); - assert!( - pool.run(&schedule, &recorder(predecessors.clone(), Some(0))) - .is_err() - ); - pool.run(&schedule, &recorder(predecessors, None)).unwrap(); - }); - let events = events.lock().unwrap(); - let rows = |name: &str| { - let name = format!("{name:?}"); - events.iter().filter(move |e| e["event"] == name) - }; - assert_eq!(rows("dispatch").count(), 2, "{events:?}"); - let runs = rows("task_run").collect::>(); - assert_eq!(runs.len(), 8); - assert!(runs.iter().any(|e| e["skipped"] == "true")); - for event in runs.iter().filter(|e| e["epoch"] == "2") { - assert_eq!(event["skipped"], "false"); - assert_eq!(event["code"], "0"); - assert!( - event["end_ns"].parse::().unwrap() - >= event["start_ns"].parse::().unwrap() - ); - } - assert_eq!(rows("task_wait").filter(|e| e["epoch"] == "2").count(), 3); - } } /// Which implementation of a kernel to run next. diff --git a/crates/celox-runtime/tests/parallel_tracing.rs b/crates/celox-runtime/tests/parallel_tracing.rs new file mode 100644 index 00000000000..a0b5f0beed3 --- /dev/null +++ b/crates/celox-runtime/tests/parallel_tracing.rs @@ -0,0 +1,117 @@ +//! Keep this capture in its own test binary so its global subscriber cannot +//! collect events from unrelated runtime tests. A thread-local subscriber can +//! lose callsite interest when another thread first uses LanePool without it +//! (https://github.com/celox-sim/celox/issues/1374). + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + +use celox_runtime::parallel::{ + LanePool, LaneSchedule, LaneTaskFailure, LaneTaskRunner, LaneTaskSpec, +}; + +struct Capture(Arc>>>); +struct Fields(BTreeMap); + +impl tracing::field::Visit for Fields { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + self.0.insert(field.name().into(), format!("{value:?}")); + } +} + +impl tracing::Subscriber for Capture { + fn max_level_hint(&self) -> Option { + Some(tracing::metadata::LevelFilter::TRACE) + } + fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { + metadata.target() == "celox::parallel" + } + fn register_callsite( + &self, + _: &'static tracing::Metadata<'static>, + ) -> tracing::subscriber::Interest { + tracing::subscriber::Interest::sometimes() + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + let mut fields = Fields(BTreeMap::new()); + event.record(&mut fields); + self.0.lock().unwrap().push(fields.0); + } +} + +struct Runner { + fail: Option, +} + +impl LaneTaskRunner for Runner { + fn run_task(&self, task: usize) -> i64 { + if self.fail == Some(task) { 7 } else { 0 } + } +} + +#[test] +fn traced_failure_and_recovery_record_skips_and_real_waits() { + let events = Arc::new(Mutex::new(Vec::new())); + tracing::subscriber::set_global_default(Capture(events.clone())).unwrap(); + + // First use the runtime's callsites on a different thread from the one + // that installed the subscriber, as happens with concurrent unit tests. + std::thread::spawn(|| { + // lane 0: t0, t2; lane 1: t1 (waits for t0); lane 2: t3 (waits for t1, t2) + let schedule = LaneSchedule::new( + 3, + vec![ + LaneTaskSpec { + lane: 0, + waits: vec![], + }, + LaneTaskSpec { + lane: 1, + waits: vec![(0, 1)], + }, + LaneTaskSpec { + lane: 0, + waits: vec![], + }, + LaneTaskSpec { + lane: 2, + waits: vec![(1, 1), (0, 2)], + }, + ], + ) + .unwrap(); + let mut pool = LanePool::new(3).unwrap(); + assert_eq!( + pool.run(&schedule, &Runner { fail: Some(0) }), + Err(LaneTaskFailure { task: 0, code: 7 }) + ); + pool.run(&schedule, &Runner { fail: None }).unwrap(); + }) + .join() + .unwrap(); + + let events = events.lock().unwrap(); + let rows = |name: &str| { + let name = format!("{name:?}"); + events.iter().filter(move |e| e["event"] == name) + }; + assert_eq!(rows("dispatch").count(), 2, "{events:?}"); + let runs = rows("task_run").collect::>(); + assert_eq!(runs.len(), 8); + assert!(runs.iter().any(|e| e["skipped"] == "true")); + for event in runs.iter().filter(|e| e["epoch"] == "2") { + assert_eq!(event["skipped"], "false"); + assert_eq!(event["code"], "0"); + assert!( + event["end_ns"].parse::().unwrap() >= event["start_ns"].parse::().unwrap() + ); + } + assert_eq!(rows("task_wait").filter(|e| e["epoch"] == "2").count(), 3); +} 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-test-suite/tests/external_adapter.rs b/crates/celox-test-suite/tests/external_adapter.rs index ee5626b4b9b..6f25ed0416c 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(), 760); + assert_eq!(names.len(), 762); assert_eq!( case("operators::test_bitwise_operations").unwrap().category, Category::Operators 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 a400230db27..8c7393b161a 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -98,6 +98,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, @@ -694,6 +696,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 0f208cb6177..f42f5b940ec 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -2234,11 +2234,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/derived_register_clock.rs b/crates/celox/tests/derived_register_clock.rs index 5951c5c167f..b7cf39ab08a 100644 --- a/crates/celox/tests/derived_register_clock.rs +++ b/crates/celox/tests/derived_register_clock.rs @@ -687,3 +687,178 @@ fn a_systemverilog_child_clock_into_a_vector_bit() { check_sv(&source, 8, &want); } } + +/// Drives `clk` low and high four times and checks that `cnt` counts the +/// falling edges only. +fn check_falling_edges(mut timed: Simulation) { + let cnt = timed.signal("cnt"); + for (port, time, value) in [("rst", 0, 1), ("clk", 0, 1), ("rst", 1, 0), ("rst", 2, 1)] { + timed.schedule(port, time, value).unwrap(); + timed.step().unwrap(); + } + for cycle in 0..4u64 { + timed.schedule("clk", 10 + cycle * 20, 0).unwrap(); + timed.step().unwrap(); + assert_eq!(timed.get(cnt), (cycle + 1).into(), "falling edge {cycle}"); + timed.schedule("clk", 20 + cycle * 20, 1).unwrap(); + timed.step().unwrap(); + assert_eq!(timed.get(cnt), (cycle + 1).into(), "rising edge {cycle}"); + } +} + +/// A whole copy of `clk` sensed at its falling edge does not join `clk`'s +/// rising domain. +#[test] +fn a_clock_copy_sensed_at_the_falling_edge_runs_on_the_falling_edge() { + check_falling_edges( + Simulation::builder( + r#" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + cnt: output logic<8>, +) { + var c: '_ clock_negedge; + var b: logic<8>; + assign c = clk; + always_ff (c, rst) { + if_reset { b = 0; } else { b = b + 8'd1; } + } + assign cnt = b; +} +"#, + "Top", + ) + .build() + .unwrap(), + ); +} + +/// The same for a child clock port sensed at the falling edge. +#[test] +fn a_falling_edge_child_clock_port_runs_on_the_falling_edge() { + check_falling_edges( + Simulation::builder( + r#" +module Child ( + clk: input '_ clock_negedge, + rst: input '_ reset_async_low, + cnt: output logic<8>, +) { + var b: logic<8>; + always_ff (clk, rst) { + if_reset { b = 0; } else { b = b + 8'd1; } + } + assign cnt = b; +} + +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + cnt: output logic<8>, +) { + var a: logic<8>; + always_ff (clk, rst) { + if_reset { a = 0; } else { a = a + 8'd1; } + } + inst u: Child (clk, rst, cnt); +} +"#, + "Top", + ) + .build() + .unwrap(), + ); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn a_systemverilog_clock_copy_sensed_at_the_falling_edge() { + let source = "module Top(input logic clk, input logic rst, output logic [7:0] cnt); + logic c; + logic [7:0] a; + assign c = clk; + always_ff @(posedge clk or negedge rst) if (!rst) a <= 0; else a <= a + 1; + always_ff @(negedge c or negedge rst) if (!rst) cnt <= 0; else cnt <= cnt + 1; + endmodule"; + let path = std::path::Path::new("derived_register_clock.sv"); + check_falling_edges( + Simulation::from_sv_sources(vec![(source, path)], "Top") + .build() + .unwrap(), + ); +} + +#[cfg(feature = "systemverilog")] +fn check_sv_falling_edges(source: &str) { + let path = std::path::Path::new("derived_register_clock.sv"); + check_falling_edges( + Simulation::from_sv_sources(vec![(source, path)], "Top") + .build() + .unwrap(), + ); +} + +/// A copy of a copy takes its edge from the end of the chain that is sensed. +#[cfg(feature = "systemverilog")] +#[test] +fn a_systemverilog_chain_of_clock_copies_sensed_at_the_falling_edge() { + check_sv_falling_edges( + "module Top(input logic clk, input logic rst, output logic [7:0] cnt); + logic c, d; + logic [7:0] a; + assign c = clk; + assign d = c; + always_ff @(posedge clk or negedge rst) if (!rst) a <= 0; else a <= a + 1; + always_ff @(negedge d or negedge rst) if (!rst) cnt <= 0; else cnt <= cnt + 1; + endmodule", + ); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn a_systemverilog_chain_of_clock_copies_through_a_child_port() { + check_sv_falling_edges( + "module Child(input logic k, input logic rst, output logic [7:0] cnt); + logic j; + assign j = k; + always_ff @(negedge j or negedge rst) if (!rst) cnt <= 0; else cnt <= cnt + 1; + endmodule + module Top(input logic clk, input logic rst, output logic [7:0] cnt); + logic c; + logic [7:0] a; + assign c = clk; + always_ff @(posedge clk or negedge rst) if (!rst) a <= 0; else a <= a + 1; + Child u(.k(c), .rst(rst), .cnt(cnt)); + endmodule", + ); +} + +/// Copies of a clock that is itself sensed at no edge, one at each edge. +#[cfg(feature = "systemverilog")] +#[test] +fn a_systemverilog_unsensed_clock_copied_to_both_edges() { + for (first, second) in [("posedge c", "negedge d"), ("negedge d", "posedge c")] { + let block = |edge: &str| { + if edge.ends_with('c') { + format!("always_ff @({edge} or negedge rst) if (!rst) a <= 0; else a <= a + 1;") + } else { + format!( + "always_ff @({edge} or negedge rst) if (!rst) cnt <= 0; else cnt <= cnt + 1;" + ) + } + }; + check_sv_falling_edges(&format!( + "module Top(input logic clk, input logic rst, output logic [7:0] cnt); + logic c, d; + logic [7:0] a; + assign c = clk; + assign d = clk; + {} + {} + endmodule", + block(first), + block(second), + )); + } +} diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index c9c10bdbdd2..160df6dc3d5 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -4,28 +4,238 @@ 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 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( + 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 + ); +} + +#[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 980df01b299..08cbf81d425 100644 --- a/packages/celox/src/e2e.test.ts +++ b/packages/celox/src/e2e.test.ts @@ -3534,6 +3534,37 @@ 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 { + 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 = ""; + $assert(text == "", "[%s]", text); + $finish(); + } + } + `, + }, + ], + "Top", + ); + expect(result.passed).toBe(true); + expect( + result.assertions.map((assertion) => + new TextDecoder().decode(assertion.message!), + ), + ).toEqual(["hi", "[a dynamic string longer than eight bytes]", "[]"]); + }); + const addon = loadNativeAddon(); test("passing testbench returns passed=true with all assertions passed", () => {