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
55 changes: 32 additions & 23 deletions crates/celox-frontend-sv/src/lowering/ff/containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-frontend-sv/src/lowering/ff/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ fn format_conversions(template: &str) -> Vec<char> {
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);
}
Expand Down
19 changes: 18 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<'_, '_> {
Expand Down Expand Up @@ -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])?;
Expand Down
4 changes: 2 additions & 2 deletions crates/celox-frontend-sv/src/lowering/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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')
Expand Down
138 changes: 138 additions & 0 deletions crates/celox-heap/src/containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -86,6 +97,48 @@ impl Layout {
}
}

/// The text of [`HANDLE_PATTERN`].
pub(crate) fn handle_pattern(handle: u64) -> Vec<u8> {
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<u8>, 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,
Expand Down Expand Up @@ -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<u8> {
let layout = Layout(parameter);
let width = (parameter & 127) as u32;
let signed = parameter & SIGNED_ELEMENTS != 0;
let element = |out: &mut Vec<u8>, 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(
Expand Down Expand Up @@ -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();
Expand Down
7 changes: 7 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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| {
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<FunctionParam>,
/// The function's value as one expression of its arguments, or `None`
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-sv-analyzer/src/ast/expression_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand Down
32 changes: 23 additions & 9 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,11 @@ enum Finish {
domain: std::sync::Arc<crate::ast::enums::EnumDomain>,
count: bool,
},
/// `$sformatf` of the bound children, whose native expressions are `ids`.
Format {
ticks_per_unit: u64,
ids: Vec<ExprId>,
},
/// A read of property `property` of the object handle child.
ObjectLoad(Box<crate::ast::classes::Property>),
/// A call of method subroutine `name` with `formals` formals; the first
Expand Down Expand Up @@ -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("::") {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<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)
))
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
Expand Down
Loading
Loading