diff --git a/crates/celox-frontend-sv/src/lowering/ff/containers.rs b/crates/celox-frontend-sv/src/lowering/ff/containers.rs index f186dd2b127..7754a5893b9 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/containers.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/containers.rs @@ -4,6 +4,34 @@ use celox_heap::{containers as heap, ops::encode}; use sv::ir::{ContainerKind, ContainerLayout, ContainerOp, HandleProperty}; impl Ff<'_, '_> { + /// The heap's parameter for a container of `layout`. + pub(super) fn container_parameter(&self, layout: ContainerLayout) -> u64 { + let (kind, capacity, signed_key, string_key, object_key) = match layout.kind { + ContainerKind::Dynamic => (0, 0, false, false, false), + ContainerKind::Queue { capacity } => (1, capacity, false, false, false), + ContainerKind::Associative { + signed, + string, + object, + .. + } => (2, 0, signed, string, object), + }; + heap::parameter( + layout.width, + layout.two_state || !self.m.four_state, + match layout.handle { + None => 0, + Some(HandleProperty::String) => 1, + Some(HandleProperty::Object) => 2, + }, + kind, + capacity, + signed_key, + string_key, + object_key, + ) + } + pub(super) fn container_call( &mut self, op: ContainerOp, @@ -94,30 +122,11 @@ impl Ff<'_, '_> { *arg = self.heap_operand(arg, context, kind)?; } } - let (kind, capacity, signed_key, string_key, object_key) = match layout.kind { - ContainerKind::Dynamic => (0, 0, false, false, false), - ContainerKind::Queue { capacity } => (1, capacity, false, false, false), - ContainerKind::Associative { - signed, - string, - object, - .. - } => (2, 0, signed, string, object), + let (signed_key, string_key) = match layout.kind { + ContainerKind::Associative { signed, string, .. } => (signed, string), + ContainerKind::Dynamic | ContainerKind::Queue { .. } => (false, false), }; - let parameter = heap::parameter( - layout.width, - layout.two_state || !self.m.four_state, - match layout.handle { - None => 0, - Some(HandleProperty::String) => 1, - Some(HandleProperty::Object) => 2, - }, - kind, - capacity, - signed_key, - string_key, - object_key, - ); + let parameter = self.container_parameter(layout); let code = |opcode| encode(opcode, parameter); if op.reduction().is_some() { return self.container_reduction(op, layout, &args[0], parameter); diff --git a/crates/celox-frontend-sv/src/lowering/ff/format.rs b/crates/celox-frontend-sv/src/lowering/ff/format.rs index eb33264e74e..8b12254356a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/format.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/format.rs @@ -193,7 +193,7 @@ fn format_conversions(template: &str) -> Vec { while chars.next_if(char::is_ascii_digit).is_some() {} } if let Some(spec) = chars.next() - && "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) + && "bBoOhHxXdDiIcCsStTeEfFgGpP".contains(spec) { conversions.push(spec); } diff --git a/crates/celox-frontend-sv/src/lowering/ff/strings.rs b/crates/celox-frontend-sv/src/lowering/ff/strings.rs index fad6ab76cdd..90fcaeed7a2 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/strings.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/strings.rs @@ -7,7 +7,7 @@ //! that build a string fill a heap buffer and intern it at the end. use super::*; -use celox_heap::ops; +use celox_heap::{containers as heap, ops}; use sv::ir::{Radix, StringOp}; impl Ff<'_, '_> { @@ -44,6 +44,23 @@ impl Ff<'_, '_> { } let result = match op { StringOp::Format { .. } => unreachable!("formatted above"), + StringOp::Pattern(layout) => { + let handle = self.handle(&args[0])?; + let code = match layout { + Some(layout) => ops::encode( + heap::PATTERN, + self.container_parameter(layout) + | if layout.signed { + heap::SIGNED_ELEMENTS + } else { + 0 + }, + ), + None => heap::HANDLE_PATTERN, + }; + let buffer = self.heap_call(code, &[handle]); + self.heap_call(ops::FREEZE, &[buffer]) + } 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 f7cc27e522d..3b461c3a961 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -1543,7 +1543,7 @@ fn template_arguments(template: &str) -> usize { while chars.next_if(char::is_ascii_digit).is_some() {} } if let Some(spec) = chars.next() - && "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) + && "bBoOhHxXdDiIcCsStTeEfFgGpP".contains(spec) { count += 1; } @@ -1582,7 +1582,7 @@ pub(super) fn prepare_time_operands( let Some(spec) = chars.next() else { break; }; - if !"bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) { + if !"bBoOhHxXdDiIcCsStTeEfFgGpP".contains(spec) { continue; } if matches!(spec, 't' | 'T') diff --git a/crates/celox-heap/src/containers.rs b/crates/celox-heap/src/containers.rs index 5ab65599b27..d736b5771df 100644 --- a/crates/celox-heap/src/containers.rs +++ b/crates/celox-heap/src/containers.rs @@ -32,6 +32,17 @@ pub const SORT: u64 = 98; /// Sort sequence a descending; b selects signed integral comparison. pub const RSORT: u64 = 99; +/// `pattern(a)`: a buffer with container `a` printed as an assignment pattern +/// (IEEE 1800-2023 21.2.1.6): `'{e0, e1}` for a sequence, `'{k0:e0}` for an +/// associative array. The parameter is the container's [`parameter`], with +/// [`SIGNED_ELEMENTS`] for signed integral elements. +pub const PATTERN: u64 = 100; +/// A [`PATTERN`] parameter bit: integral elements print as signed values. +pub const SIGNED_ELEMENTS: u64 = 1 << 47; +/// `handle_pattern(a)`: a buffer with class handle `a` as [`PATTERN`] prints +/// an element: `null`, or `@` and the handle. +pub const HANDLE_PATTERN: u64 = 101; + /// The operation parameter encodes the element width (bits 0..6), whether /// it is two-state (7), its handle kind (8..9: none/string/object), container /// kind (10..11: dynamic/queue/associative), queue capacity (12..43, 0 means @@ -86,6 +97,48 @@ impl Layout { } } +/// The text of [`HANDLE_PATTERN`]. +pub(crate) fn handle_pattern(handle: u64) -> Vec { + if handle == 0 { + b"null".to_vec() + } else { + format!("@{handle}").into_bytes() + } +} + +/// `text` in double quotes, as `%p` prints a string. +fn quoted(out: &mut Vec, text: &[u8]) { + out.push(b'"'); + out.extend_from_slice(text); + out.push(b'"'); +} + +/// The `width`-bit `value` in decimal, as `%0d` prints it: an element with +/// unknown bits (`mask`) prints one character for them (IEEE 1800-2023 +/// 21.2.1.3), where X stands for unknown and Z for high-impedance bits. +fn decimal(value: u64, mask: u64, width: u32, signed: bool) -> String { + let bits = u64::MAX >> (64 - width.clamp(1, 64)); + let value = value & bits; + if mask != 0 { + let x = mask & value; + let z = mask & !value; + return match () { + _ if x == bits => "x", + _ if z == bits => "z", + _ if x == 0 => "Z", + _ => "X", + } + .into(); + } + if signed && width < 64 && value >> (width - 1) & 1 != 0 { + return ((value | !bits) as i64).to_string(); + } + if signed && width >= 64 { + return (value as i64).to_string(); + } + value.to_string() +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] struct Element { value: u64, @@ -203,6 +256,56 @@ impl Heap { } roots } + /// The text of [`PATTERN`]. Integral elements print in decimal, as + /// `%0d` does, strings in quotes, and class handles as `null` or `@` + /// and their handle. + pub(crate) fn container_pattern(&self, handle: Handle, parameter: u64) -> Vec { + let layout = Layout(parameter); + let width = (parameter & 127) as u32; + let signed = parameter & SIGNED_ELEMENTS != 0; + let element = |out: &mut Vec, element: &Element| match (parameter >> 8) & 3 { + 1 => quoted(out, self.string(element.value as Handle)), + 2 => out.extend_from_slice(&handle_pattern(element.value)), + _ => out.extend_from_slice( + decimal(element.value, element.mask & layout.bits(), width, signed).as_bytes(), + ), + }; + let mut out = b"'{".to_vec(); + match self + .containers + .get(&handle) + .map(|container| &container.contents) + { + None => {} + Some(Contents::Sequence(elements)) => { + for (index, value) in elements.iter().enumerate() { + if index > 0 { + out.extend_from_slice(b", "); + } + element(&mut out, value); + } + } + Some(Contents::Associative(entries)) => { + for (index, (key, value)) in entries.iter().enumerate() { + if index > 0 { + out.extend_from_slice(b", "); + } + match key { + Key::String(text) => quoted(&mut out, text), + Key::Integer(key) if parameter & (1 << 44) != 0 => { + out.extend_from_slice(((key ^ 1 << 63) as i64).to_string().as_bytes()) + } + Key::Integer(key) => out.extend_from_slice(key.to_string().as_bytes()), + } + out.push(b':'); + element(&mut out, value); + } + } + } + out.push(b'}'); + out + } + /// Execute a container helper. Indices have already undergone language /// conversion; invalid four-state indices use an out-of-range sentinel. pub(crate) fn container_call( @@ -469,6 +572,41 @@ mod tests { assert_ne!(old, new); } + #[test] + fn patterns_print_elements_keys_and_handles() { + let mut heap = Heap::new(); + let pattern = |heap: &mut Heap, p: u64, a: u64| { + let buffer = call(heap, PATTERN, p, a, 0, 0); + heap.take_buffer(buffer) + }; + // Four-state 4-bit elements: X, Z and both unknown digits. + let p = parameter(4, false, 0, 0, 0, false, false, false); + let a = call(&mut heap, NEW, p, 4, 0, 0); + let a = call(&mut heap, SET, p, a, 1, 0xf); + let a = call(&mut heap, SET_MASK, p, a, 1, 0); + let a = call(&mut heap, SET, p, a, 2, 0); + let a = call(&mut heap, SET_MASK, p, a, 2, 0xf); + let a = call(&mut heap, SET, p, a, 3, 0b0001); + let a = call(&mut heap, SET_MASK, p, a, 3, 0b0011); + assert_eq!(pattern(&mut heap, p, a), b"'{x, 15, z, X}"); + assert_eq!( + pattern(&mut heap, p | SIGNED_ELEMENTS, a), + b"'{x, -1, z, X}" + ); + assert_eq!(pattern(&mut heap, p, 0), b"'{}"); + // Signed integral keys print in key order. + let p = parameter(8, true, 0, 2, 0, true, false, false); + let a = call(&mut heap, SET, p, 0, 7, 1); + let a = call(&mut heap, SET_MASK, p, a, 7, 0); + let a = call(&mut heap, SET, p, a, -2i64 as u64, 2); + let a = call(&mut heap, SET_MASK, p, a, -2i64 as u64, 0); + assert_eq!(pattern(&mut heap, p, a), b"'{-2:2, 7:1}"); + let buffer = call(&mut heap, HANDLE_PATTERN, 0, 0, 0, 0); + assert_eq!(heap.take_buffer(buffer), b"null"); + let buffer = call(&mut heap, HANDLE_PATTERN, 0, 3, 0, 0); + assert_eq!(heap.take_buffer(buffer), b"@3"); + } + #[test] fn resize_copy_delete_and_four_state_defaults() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index f1bc8b4cbe4..9826d4647e0 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -121,6 +121,13 @@ impl Heap { op @ crate::containers::NEW..=crate::containers::RSORT => { self.container_call(op, parameter, a, b, c) } + crate::containers::PATTERN => { + let bytes = self.container_pattern(a as Handle, parameter); + self.new_buffer(bytes) + } + crate::containers::HANDLE_PATTERN => { + self.new_buffer(crate::containers::handle_pattern(a as u32 as u64)) + } COMPARE => ordering(self.string(a as Handle).cmp(self.string(b as Handle))), ICOMPARE => { let lower = |handle| { diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 654368947f6..454ba234470 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2877,6 +2877,8 @@ struct Function { return_real: bool, /// Whether the function returns a `string`. return_string: bool, + /// Whether the function returns a class handle. + return_handle: bool, name: String, params: Vec, /// The function's value as one expression of its arguments, or `None` diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 2fb1a538e7c..b6df3750135 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -4,6 +4,7 @@ use celox_sv_syntax::{Declarations, DimensionKind, ExprId, ExprKind}; mod calls; mod direct; mod enums; +mod format_patterns; mod lvalues; mod objects; mod references; @@ -16,6 +17,10 @@ pub(super) use direct::{ format_arguments, member_context, real_value, remove_real_division_guards, string_literal_bytes, ungroup, }; +pub(super) use format_patterns::{ + bytes_literal, format as format_call, has_pattern, pattern as format_pattern, + pattern_argument as format_pattern_argument, rewrite_format, rewrite_template, +}; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ Cast as ObjectCast, Receiver as ObjectReceiver, 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 d6eab346513..e5446d36fb6 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -246,6 +246,11 @@ enum Finish { domain: std::sync::Arc, count: bool, }, + /// `$sformatf` of the bound children, whose native expressions are `ids`. + Format { + ticks_per_unit: u64, + ids: Vec, + }, /// A read of property `property` of the object handle child. ObjectLoad(Box), /// A call of method subroutine `name` with `formals` formals; the first @@ -735,9 +740,10 @@ pub(in crate::ast) fn bind_value( } else if name == "$sformatf" { let actuals = format_arguments(&name, args)?; ( - Finish::StringCall(StringOp::Format { + Finish::Format { ticks_per_unit: timescales::time_divisor(id, tree)?, - }), + ids: actuals.clone(), + }, actuals.into_iter().map(|id| (id, None)).collect(), ) } else if name.starts_with('$') && !name.contains("::") { @@ -1228,6 +1234,17 @@ pub(in crate::ast) fn bind_value( Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } + Finish::Format { + ticks_per_unit, + ids, + } => format_patterns::format( + ticks_per_unit, + &ids, + operands, + tree, + native, + dimensions, + )?, Finish::ScopeRandomize(domains) => { // Preserve the original call when no enum is present. // Every scalar operation succeeds and returns signed int 1; @@ -1976,13 +1993,10 @@ pub(in crate::ast) fn format_arguments( /// 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 { - let bytes = string_literal_bytes(text)?; - let width = (bytes.len() * 8).max(8); - Some(format!( - "{}'h{}", - width, - num_bigint::BigUint::from_bytes_be(&bytes).to_str_radix(16) - )) + match format_patterns::bytes_literal(&string_literal_bytes(text)?) { + Expr::Literal(literal) => Some(literal), + _ => unreachable!("a packed literal"), + } } /// The bytes of string literal `text`, written with its quotes, after its diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs index ebe79bea067..88194b52f3d 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs @@ -171,17 +171,9 @@ pub(super) fn domain( }) } } - ExprKind::Cast { target, .. } => { - let target = ungroup(*target, native); - let ty = if let Some(name) = call_name(&tree.state, target, native) { - dimensions.type_aliases.get(&name).cloned() - } else if let ExprKind::Type(id) = native.expression(target).kind { - type_binding::binding::bind_in(id, native, tree, dimensions)? - } else { - None - }; - ty.as_ref().and_then(scalar) - } + ExprKind::Cast { target, .. } => cast_type(tree, *target, native, dimensions)? + .as_ref() + .and_then(scalar), ExprKind::Conditional { then_expression, else_expression, @@ -195,6 +187,24 @@ pub(super) fn domain( }) } +/// The type a cast to native `target` converts to, when `target` names a +/// type rather than a width or signedness. +pub(super) fn cast_type( + tree: &AnalysisContext<'_>, + target: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + let target = ungroup(target, native); + Ok(if let Some(name) = call_name(&tree.state, target, native) { + dimensions.type_aliases.get(&name).cloned() + } else if let ExprKind::Type(id) = native.expression(target).kind { + type_binding::binding::bind_in(id, native, tree, dimensions)? + } else { + None + }) +} + /// The enumerated type of a value of type `ty`. fn scalar(ty: &Type) -> Option> { (ty.unpacked_ranges.is_empty() && ty.container.is_none()) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/format_patterns.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/format_patterns.rs new file mode 100644 index 00000000000..9c3082ad0b7 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/format_patterns.rs @@ -0,0 +1,464 @@ +//! `%p`, the assignment pattern format (IEEE 1800-2023 21.2.1.6). +//! +//! The analyzer rewrites each `%p` of a literal format into a conversion the +//! formatter has: an integral value prints as `%0d`, a real as an unformatted +//! real, and a string, class handle or container as the `%s` of its pattern +//! text. Types whose patterns are not supported yet are rejected. + +use super::*; +use crate::system_functions::ContainerLayout; + +/// How `%p` prints a value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::ast) enum Pattern { + Integral, + String, + /// A class handle, or with its layout a container. + Handle(Option), +} + +/// The conversions of a format that take an argument (21.2.1.2). +const CONVERSIONS: &[u8] = b"bBoOhHxXdDiIcCsStTeEfFgGpP"; + +/// Whether `template` has a `%p` conversion. +pub(in crate::ast) fn has_pattern(template: &[u8]) -> bool { + let mut found = false; + let _ = rewrite_template(template, |_| { + found = true; + Ok(&b""[..]) + }); + found +} + +/// `template` with each `%p` conversion, flags and width included, replaced +/// by the conversion `replace` gives for the index of its argument among the +/// arguments the template converts. +pub(in crate::ast) fn rewrite_template( + template: &[u8], + mut replace: impl FnMut(usize) -> Converted<&'static [u8]>, +) -> Converted> { + let mut out = Vec::with_capacity(template.len()); + let mut position = 0; + let mut index = 0; + while position < template.len() { + let byte = template[position]; + if byte != b'%' { + out.push(byte); + position += 1; + continue; + } + 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 Some(&spec) = template.get(position) else { + out.extend_from_slice(&template[start..]); + break; + }; + position += 1; + if matches!(spec, b'p' | b'P') { + out.extend_from_slice(replace(index)?); + } else { + out.extend_from_slice(&template[start..position]); + } + if CONVERSIONS.contains(&spec) { + index += 1; + } + } + Ok(out) +} + +/// How `%p` prints native expression `id`, bound as `value` (before its +/// names are renamed). +pub(in crate::ast) fn pattern( + tree: &AnalysisContext<'_>, + id: ExprId, + value: &Expr, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted { + let expression = &native.expression(ungroup(id, native)).kind; + // A conditional has the type of its operands (11.4.11). + if let ExprKind::Conditional { + then_expression, + else_expression, + .. + } = expression + && let Expr::Mux { + then_expr, + else_expr, + .. + } = value + { + // A string literal is integral unless the other operand is a string + // (5.9, 6.16). + let operand = |id, value| { + Ok(match pattern(tree, id, value, native, dimensions)? { + Pattern::String + if matches!(&native.expression(ungroup(id, native)).kind, + ExprKind::Literal(text) if text.starts_with('"')) => + { + Pattern::Integral + } + pattern => pattern, + }) + }; + let then_pattern = operand(*then_expression, then_expr)?; + let else_pattern = operand(*else_expression, else_expr)?; + return Ok(match (then_pattern, else_pattern) { + (Pattern::Handle(Some(layout)), _) | (_, Pattern::Handle(Some(layout))) => { + Pattern::Handle(Some(layout)) + } + (Pattern::Handle(None), _) | (_, Pattern::Handle(None)) => Pattern::Handle(None), + (Pattern::String, _) | (_, Pattern::String) => Pattern::String, + (Pattern::Integral, Pattern::Integral) => Pattern::Integral, + }); + } + // An enum value: a variable, constant, cast, method or call of an + // enumerated type. + if matches!(expression, ExprKind::Call { expression, .. } + if direct::call_name(&tree.state, *expression, native) + .is_some_and(|name| returns_enum(&name, dimensions))) + || enums::domain(tree, id, native, dimensions)?.is_some() + { + return Err(unsupported("%p of an enum value")); + } + if strings::string_value(value, dimensions) + || strings::native_string(tree, id, native, dimensions) + || matches!(expression, ExprKind::Literal(text) if text.starts_with('"')) + { + return Ok(Pattern::String); + } + if matches!(expression, ExprKind::Literal(text) if text == "null") { + return Ok(Pattern::Handle(None)); + } + if let Some(container) = containers::native_type(id, native, tree, dimensions)? { + let element = &container.element; + if element.is_enum || element.enum_domain.is_some() || element.packed_enum { + return Err(unsupported("%p of a container of enum values")); + } + if matches!(element.kind, TypeKind::Real | TypeKind::Shortreal) { + return Err(unsupported("%p of a container of real values")); + } + if !element.members.is_empty() + || element.container.is_some() + || !element.unpacked_ranges.is_empty() + { + return Err(unsupported("%p of a container of aggregate elements")); + } + if container + .key + .as_ref() + .is_some_and(|key| key.is_enum || key.enum_domain.is_some() || key.packed_enum) + { + return Err(unsupported("%p of an associative array with enum keys")); + } + if container + .key + .as_ref() + .is_some_and(|key| key.class.is_some()) + { + return Err(unsupported( + "%p of an associative array with class handle keys", + )); + } + return Ok(Pattern::Handle(Some(container.layout))); + } + if objects::native_class(tree, id, native, dimensions).is_some() + || handle_value(value, dimensions) + || matches!(expression, ExprKind::Call { expression, .. } + if direct::call_name(&tree.state, *expression, native) + .is_some_and(|name| returns_handle(&name, dimensions))) + { + return Ok(Pattern::Handle(None)); + } + // An element selected from or popped off an unpacked array or container + // has its element type. + let base = match expression { + ExprKind::Select { expression, .. } => Some(*expression), + ExprKind::Call { expression, .. } => match &native + .expression(ungroup(*expression, native)) + .kind + { + ExprKind::Member { + expression, name, .. + } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") => Some(*expression), + _ => None, + }, + _ => None, + }; + if let Some(base) = base { + if let Some(container) = containers::native_type(base, native, tree, dimensions)? { + let element = &container.element; + if element.is_enum || element.enum_domain.is_some() || element.packed_enum { + return Err(unsupported("%p of an enum value")); + } + if element.class.is_some() { + return Ok(Pattern::Handle(None)); + } + if !element.members.is_empty() + || element.container.is_some() + || !element.unpacked_ranges.is_empty() + { + return Err(unsupported("%p of a structure or unpacked array")); + } + } else if let Some((shape, indices)) = fixed_selection(id, native, dimensions) + && !shape.unpacked.is_empty() + { + // A selection from a fixed-size unpacked array: an index of each + // unpacked dimension selects an element, which further selects + // take bits of; fewer indices, or a slice, leave an array. + match indices { + Some(indices) if indices > shape.unpacked.len() => {} + Some(indices) if indices == shape.unpacked.len() => { + if shape.enum_domain.is_some() || shape.packed_enum { + return Err(unsupported("%p of an enum value")); + } + if !shape.members.is_empty() { + return Err(unsupported("%p of a structure or unpacked array")); + } + } + _ => return Err(unsupported("%p of a structure or unpacked array")), + } + } + } + // A cast to, or a call of a function that returns, a structure or an + // unpacked array. + let aggregate = |ty: &Type| !ty.members.is_empty() || !ty.unpacked_ranges.is_empty(); + let aggregate_value = match expression { + ExprKind::Cast { target, .. } => { + enums::cast_type(tree, *target, native, dimensions)?.is_some_and(|ty| aggregate(&ty)) + } + ExprKind::Call { expression, .. } => direct::call_name(&tree.state, *expression, native) + .is_some_and(|name| returns_aggregate(&name, dimensions, aggregate)), + _ => false, + }; + if aggregate_value { + return Err(unsupported("%p of a structure or unpacked array")); + } + let checked = |is_enum: bool, aggregate: bool| { + if is_enum { + Err(unsupported("%p of an enum value")) + } else if aggregate { + Err(unsupported("%p of a structure or unpacked array")) + } else { + Ok(Pattern::Integral) + } + }; + if let ExprKind::Name(name) = expression + && let Some(shape) = dimensions.get(&instances::normalize_identifier(&name.spelling)) + { + return checked( + shape.enum_domain.is_some() || shape.packed_enum, + !shape.members.is_empty() || !shape.unpacked.is_empty(), + ); + } + if let Some((property, _)) = objects::property(tree, id, native, dimensions)? { + let ty = &property.r#type; + return checked( + ty.is_enum || ty.enum_domain.is_some() || ty.packed_enum, + !ty.members.is_empty() || !ty.unpacked_ranges.is_empty(), + ); + } + Ok(Pattern::Integral) +} + +/// Whether bound `value` is a class handle: a handle variable or property, +/// an element of a container of handles, a call of a function that returns +/// one, or a conditional with such an operand. +fn handle_value(value: &Expr, dimensions: &PackedDimensions) -> bool { + match value { + Expr::Ident(name) => dimensions + .get(name) + .is_some_and(|shape| shape.class.is_some() && shape.unpacked.is_empty()), + Expr::Mux { + then_expr, + else_expr, + .. + } => handle_value(then_expr, dimensions) || handle_value(else_expr, dimensions), + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => returns_handle(name, dimensions), + Expr::Call { + callee: Callee::Object(op), + .. + } => match &**op { + ObjectOp::Load(field) => { + field.handle == Some(crate::system_functions::HandleProperty::Object) + } + ObjectOp::Container { + op: ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack, + layout, + } => layout.handle == Some(crate::system_functions::HandleProperty::Object), + _ => false, + }, + _ => false, + } +} + +/// Whether function `name` returns an enumerated value. +fn returns_enum(name: &str, dimensions: &PackedDimensions) -> bool { + dimensions + .functions + .get(name) + .is_some_and(|function| function.return_enum_domain.is_some()) + || dimensions + .function_return_types + .get(name) + .is_some_and(|metadata| metadata.enum_domain.is_some()) +} + +/// The shape of the variable that native selection `id` selects from, and +/// the number of indices that precede the first slice, all of them when +/// there is no slice, or `None` when an unpacked dimension is sliced. +fn fixed_selection<'a>( + id: ExprId, + native: &Declarations, + dimensions: &'a PackedDimensions, +) -> Option<(&'a VariableDimensions, Option)> { + let mut selects = Vec::new(); + let mut current = ungroup(id, native); + let name = loop { + match &native.expression(current).kind { + ExprKind::Select { + expression, + dimension, + } => { + selects.push(matches!(dimension.kind, DimensionKind::Index(_))); + current = ungroup(*expression, native); + } + ExprKind::Name(name) => break name, + _ => return None, + } + }; + let shape = dimensions.get(&instances::normalize_identifier(&name.spelling))?; + // Outermost select last: the first ones apply to the unpacked dimensions. + selects.reverse(); + let indices = selects.iter().take_while(|index| **index).count(); + let sliced = indices < selects.len() && indices < shape.unpacked.len(); + Some((shape, (!sliced).then_some(selects.len()))) +} + +/// Whether function `name` returns a value of a type that `aggregate` holds +/// for. +fn returns_aggregate( + name: &str, + dimensions: &PackedDimensions, + aggregate: impl Fn(&Type) -> bool, +) -> bool { + dimensions + .functions + .get(name) + .and_then(|function| function.return_type.as_ref()) + .or_else(|| { + dimensions + .function_return_types + .get(name) + .and_then(|metadata| metadata.pattern_type.as_ref()) + }) + .is_some_and(aggregate) +} + +/// Whether function `name` returns a class handle. +fn returns_handle(name: &str, dimensions: &PackedDimensions) -> bool { + dimensions + .functions + .get(name) + .is_some_and(|function| function.return_handle) +} + +/// The conversion that prints `value` as `%p` does, and the argument it +/// converts. +pub(in crate::ast) fn pattern_argument( + pattern: Pattern, + value: Expr, + dimensions: &PackedDimensions, +) -> (&'static [u8], Expr) { + let quote = || Expr::Literal("8'h22".into()); + match pattern { + // A real prints as an unformatted `$display` prints it. + Pattern::Integral if real_value(&value, dimensions) => (b"%#g", value), + Pattern::Integral => (b"%0d", value), + Pattern::String => ( + b"%s", + strings::call( + StringOp::Concat, + strings::operands(StringOp::Concat, vec![quote(), value, quote()], dimensions), + ), + ), + Pattern::Handle(layout) => (b"%s", strings::call(StringOp::Pattern(layout), vec![value])), + } +} + +/// A literal format and the values it converts, with each `%p` rewritten. +/// `ids` are the native values, `values` the bound ones. +pub(in crate::ast) fn rewrite_format( + template: &[u8], + ids: &[ExprId], + values: &mut [Expr], + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + rewrite_template(template, |index| { + let (Some(&id), Some(value)) = (ids.get(index), values.get_mut(index)) else { + // A conversion without an argument prints nothing. + return Ok(&b"%0d"[..]); + }; + let pattern = pattern(tree, id, value, native, dimensions)?; + let (conversion, argument) = pattern_argument( + pattern, + std::mem::replace(value, Expr::Literal("0".into())), + dimensions, + ); + *value = argument; + Ok(conversion) + }) +} + +/// The packed literal of `bytes`, most significant first, as a string +/// literal is (5.9). +pub(in crate::ast) fn bytes_literal(bytes: &[u8]) -> Expr { + Expr::Literal(format!( + "{}'h{}", + (bytes.len() * 8).max(8), + num_bigint::BigUint::from_bytes_be(bytes).to_str_radix(16) + )) +} + +/// `$sformatf` of the bound `operands`, a format and its values, whose native +/// expressions are `ids` (21.3.3). A literal format has its `%p` conversions +/// rewritten. +pub(in crate::ast) fn format( + ticks_per_unit: u64, + ids: &[ExprId], + mut operands: Vec, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted { + if let Some((&format, values)) = ids.split_first() + && let ExprKind::Literal(text) = &native.expression(ungroup(format, native)).kind + && let Some(bytes) = string_literal_bytes(text) + && has_pattern(&bytes) + && let Some((first, rest)) = operands.split_first_mut() + { + let template = rewrite_format(&bytes, values, rest, tree, native, dimensions)?; + *first = bytes_literal(&template); + } + Ok(strings::call(StringOp::Format { ticks_per_unit }, operands)) +} 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 f740f2c6adc..88e34a4d8af 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -114,7 +114,9 @@ pub(in crate::ast) fn operands( ) -> Vec { let strings = match op { // A format keeps its type: the frontend reads a literal one as text. - StringOp::FromBits | StringOp::Itoa(_) | StringOp::Format { .. } => 0, + StringOp::FromBits | StringOp::Itoa(_) | StringOp::Format { .. } | StringOp::Pattern(_) => { + 0 + } StringOp::Concat => usize::MAX, StringOp::Compare | StringOp::ICompare => 2, _ => 1, diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index a6d1e25580f..3474be154fe 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -238,6 +238,7 @@ fn native_signature( .as_ref() .is_some_and(|ty| matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal)), return_string: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::String), + return_handle: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::Object), name: instances::normalize_identifier(&native.name.spelling), params, body: None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 8d360c66a55..27af3c45ca3 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -858,6 +858,59 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { ids.extend(kept_ids); } + /// Rewrite each `%p` of the format of a display or write task into a + /// conversion of the value it prints (IEEE 1800-2023 21.2.1.6). + fn rewrite_display_patterns( + &self, + task: SystemTask, + args: &mut [SystemTaskArg], + ids: &[Option], + ) -> Result<(), AnalyzerError> { + let Some(template) = template_index(task, args) else { + return Ok(()); + }; + let Some(SystemTaskArg::Str(text)) = args.get(template) else { + return Ok(()); + }; + if !expression_binding::has_pattern(text.as_bytes()) { + return Ok(()); + } + let text = text.clone(); + let native = self.tree.declarations(); + let rewritten = expression_binding::rewrite_template(text.as_bytes(), |index| { + let position = template + 1 + index; + Ok(match args.get_mut(position) { + Some(SystemTaskArg::Expr(value)) => { + let id = ids + .get(position) + .copied() + .flatten() + .ok_or_else(|| unsupported("omitted %p argument"))?; + let pattern = expression_binding::format_pattern( + self.tree, id, value, native, &self.dims, + )?; + let (conversion, argument) = expression_binding::format_pattern_argument( + pattern, + std::mem::replace(value, Expr::Literal("0".into())), + &self.dims, + ); + *value = argument; + conversion + } + // A string literal prints in quotes. + Some(SystemTaskArg::Str(literal)) => { + *literal = format!("\\\"{literal}\\\""); + b"%s" + } + Some(SystemTaskArg::Empty) | None => b"%0d", + }) + })?; + args[template] = SystemTaskArg::Str( + String::from_utf8(rewritten).map_err(|_| unsupported("non-UTF-8 format"))?, + ); + Ok(()) + } + /// `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). @@ -1767,8 +1820,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { detail: "expected an output argument".into(), } })?; + let ids = expression_binding::format_arguments(name, &arguments[1..])?; let mut values = Vec::new(); - for id in expression_binding::format_arguments(name, &arguments[1..])? { + for &id in &ids { values.push(expression_binding::bind_value( id, declarations, @@ -1777,12 +1831,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { None, )?); } - let value = expression_binding::string_call( - StringOp::Format { - ticks_per_unit: timescales::time_divisor(root, self.tree)?, - }, + let value = expression_binding::format_call( + timescales::time_divisor(root, self.tree)?, + &ids, values, - ); + self.tree, + declarations, + &self.dims, + )?; return Ok(vec![self.format_assignment(output, value)?]); } // `$swrite(output, args...)` assigns what `$write(args...)` would @@ -1801,6 +1857,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { // continues the format, and a value without a conversion of its // own is written in the radix of the task (21.2.1.1). let mut text = Vec::new(); + let mut ids = Vec::new(); let mut values = Vec::new(); let mut pending = 0; for (position, arg) in arguments.iter().enumerate().skip(1) { @@ -1838,13 +1895,20 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .as_bytes(), ); } + ids.push(id); values.push(value); } - let format = Expr::Literal(format!( - "{}'h{}", - (text.len() * 8).max(8), - num_bigint::BigUint::from_bytes_be(&text).to_str_radix(16) - )); + if expression_binding::has_pattern(&text) { + text = expression_binding::rewrite_format( + &text, + &ids, + &mut values, + self.tree, + declarations, + &self.dims, + )?; + } + let format = expression_binding::bytes_literal(&text); let value = expression_binding::string_call( StringOp::Format { ticks_per_unit: timescales::time_divisor(root, self.tree)?, @@ -1937,6 +2001,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { // The native expression of each argument, kept in step with `args`. let mut ids = arguments.iter().map(|arg| arg.value).collect::>(); self.merge_display_formats(task, &mut args, &mut ids); + self.rewrite_display_patterns(task, &mut args, &ids)?; for arg in &mut args { if let SystemTaskArg::Expr(value) = arg { self.rename_expr(value); @@ -4122,7 +4187,7 @@ fn format_conversions(text: &str) -> Vec { while chars.next_if(char::is_ascii_digit).is_some() {} } if let Some(spec) = chars.next() - && "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) + && "bBoOhHxXdDiIcCsStTeEfFgGpP".contains(spec) { conversions.push(spec); } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 41acaf58a43..5e5afe1525f 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -740,6 +740,9 @@ pub enum StringOp { /// the calling scope, of which `ticks_per_unit` simulation time units /// make one. Format { ticks_per_unit: u64 }, + /// The text `%p` prints for a class handle, or with a layout for a + /// container (21.2.1.6). + Pattern(Option), } impl StringOp { @@ -756,6 +759,7 @@ impl StringOp { | Self::ToLower | Self::Itoa(_) | Self::Format { .. } + | Self::Pattern(_) ) } @@ -823,6 +827,7 @@ impl fmt::Display for StringOp { Self::Itoa(Radix::Octal) => "octtoa", Self::Itoa(Radix::Binary) => "bintoa", Self::Format { .. } => "$sformatf", + Self::Pattern(_) => "%p", }; f.write_str(name) } diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 4571b041648..892b6d28c7d 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -630,13 +630,18 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_unpacked_structs` | compile | icarus | 21 | Icarus 13.0 does not support unpacked structures ("sorry: Unpacked structs not supported."), which IEEE 1800-2023 7.2 defines; the standalone source reproduces the diagnostic. Verilator passes all but the nested default pattern, see sv_verilator_nested_struct_default. | | `sv_icarus_nested_containers` | compile | icarus | 4 | Icarus 13.0 rejects an associative array whose index type is a type name ("Type names are not valid expressions here."), as for the class-handle and string indices of these nested containers, does not support a dynamic array of dynamic arrays ("Sorry: Dynamic array of type `dynamic array of ...` is not yet supported."), and does not support unpacked structures (see sv_icarus_unpacked_structs). IEEE 1800-2023 7.4.5, 7.8 and 7.8.5 define these. Verilator passes these cases. | | `sv_verilator_nested_struct_default` | execute | verilator | 1 | Verilator 5.052 applies '{default: 5, ...} to the int member of a nested unpacked structure but leaves its bit [3:0] member 0 ("5 0000 1" in the standalone source; a top-level '{default: 5} sets both). IEEE 1800-2023 10.9.2 applies the default recursively to each member of an unmatched substructure and evaluates it in the context of an assignment to a simple bit vector member, giving 4'b0101. | +| `sv_verilator_pattern_format` | execute | verilator | 2 | Verilator 5.052 prints `%p` of integral container elements and integral associative keys in hexadecimal (`'h1`, and `'hfffffffe` for the `int` key -2) and a string literal as its packed value. IEEE 1800-2023 21.2.1.6 prints singular values as unformatted `$display` prints them, in decimal, and a string literal in quotes; xezim 0.11.3 prints the queue and dynamic array case as expected. | +| `sv_icarus_pattern_format` | execute | icarus | 1 | Icarus 13.0 compiles `%p` of queues and dynamic arrays, then `vvp` stops: "$display does not support argument type (116)." IEEE 1800-2023 21.2.1.6 prints them as assignment patterns. | +| `sv_icarus_associative_arrays_and_class_queues` | compile | icarus | 1 | Icarus 13.0 rejects associative arrays with `int` and `string` indices ("Type names are not valid expressions here") and queues of class handles, which IEEE 1800-2023 7.8 and 7.10 define. | The `string_format` cases compare `$sformatf`, `$sformat` and `$swrite` with `$display` / `$write` 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. +design in its own testbench hierarchy. The `pattern_format` cases print `%p` +of containers, strings and class handles; the [observations](verification/sv/limitations/pattern-format.json) +retain the standalone Verilator, Icarus and xezim outputs. 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/string_format.vtest b/crates/celox-test-suite/src/sv/cases/string_format.vtest index 0d9ed8ee4f3..fb64c530c4d 100644 --- a/crates/celox-test-suite/src/sv/cases/string_format.vtest +++ b/crates/celox-test-suite/src/sv/cases/string_format.vtest @@ -401,3 +401,90 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "hello!\n[ 65000]\n[ 65000]\n")) + +; 21.2.1.6: `%p` prints an integral value as unformatted, a string in quotes +; and a queue or dynamic array as an assignment pattern. `$sformatf` and +; `$sformat` return the same text. +(case pattern_format + (source "pattern_format.sv" #" +module Top(output bit done); + int q[$]; + byte signed d[]; + string names[$]; + int i; + string s, t; + initial begin + q = {1, 2, 3}; + d = new[2]; + d[0] = -1; + d[1] = 5; + names = {"p", "q"}; + i = -7; + t = "str"; + $display("%p|%p|%p|%p|%p|%0p", q, d, names, i, t, q); + $display("q=", "%p", q, " t=%p", t); + begin + string local_text; + local_text = "loc"; + $display("%p", local_text); + end + s = $sformatf("%p|%p|%p|%p|%p|%0p", q, d, names, i, t, q); + $display("%s", s); + q.delete(); + $sformat(s, "[%p]", q); + $display("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "'{1, 2, 3}|'{-1, 5}|'{\"p\", \"q\"}|-7|\"str\"|'{1, 2, 3}\nq='{1, 2, 3} t=\"str\"\n\"loc\"\n'{1, 2, 3}|'{-1, 5}|'{\"p\", \"q\"}|-7|\"str\"|'{1, 2, 3}\n['{}]\n")) + +; 21.2.1.6: an associative array prints its index labels in index order, a +; class handle prints null when it is null, also from a conditional or a +; function, a conditional of containers prints the selected one, and a string +; literal, conditional or function result prints in quotes. +(case pattern_format_keys_and_handles + (source "pattern_keys_handles.sv" #" +class Item; + int id; +endclass + +module Top(output bit done); + function automatic string name(int n); + return $sformatf("n%0d", n); + endfunction + function automatic Item pick(); + return null; + endfunction + int a[string]; + bit [7:0] m[int]; + Item item, items[$]; + string s, t; + int i; + int q[$], r[$]; + initial begin + q = {1, 2}; + r = {9}; + a["x"] = 10; + a["a"] = 20; + m[-2] = 8'h41; + m[7] = 8'h0; + items.push_back(null); + items.push_back(item); + $display("%p|%p|%p|%p|%p", a, m, items, item, "lit"); + s = $sformatf("%p|%p|%p|%p|%p", a, m, items, item, "lit"); + $display("%s", s); + t = "str"; + i = 1; + $display("%p %p", i < 0 ? s : t, name(2)); + $display("%p %p %p", items[1], items.pop_front(), items.pop_back()); + $display("%p %p", i > 0 ? item : null, pick()); + $display("%p %p", i > 0 ? q : r, i < 0 ? q : r); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "'{\"a\":20, \"x\":10}|'{-2:65, 7:0}|'{null, null}|null|\"lit\"\n'{\"a\":20, \"x\":10}|'{-2:65, 7:0}|'{null, null}|null|\"lit\"\n\"str\" \"n2\"\nnull null null\nnull null\n'{1, 2} '{9}\n")) + diff --git a/crates/celox-test-suite/verification/sv/icarus/string_format.json b/crates/celox-test-suite/verification/sv/icarus/string_format.json index ab9e5eb08ff..a793b219fcc 100644 --- a/crates/celox-test-suite/verification/sv/icarus/string_format.json +++ b/crates/celox-test-suite/verification/sv/icarus/string_format.json @@ -1,5 +1,51 @@ { "cases": [ + { + "category": "Types", + "detail": "Icarus 13.0 compiles %p of queues and dynamic arrays, but vvp stops with \"$display does not support argument type (116).\" IEEE 1800-2023 21.2.1.6 prints them as assignment patterns.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/sv/limitations/pattern-format.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_pattern_format", + "observed_version": "Icarus Verilog 13.0", + "phase": "execute", + "reason": "Icarus 13.0 compiles %p of queues and dynamic arrays, but vvp stops with \"$display does not support argument type (116).\" IEEE 1800-2023 21.2.1.6 prints them as assignment patterns.", + "upstream": [] + }, + "name": "string_format::pattern_format", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects associative arrays declared with int and string indices (\"Type names are not valid expressions here\") and queues of class handles (\"Queue of type class ... is not yet supported\", \"Class/null r-value not allowed in this context\"), which IEEE 1800-2023 7.8 and 7.10 define.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/pattern-format.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_associative_arrays_and_class_queues", + "observed_version": "Icarus Verilog 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects associative arrays declared with int and string indices (\"Type names are not valid expressions here\") and queues of class handles (\"Queue of type class ... is not yet supported\", \"Class/null r-value not allowed in this context\"), which IEEE 1800-2023 7.8 and 7.10 define.", + "upstream": [] + }, + "name": "string_format::pattern_format_keys_and_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "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.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 678cda31ec5..bdf424eb222 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -3043,5 +3043,57 @@ "containers::nested_updates_evaluate_indices_once" ] } + }, + { + "id": "sv_verilator_pattern_format", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 prints %p of integral container elements and integral associative keys in hexadecimal ('h1, and 'hfffffffe for the int key -2) and a string literal as its packed integer value (7104884 for \"lit\"). IEEE 1800-2023 21.2.1.6 prints singular values as they would print unformatted, which $display prints in decimal, and a string literal enclosed in quotes; xezim 0.11.3 prints the queue and dynamic array elements in decimal.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/pattern-format.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "string_format::pattern_format", + "string_format::pattern_format_keys_and_handles" + ] + } + }, + { + "id": "sv_icarus_pattern_format", + "category": "simulator_unsupported", + "phase": "execute", + "observed_version": "Icarus Verilog 13.0", + "reason": "Icarus 13.0 compiles %p of queues and dynamic arrays, but vvp stops with \"$display does not support argument type (116).\" IEEE 1800-2023 21.2.1.6 prints them as assignment patterns.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/pattern-format.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "string_format::pattern_format" + ] + } + }, + { + "id": "sv_icarus_associative_arrays_and_class_queues", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog 13.0", + "reason": "Icarus 13.0 rejects associative arrays declared with int and string indices (\"Type names are not valid expressions here\") and queues of class handles (\"Queue of type class ... is not yet supported\", \"Class/null r-value not allowed in this context\"), which IEEE 1800-2023 7.8 and 7.10 define.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/pattern-format.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "string_format::pattern_format_keys_and_handles" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/pattern-format.json b/crates/celox-test-suite/verification/sv/limitations/pattern-format.json new file mode 100644 index 00000000000..50d56e82d92 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/pattern-format.json @@ -0,0 +1,57 @@ +{ + "source": "src/sv/cases/string_format.vtest", + "method": "The shared cases pattern_format and pattern_format_keys_and_handles run in verify-sv-verilator, verify-sv-icarus and verify-sv-xezim. The reduced sources run standalone with verilator --binary, iverilog -g2012 -s Top / vvp -n, and xezim -s Top.", + "observations": [ + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "source": "module Top;\n int q[$];\n byte signed d[];\n string names[$];\n int i;\n string s, t;\n initial begin\n q = {1, 2, 3};\n d = new[2];\n d[0] = -1;\n d[1] = 5;\n names = {\"p\", \"q\"};\n i = -7;\n t = \"str\";\n $display(\"%p|%p|%p|%p|%p|%0p\", q, d, names, i, t, q);\n s = $sformatf(\"%p|%p|%p|%p|%p|%0p\", q, d, names, i, t, q);\n $display(\"%s\", s);\n q.delete();\n $display(\"[%p]\", q);\n end\nendmodule\n", + "stdout": "'{'h1, 'h2, 'h3}|'{'hff, 'h5}|'{\"p\", \"q\"}|-7|\"str\"|'{'h1, 'h2, 'h3}\n'{'h1, 'h2, 'h3}|'{'hff, 'h5}|'{\"p\", \"q\"}|-7|\"str\"|'{'h1, 'h2, 'h3}\n['{}]\n" + }, + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "source": "module Top;\n int a[string];\n bit [7:0] m[int];\n initial begin\n a[\"x\"] = 10;\n a[\"a\"] = 20;\n m[-2] = 8'h41;\n m[7] = 8'h0;\n $display(\"%p|%p\", a, m);\n end\nendmodule\n", + "stdout": "'{\"a\":'h14, \"x\":'ha}|'{'h7:'h0, 'hfffffffe:'h41}\n" + }, + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "source": "class Item; int id; endclass\nmodule Top;\n Item item, items[$];\n initial begin\n items.push_back(null);\n items.push_back(null);\n $display(\"%p|%p|%p\", items, item, \"lit\");\n end\nendmodule\n", + "stdout": "'{null, null}|null|7104884\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog 13.0", + "source": "module Top;\n int q[$];\n byte signed d[];\n string names[$];\n int i;\n string s, t;\n initial begin\n q = {1, 2, 3};\n d = new[2];\n d[0] = -1;\n d[1] = 5;\n names = {\"p\", \"q\"};\n i = -7;\n t = \"str\";\n $display(\"%p|%p|%p|%p|%p|%0p\", q, d, names, i, t, q);\n s = $sformatf(\"%p|%p|%p|%p|%p|%0p\", q, d, names, i, t, q);\n $display(\"%s\", s);\n q.delete();\n $display(\"[%p]\", q);\n end\nendmodule\n", + "status": "runtime_error", + "stderr": "ERROR: p1.sv:15: $display does not support argument type (116).\nERROR: p1.sv:16: $sformatf does not support argument type (116).\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog 13.0", + "source": "module Top;\n int a[string];\n bit [7:0] m[int];\n initial begin\n a[\"x\"] = 10;\n a[\"a\"] = 20;\n m[-2] = 8'h41;\n m[7] = 8'h0;\n $display(\"%p|%p\", a, m);\n end\nendmodule\n", + "status": "compile_error", + "stderr": "p2.sv:2: error: Type names are not valid expressions here.\np2.sv:2: internal error: I do not know how to elaborate this expression.\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog 13.0", + "source": "class Item; int id; endclass\nmodule Top;\n Item item, items[$];\n initial begin\n items.push_back(null);\n items.push_back(null);\n $display(\"%p|%p|%p\", items, item, \"lit\");\n end\nendmodule\n", + "status": "compile_error", + "stderr": "p3.sv:5: Error: Class/null r-value not allowed in this context.\np3.sv:6: Error: Class/null r-value not allowed in this context.\n" + }, + { + "tool": "xezim", + "version": "xezim 0.11.3", + "source": "module Top;\n int q[$];\n byte signed d[];\n string names[$];\n int i;\n string s, t;\n initial begin\n q = {1, 2, 3};\n d = new[2];\n d[0] = -1;\n d[1] = 5;\n names = {\"p\", \"q\"};\n i = -7;\n t = \"str\";\n $display(\"%p|%p|%p|%p|%p|%0p\", q, d, names, i, t, q);\n s = $sformatf(\"%p|%p|%p|%p|%p|%0p\", q, d, names, i, t, q);\n $display(\"%s\", s);\n q.delete();\n $display(\"[%p]\", q);\n end\nendmodule\n", + "stdout": "'{1, 2, 3}|'{-1, 5}|'{\"p\", \"q\"}|-7|\"str\"|'{1, 2, 3}\n'{1, 2, 3}|'{-1, 5}|'{\"p\", \"q\"}|-7|\"str\"|'{1, 2, 3}\n['{}]\n" + }, + { + "tool": "xezim", + "version": "xezim 0.11.3", + "source": "class Item; int id; endclass\nmodule Top;\n Item item, items[$];\n initial begin\n items.push_back(null);\n items.push_back(null);\n $display(\"%p|%p|%p\", items, item, \"lit\");\n end\nendmodule\n", + "stdout": "'{0, 0}|null|7104884\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/verilator/string_format.json b/crates/celox-test-suite/verification/sv/verilator/string_format.json index 0ccd46d0f86..5168fb4b084 100644 --- a/crates/celox-test-suite/verification/sv/verilator/string_format.json +++ b/crates/celox-test-suite/verification/sv/verilator/string_format.json @@ -1,5 +1,51 @@ { "cases": [ + { + "category": "Types", + "detail": "Verilator 5.052 prints %p of integral container elements and integral associative keys in hexadecimal ('h1, and 'hfffffffe for the int key -2) and a string literal as its packed integer value (7104884 for \"lit\"). IEEE 1800-2023 21.2.1.6 prints singular values as they would print unformatted, which $display prints in decimal, and a string literal enclosed in quotes; xezim 0.11.3 prints the queue and dynamic array elements in decimal.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/pattern-format.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_pattern_format", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 prints %p of integral container elements and integral associative keys in hexadecimal ('h1, and 'hfffffffe for the int key -2) and a string literal as its packed integer value (7104884 for \"lit\"). IEEE 1800-2023 21.2.1.6 prints singular values as they would print unformatted, which $display prints in decimal, and a string literal enclosed in quotes; xezim 0.11.3 prints the queue and dynamic array elements in decimal.", + "upstream": [] + }, + "name": "string_format::pattern_format", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Verilator 5.052 prints %p of integral container elements and integral associative keys in hexadecimal ('h1, and 'hfffffffe for the int key -2) and a string literal as its packed integer value (7104884 for \"lit\"). IEEE 1800-2023 21.2.1.6 prints singular values as they would print unformatted, which $display prints in decimal, and a string literal enclosed in quotes; xezim 0.11.3 prints the queue and dynamic array elements in decimal.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/pattern-format.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_pattern_format", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 prints %p of integral container elements and integral associative keys in hexadecimal ('h1, and 'hfffffffe for the int key -2) and a string literal as its packed integer value (7104884 for \"lit\"). IEEE 1800-2023 21.2.1.6 prints singular values as they would print unformatted, which $display prints in decimal, and a string literal enclosed in quotes; xezim 0.11.3 prints the queue and dynamic array elements in decimal.", + "upstream": [] + }, + "name": "string_format::pattern_format_keys_and_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "four-state expectations", diff --git a/crates/celox-test-suite/verification/sv/xezim/string_format.json b/crates/celox-test-suite/verification/sv/xezim/string_format.json index 2a30cfb32a7..ec8b4edcc82 100644 --- a/crates/celox-test-suite/verification/sv/xezim/string_format.json +++ b/crates/celox-test-suite/verification/sv/xezim/string_format.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "string_format::pattern_format_keys_and_handles at 489:3: expect_output: expected [39, 123, 34, 97, 34, 58, 50, 48, 44, 32, 34, 120, 34, 58, 49, 48, 125, 124, 39, 123, 45, 50, 58, 54, 53, 44, 32, 55, 58, 48, 125, 124, 39, 123, 110, 117, 108, 108, 44, 32, 110, 117, 108, 108, 125, 124, 110, 117, 108, 108, 124, 34, 108, 105, 116, 34, 10, 39, 123, 34, 97, 34, 58, 50, 48, 44, 32, 34, 120, 34, 58, 49, 48, 125, 124, 39, 123, 45, 50, 58, 54, 53, 44, 32, 55, 58, 48, 125, 124, 39, 123, 110, 117, 108, 108, 44, 32, 110, 117, 108, 108, 125, 124, 110, 117, 108, 108, 124, 34, 108, 105, 116, 34, 10, 34, 115, 116, 114, 34, 32, 34, 110, 50, 34, 10, 110, 117, 108, 108, 32, 110, 117, 108, 108, 32, 110, 117, 108, 108, 10, 110, 117, 108, 108, 32, 110, 117, 108, 108, 10, 39, 123, 49, 44, 32, 50, 125, 32, 39, 123, 57, 125, 10], got [39, 123, 34, 97, 34, 58, 50, 48, 44, 32, 34, 120, 34, 58, 49, 48, 125, 124, 39, 123, 45, 50, 58, 39, 104, 52, 49, 44, 32, 55, 58, 39, 104, 48, 125, 124, 39, 123, 48, 44, 32, 48, 125, 124, 110, 117, 108, 108, 124, 55, 49, 48, 52, 56, 56, 52, 10, 39, 123, 34, 97, 34, 58, 50, 48, 44, 32, 34, 120, 34, 58, 49, 48, 125, 124, 39, 123, 45, 50, 58, 39, 104, 52, 49, 44, 32, 55, 58, 39, 104, 48, 125, 124, 39, 123, 48, 44, 32, 48, 125, 124, 110, 117, 108, 108, 124, 55, 49, 48, 52, 56, 56, 52, 10, 55, 53, 54, 54, 52, 53, 48, 32, 34, 110, 50, 34, 10, 48, 32, 48, 32, 48, 10, 48, 32, 48, 10, 120, 32, 120, 10]", + "expectation": "Simulation", + "name": "string_format::pattern_format_keys_and_handles", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "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]", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index 6e78d1ff9d7..9ed27906184 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -806,6 +806,10 @@ "sv_rest-X90": { "title": "An update of an element of a nested container evaluates the outer index expression again, and $unpacked_dimensions/$dimensions of a dynamic array of dynamic arrays count one level", "standard": "IEEE 1800-2023 7.4.5, 11.4.1, 20.7" + }, + "sv_pattern_handles_and_literals": { + "title": "%p prints null class handles in a queue as 0 and a string literal as a number", + "standard": "IEEE 1800-2023 21.2.1.6" } }, "cases": [ @@ -4703,6 +4707,14 @@ "classification": "xezim_bug", "bug": "sv_rest-X84", "note": "h.p.m_type_name, the string member of a class property written through a ref formal, prints as a space-padded wide value and h.p.m_type.text prints empty; xezim does the same for a direct write of the property (h.p = '{...}). Reproduced by verification/repros/sv_xezim_unpacked_struct_properties.sv." + }, + { + "suite": "sv", + "name": "string_format::pattern_format_keys_and_handles", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_pattern_handles_and_literals", + "note": "xezim 0.11.3 prints '{0, 0} for a queue of two null class handles 7104884 for the string literal \"lit\", and the packed bytes of a string-valued conditional (7566450 for \"str\"); 21.2.1.6 prints a null handle as null and a string literal in quotes. It also prints the bit [7:0] elements of an associative array as 'h41 and 'h0, where unformatted $display prints decimal. See verification/sv/limitations/pattern-format.json." } ] } diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index f386554d3b5..6f70a2ca99a 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -840,6 +840,37 @@ mod host { out.extend_from_slice(&runtime_event_format_arg(arg, 'd', site.sizing, field)); arg_idx += 1; } + // The analyzer rewrites each `%p` of a literal format; one of a + // format read at run time prints a string in quotes and any + // other value as `%0d` does (IEEE 1800-2023 21.2.1.6). + 'p' | 'P' if site.sizing == DisplaySizing::Ieee => { + let Some(arg) = args.get(arg_idx) else { + arg_idx += 1; + continue; + }; + if arg.is_string { + out.push(b'"'); + out.extend_from_slice(&runtime_event_format_arg( + arg, + 's', + site.sizing, + FieldSpec::default(), + )); + out.push(b'"'); + } else { + let field = FieldSpec { + width: Some(0), + ..FieldSpec::default() + }; + out.extend_from_slice(&runtime_event_format_arg( + arg, + 'd', + site.sizing, + field, + )); + } + arg_idx += 1; + } 't' | 'T' | 'm' | 'M' => { let text = if matches!(spec, 't' | 'T') { ctx.tb_time.unwrap_or(0).to_string() diff --git a/crates/celox/src/simulator/host/format.rs b/crates/celox/src/simulator/host/format.rs index 52d4a773784..641ecdfb6da 100644 --- a/crates/celox/src/simulator/host/format.rs +++ b/crates/celox/src/simulator/host/format.rs @@ -172,7 +172,7 @@ fn scale_time_arguments(template: &str, args: &mut [RuntimeEventArgValue], ticks let Some(spec) = chars.next() else { break; }; - if !"bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) { + if !"bBoOhHxXdDiIcCsStTeEfFgGpP".contains(spec) { continue; } if matches!(spec, 't' | 'T') diff --git a/crates/celox/tests/frontends/systemverilog/string_format.rs b/crates/celox/tests/frontends/systemverilog/string_format.rs index 9f4d1b542a5..b211488dfae 100644 --- a/crates/celox/tests/frontends/systemverilog/string_format.rs +++ b/crates/celox/tests/frontends/systemverilog/string_format.rs @@ -17,6 +17,35 @@ sv_backends! { fn sformatf_with_reference_argument(sim) { @case "string_format::sformatf_with_reference_argument"; } fn swrite_matches_write(sim) { @case "string_format::swrite_matches_write"; } fn display_later_formats(sim) { @case "string_format::display_later_formats"; } + fn pattern_format(sim) { @case "string_format::pattern_format"; } + fn pattern_format_keys_and_handles(sim) { @case "string_format::pattern_format_keys_and_handles"; } + // A string literal operand leaves a conditional integral (5.9): `%p` + // prints it unformatted, not in quotes. + fn pattern_format_conditional_string_literal(sim) { + @setup { + let source = r#" + module Top; + bit f; + string s; + initial begin + f = 1; + $display("%p", f ? "A" : 8'h42); + s = $sformatf("%p", f ? "A" : 8'h42); + $display("%s", s); + f = 0; + $display("%p", f ? "A" : 8'h42); + end + endmodule + "#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("pattern_literal.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![ + celox::RuntimeEvent::Display { message: b"65".to_vec() }, + celox::RuntimeEvent::Display { message: b"65".to_vec() }, + celox::RuntimeEvent::Display { message: b"66".to_vec() }, + ]); + } // 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) { @@ -123,3 +152,73 @@ fn later_formats_keep_default_conversions_of_locals() { String::from_utf8_lossy(&messages[0]) ); } + +/// `%p` of a type whose pattern Celox does not print yet is rejected, not +/// printed as a plain integral value (IEEE 1800-2023 21.2.1.6). +#[test] +fn pattern_format_rejects_unsupported_types() { + for (declarations, expected) in [ + ("typedef enum {A, B} e_t; e_t v;", "%p of an enum value"), + ( + "typedef struct packed { bit [3:0] a; } s_t; s_t v;", + "%p of a structure or unpacked array", + ), + ( + "typedef enum {A, B} e_t; e_t v[$];", + "%p of a container of enum values", + ), + ( + "class C; endclass int v[C];", + "%p of an associative array with class handle keys", + ), + ] { + check_rejected(declarations, "v", expected); + } + for (declarations, value) in [ + ("typedef struct packed { bit [3:0] a; } s_t;", "s_t'(4'h3)"), + ( + "typedef struct packed { bit [3:0] a; } s_t; s_t q[2];", + "q[0]", + ), + ("int m[2][3];", "m[1]"), + ("int a[4];", "a[1:2]"), + ( + "typedef struct packed { bit [3:0] a; } s_t; \ + function automatic s_t make(); return s_t'(4'h3); endfunction", + "make()", + ), + ] { + check_rejected(declarations, value, "%p of a structure or unpacked array"); + } + for (declarations, value) in [ + ("typedef enum {A, B} e_t; e_t q[$];", "q[0]"), + ("typedef enum {A, B} e_t; e_t q[$];", "q.pop_front()"), + ("typedef enum {A, B} e_t; e_t a[2];", "a[1]"), + ("typedef enum {A, B} e_t; e_t a, b; bit f;", "f ? a : b"), + ("typedef enum {A, B} e_t;", "A"), + ("typedef enum {A, B} e_t;", "e_t'(1)"), + ("typedef enum {A, B} e_t; e_t v;", "v.next()"), + ( + "typedef enum {A, B} e_t; function automatic e_t pick(); return B; endfunction", + "pick()", + ), + ] { + check_rejected(declarations, value, "%p of an enum value"); + } +} + +/// Building `%p` of `value` fails with `expected`. +fn check_rejected(declarations: &str, value: &str, expected: &str) { + let source = format!( + "module Top; {declarations} string s; \ + initial begin $display(\"%p\", {value}); s = $sformatf(\"%p\", {value}); end endmodule" + ); + let Err(error) = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("pattern.sv"))], "Top") + .build_cranelift() + else { + panic!("{declarations}: %p of {value} is unsupported"); + }; + let error = error.to_string(); + assert!(error.contains(expected), "{declarations} {value}: {error}"); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6548eb8681b..cc6adf4ef84 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -1185,7 +1185,16 @@ is available, with the same field widths, X/Z digits and `%t` scaling. 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` and `$swrite` must be a `string` variable or -class property; integral outputs and `%p` are unsupported. +class property; integral outputs are unsupported. + +`%p` of a literal format, in these functions and in `$display`, `$write`, +the file output and the severity tasks, prints an integral value as `%0d` +does, a real as an unformatted real, a string or string literal in quotes, a +class handle as `null` or `@` and its handle, and a queue, dynamic array or +associative array of such elements as an assignment pattern, `'{1, 2}` or +`'{"key":1}` (IEEE 1800-2023 21.2.1.6). `%p` of enums, structures, unpacked +arrays and containers of them is rejected. A `%p` of a format read at run time +prints a string in quotes and any other value as `%0d`. 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