Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions crates/celox-sv-analyzer/src/ast/expression_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ mod strings;
pub(super) use calls::{statement as call_statement, statement_root as call_statement_root};
pub(super) use direct::{
arguments, bind_value, call_name as native_name, callable_name, cast_target_native,
format_arguments, member_context, real_value, remove_real_division_guards, ungroup,
format_arguments, member_context, real_value, remove_real_division_guards,
string_literal_bytes, ungroup,
};
pub(super) use lvalues::{net_lvalue, variable_lvalue};
pub(super) use objects::{
Expand All @@ -25,7 +26,8 @@ pub(super) use objects::{
receiver as object_receiver, static_property as object_static_property, this as object_this,
};
pub(super) use strings::{
call as string_call, method as string_method, native_string, to_string as string_operand,
call as string_call, method as string_method, native_string, string_value,
to_string as string_operand,
};
fn disagreement() -> AnalyzerError {
AnalyzerError::Parse("invalid native expression ownership".into())
Expand Down
19 changes: 13 additions & 6 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1879,6 +1879,18 @@ 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<String> {
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)
))
}

/// The bytes of string literal `text`, written with its quotes, after its
/// escapes (IEEE 1800-2023 5.9.1).
pub(in crate::ast) fn string_literal_bytes(text: &str) -> Option<Vec<u8>> {
let text = if let Some(text) = text.strip_prefix("\"\"\"") {
text.strip_suffix("\"\"\"")?
} else {
Expand Down Expand Up @@ -1939,12 +1951,7 @@ fn packed_string_literal(text: &str) -> Option<String> {
};
bytes.push(value);
}
let width = (bytes.len() * 8).max(8);
Some(format!(
"{}'h{}",
width,
num_bigint::BigUint::from_bytes_be(&bytes).to_str_radix(16)
))
Some(bytes)
}

pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> bool {
Expand Down
237 changes: 211 additions & 26 deletions crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,76 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
.map(Some)
}

/// Fold the arguments of a display or write task after its first format
/// into that format when a later string literal is a further format: a
/// string literal that no conversion consumes continues the format, and
/// a value without a conversion of its own is written in the radix of the
/// task (IEEE 1800-2023 21.2.1.1).
fn merge_display_formats(
&self,
task: SystemTask,
args: &mut Vec<SystemTaskArg<Expr>>,
ids: &mut Vec<Option<celox_sv_syntax::ExprId>>,
) {
let (SystemTask::Display(radix)
| SystemTask::Write(radix)
| SystemTask::Fdisplay(radix)
| SystemTask::Fwrite(radix)) = task
else {
return;
};
let Some(start) = template_index(task, args) else {
return;
};
let Some(SystemTaskArg::Str(first)) = args.get(start) else {
return;
};
let mut text = first.clone();
let mut pending = format_conversions(&text).len();
let mut later_format = false;
for arg in &args[start + 1..] {
match arg {
SystemTaskArg::Str(literal) if pending == 0 => {
later_format = true;
pending = format_conversions(literal).len();
text.push_str(literal);
}
_ if pending > 0 => pending -= 1,
SystemTaskArg::Expr(value) => text.push_str(&default_conversion(
expression_binding::string_value(value, &self.dims),
expression_binding::real_value(value, &self.dims),
Comment thread
tignear marked this conversation as resolved.
Resolved
radix,
Comment thread
tignear marked this conversation as resolved.
Resolved
)),
SystemTaskArg::Str(_) => unreachable!("an unconsumed literal is a format"),
SystemTaskArg::Empty => text.push_str(&default_conversion(false, false, radix)),
}
}
if !later_format {
return;
}
// The values keep their places; the further formats are folded into
// the first one.
let mut pending = format_conversions(first).len();
let mut kept = vec![SystemTaskArg::Str(text)];
let mut kept_ids = vec![ids.get(start).copied().flatten()];
for (position, arg) in args.iter().enumerate().skip(start + 1) {
match arg {
SystemTaskArg::Str(literal) if pending == 0 => {
pending = format_conversions(literal).len();
}
arg => {
pending = pending.saturating_sub(1);
kept.push(arg.clone());
kept_ids.push(ids.get(position).copied().flatten());
}
}
}
args.truncate(start);
args.extend(kept);
ids.truncate(start);
ids.extend(kept_ids);
}

/// `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).
Expand Down Expand Up @@ -1453,6 +1523,74 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
);
return Ok(vec![self.format_assignment(output, value)?]);
}
// `$swrite(output, args...)` assigns what `$write(args...)` would
// print, in the radix of its name (IEEE 1800-2023 21.3.3).
if let Some(radix) = swrite_radix(name) {
if arguments.iter().any(|arg| arg.name.is_some()) {
return Err(unsupported(format!("named arguments of `{name}`")));
}
let output = arguments.first().and_then(|arg| arg.value).ok_or_else(|| {
AnalyzerError::InvalidSystemTfCall {
name: name.into(),
detail: "expected an output argument".into(),
}
})?;
// As for `$write`, a string literal that no conversion consumes
// 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 values = Vec::new();
let mut pending = 0;
for (position, arg) in arguments.iter().enumerate().skip(1) {
let id = arg
.value
.ok_or_else(|| AnalyzerError::InvalidSystemTfCall {
name: name.into(),
detail: format!("argument {} is omitted", position + 1),
})?;
let literal = match &declarations.expression(id).kind {
celox_sv_syntax::ExprKind::Literal(text) => {
expression_binding::string_literal_bytes(text)
}
_ => None,
};
if pending == 0
&& let Some(literal) = literal
{
pending = format_conversions(&String::from_utf8_lossy(&literal)).len();
text.extend_from_slice(&literal);
continue;
}
let value =
expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?;
if pending > 0 {
pending -= 1;
} else {
text.extend_from_slice(
default_conversion(
literal.is_some()
|| expression_binding::string_value(&value, &self.dims),
expression_binding::real_value(&value, &self.dims),
radix,
)
.as_bytes(),
);
}
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)
));
let value = expression_binding::string_call(
StringOp::Format {
ticks_per_unit: timescales::time_divisor(root, self.tree)?,
},
std::iter::once(format).chain(values).collect(),
);
return Ok(vec![self.format_assignment(output, value)?]);
}
if name == "$sformatf" {
let mut value =
expression_binding::bind_value(root, declarations, self.tree, &self.dims, None)?;
Expand Down Expand Up @@ -1526,17 +1664,26 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
{
return Ok(SystemTaskArg::Str(text.to_string()));
}
let mut value =
// Renamed below, once the types of the source names have
// chosen the conversions of the format.
let value =
expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?;
self.rename_expr(&mut value);
Ok(SystemTaskArg::Expr(value))
})
.collect::<Result<Vec<_>, AnalyzerError>>()?;
let mut args = args;
// The native expression of each argument, kept in step with `args`.
let mut ids = arguments.iter().map(|arg| arg.value).collect::<Vec<_>>();
self.merge_display_formats(task, &mut args, &mut ids);
for arg in &mut args {
if let SystemTaskArg::Expr(value) = arg {
self.rename_expr(value);
}
}
// A string literal that %t converts is bound as a value: the binder
// handles every literal form, triple quotes and escapes included.
let mut bind = |index: usize| -> Result<Option<Expr>, AnalyzerError> {
let Some(id) = arguments.get(index).and_then(|arg| arg.value) else {
let Some(id) = ids.get(index).copied().flatten() else {
return Ok(None);
};
let mut value =
Expand Down Expand Up @@ -3386,34 +3533,49 @@ pub(super) fn process_site(
})
}

/// `%t` reports a time value in the units of `$timeformat`, by default the
/// smallest time precision of the design (IEEE 1800-2023 20.4.3, Table 20-3),
/// in which the simulation counts its time. The value is in the time unit of
/// the calling scope, of which `ticks_per_unit` simulation time units make
/// one, so each value a `%t` of the template converts is scaled by it.
fn scale_time_conversions(
task: SystemTask,
args: &mut [SystemTaskArg<Expr>],
ticks_per_unit: u64,
bind: &mut impl FnMut(usize) -> Result<Option<Expr>, AnalyzerError>,
) -> Result<(), AnalyzerError> {
if ticks_per_unit == 1 {
return Ok(());
}
let template = match task {
/// The position of the format among the arguments of a display, write or
/// severity task, which a leading string literal there is.
fn template_index(task: SystemTask, args: &[SystemTaskArg<Expr>]) -> Option<usize> {
Some(match task {
SystemTask::Display(_) | SystemTask::Write(_) | SystemTask::Severity(_) => 0,
SystemTask::Fatal => usize::from(matches!(args.first(), Some(SystemTaskArg::Expr(_)))),
SystemTask::Fdisplay(_)
| SystemTask::Fwrite(_)
| SystemTask::Assert
| SystemTask::AssertContinue => 1,
_ => return Ok(()),
};
let Some(SystemTaskArg::Str(text)) = args.get(template) else {
return Ok(());
};
// The conversions of the template, in the order they take arguments
// (21.2.1.2): flags, a width and a precision may precede each.
_ => return None,
})
}

/// The conversion that writes a value without one of its own in a task of
/// `radix` (IEEE 1800-2023 21.2.1.1): a string as text, a real as `$write`
/// writes reals.
fn default_conversion(string: bool, real: bool, radix: system_functions::Radix) -> String {
if real {
"%#g".into()
} else if string {
"%s".into()
} else {
format!("%{}", radix.letter())
}
}

/// The radix of a `$swrite` task named `name`.
fn swrite_radix(name: &str) -> Option<system_functions::Radix> {
use system_functions::Radix;
Some(match name {
"$swrite" => Radix::Decimal,
"$swriteb" => Radix::Binary,
"$swriteo" => Radix::Octal,
"$swriteh" => Radix::Hexadecimal,
_ => return None,
})
}

/// The conversions of a format, in the order they take arguments
/// (IEEE 1800-2023 21.2.1.2): flags, a width and a precision may precede
/// each.
fn format_conversions(text: &str) -> Vec<char> {
let mut conversions = Vec::new();
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
Expand All @@ -3434,7 +3596,30 @@ fn scale_time_conversions(
conversions.push(spec);
}
}
for (offset, spec) in conversions.into_iter().enumerate() {
conversions
}

/// `%t` reports a time value in the units of `$timeformat`, by default the
/// smallest time precision of the design (IEEE 1800-2023 20.4.3, Table 20-3),
/// in which the simulation counts its time. The value is in the time unit of
/// the calling scope, of which `ticks_per_unit` simulation time units make
/// one, so each value a `%t` of the template converts is scaled by it.
fn scale_time_conversions(
task: SystemTask,
args: &mut [SystemTaskArg<Expr>],
ticks_per_unit: u64,
bind: &mut impl FnMut(usize) -> Result<Option<Expr>, AnalyzerError>,
) -> Result<(), AnalyzerError> {
if ticks_per_unit == 1 {
return Ok(());
}
let Some(template) = template_index(task, args) else {
return Ok(());
};
let Some(SystemTaskArg::Str(text)) = args.get(template) else {
return Ok(());
};
for (offset, spec) in format_conversions(text).into_iter().enumerate() {
if !matches!(spec, 't' | 'T') {
continue;
}
Expand Down
6 changes: 3 additions & 3 deletions crates/celox-sv-analyzer/src/system_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1557,13 +1557,13 @@ pub const SYSTEM_TFS: &[SystemTf] = &[
unsupported("$fmonitorb", Task),
unsupported("$fmonitoro", Task),
unsupported("$fmonitorh", Task),
// The binders convert `$swrite`, `$sformat` and `$sformatf` into string
// operations (`StringOp::Format`) before consulting the catalog, which
// rejects them anywhere else, such as in a constant expression.
unsupported("$swrite", Task),
unsupported("$swriteb", Task),
unsupported("$swriteo", Task),
unsupported("$swriteh", Task),
// The binders convert `$sformat` and `$sformatf` into string operations
// (`StringOp::Format`) before consulting the catalog, which rejects them
// anywhere else, such as in a constant expression.
unsupported("$sformat", Task),
unsupported("$sformatf", Function),
function(SystemFunction::Fgetc, 1, Some(1)),
Expand Down
4 changes: 2 additions & 2 deletions crates/celox-test-suite/LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -628,8 +628,8 @@ four-state expectations; the assertions remain enabled on all Celox variants.
| `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. |
| `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). |

The `string_format` cases compare `$sformatf` and `$sformat` with `$display`
of the same format and arguments. The [Icarus observations](verification/sv/limitations/string-format-icarus.json)
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
Expand Down
Loading
Loading