Skip to main content

polydat_core/compile/
marshal.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Marshalling between typed `Value`s and compiled-tier slots. One
5//! place owns the rule for every port type, so embedded cones and
6//! whole compiled kernels decode alike:
7//!
8//! - scalars ride as their slot bits, one slot or two;
9//! - every `Ref2` kind rides as a `(ptr, len)` pair (jit_boundary.md,
10//!   axioms S1–S10): a typed vector, a string, or a byte string as a
11//!   slice of its elements, and a JSON, extension, or handle value as
12//!   a one-element slice holding the `Value`.
13//!
14//! Entering the compiled tier, a `Value` is borrowed: the pair points
15//! into the value the caller holds for the duration of the call.
16//! Leaving it, the pair is copied out to an owned `Value`: the
17//! interpreter and the host never hold a reference into a state's
18//! buffers.
19
20use crate::ast::SlotShape;
21use crate::ast::{PortType, Value};
22
23/// The `(ptr, len)` pair a `Ref2`-kind value is borrowed as: into the
24/// value's own bytes or element storage, or the value itself for a
25/// JSON, extension, or handle value. The pair is valid while `v` is.
26/// `None` for a scalar or for a variant the port type does not admit.
27pub(crate) fn borrow_pair(v: &Value) -> Option<(u64, u64)> {
28    Some(match v {
29        Value::Str(s) => (s.as_ptr() as usize as u64, s.len() as u64),
30        Value::Bytes(b) => (b.as_ptr() as usize as u64, b.len() as u64),
31        Value::Json(_) | Value::Ext(_) | Value::Handle(_) => (v as *const Value as usize as u64, 1),
32        Value::VecF32(v) => slice_pair(v.as_slice()),
33        Value::VecF64(v) => slice_pair(v.as_slice()),
34        Value::VecF16(v) => slice_pair(v.as_slice()),
35        Value::VecI8(v) => slice_pair(v.as_slice()),
36        Value::VecI16(v) => slice_pair(v.as_slice()),
37        Value::VecI32(v) => slice_pair(v.as_slice()),
38        Value::VecI64(v) => slice_pair(v.as_slice()),
39        _ => return None,
40    })
41}
42
43/// The `(ptr, len)` pair of a slice.
44#[inline]
45pub(crate) fn slice_pair<T>(s: &[T]) -> (u64, u64) {
46    (s.as_ptr() as usize as u64, s.len() as u64)
47}
48
49/// An empty pair for an unset `Ref2` slot: a dangling, non-null
50/// pointer with length zero, which every slice reader accepts.
51#[inline]
52pub(crate) fn empty_pair() -> (u64, u64) {
53    (
54        std::ptr::NonNull::<u8>::dangling().as_ptr() as usize as u64,
55        0,
56    )
57}
58
59/// A `Value` as the slot bits its port type rides as: the bits of a
60/// scalar, or the borrowed pair of a `Ref2` kind. `None` when the
61/// value's variant has no compiled representation.
62#[cfg(feature = "jit")]
63pub(crate) fn encode_slots(v: &Value, out: &mut [u64]) -> Option<()> {
64    match v {
65        Value::U64(x) => out[0] = *x,
66        Value::I64(x) => out[0] = *x as u64,
67        Value::F64(x) => out[0] = x.to_bits(),
68        Value::Bool(b) => out[0] = *b as u64,
69        _ => {
70            let (p, l) = borrow_pair(v)?;
71            out[0] = p;
72            out[1] = l;
73        }
74    }
75    Some(())
76}
77
78/// The value a `Ref2` pair names, copied out as the `Value` its port
79/// type declares. Every read that leaves the compiled tier goes
80/// through here.
81///
82/// # Safety
83///
84/// The pair was published by a producer whose storage is alive: its
85/// own scratch, an extern's stored value, an interned constant, or a
86/// boundary value alive for the call (axioms S3, S4).
87pub(crate) unsafe fn decode_pair(ty: PortType, ptr: u64, len: u64) -> Value {
88    use crate::ast::SliceArc;
89    let (p, n) = (ptr as usize, len as usize);
90    // SAFETY: as documented on the function.
91    unsafe {
92        match ty {
93            PortType::Str => Value::Str(std::sync::Arc::from(std::str::from_utf8_unchecked(
94                std::slice::from_raw_parts(p as *const u8, n),
95            ))),
96            PortType::Bytes => Value::Bytes(std::sync::Arc::from(std::slice::from_raw_parts(
97                p as *const u8,
98                n,
99            ))),
100            PortType::Json | PortType::Ext | PortType::Handle => {
101                if n == 0 {
102                    Value::None
103                } else {
104                    (*(p as *const Value)).clone()
105                }
106            }
107            PortType::VecF32 => Value::VecF32(SliceArc::from_vec(
108                std::slice::from_raw_parts(p as *const f32, n).to_vec(),
109            )),
110            PortType::VecF64 => Value::VecF64(SliceArc::from_vec(
111                std::slice::from_raw_parts(p as *const f64, n).to_vec(),
112            )),
113            PortType::VecF16 => Value::VecF16(SliceArc::from_vec(
114                std::slice::from_raw_parts(p as *const half::f16, n).to_vec(),
115            )),
116            PortType::VecI8 => Value::VecI8(SliceArc::from_vec(
117                std::slice::from_raw_parts(p as *const i8, n).to_vec(),
118            )),
119            PortType::VecI16 => Value::VecI16(SliceArc::from_vec(
120                std::slice::from_raw_parts(p as *const i16, n).to_vec(),
121            )),
122            PortType::VecI32 => Value::VecI32(SliceArc::from_vec(
123                std::slice::from_raw_parts(p as *const i32, n).to_vec(),
124            )),
125            PortType::VecI64 => Value::VecI64(SliceArc::from_vec(
126                std::slice::from_raw_parts(p as *const i64, n).to_vec(),
127            )),
128            other => panic!("{other:?} is not a Ref2-colored port type"),
129        }
130    }
131}
132
133/// The port type of the `Value` a port of type `ty` carries, which is
134/// what [`decode_slot`] reads back. A narrow integer rides the 64-bit
135/// carrier of its sign, and `f32` and `f16` ride their bit patterns in
136/// a `U64`, as their `Wire` impls inject them; every other type is its
137/// own carrier.
138pub(crate) fn carrier_port(ty: PortType) -> PortType {
139    match ty {
140        PortType::I8 | PortType::I16 | PortType::I32 => PortType::I64,
141        PortType::U32 | PortType::U16 | PortType::U8 | PortType::F32 | PortType::F16 => {
142            PortType::U64
143        }
144        other => other,
145    }
146}
147
148/// Slot bits as the `Value` their declared port type names, copied
149/// out where they are a pair.
150///
151/// The read is chosen by the type's slot color, as `write_poly`'s
152/// write is, so every compiled read of a value (an output a host
153/// pulls, and an input a polymorphic node takes) is the inverse of
154/// the one write. This used to match on the type with a `U64`
155/// fallback. The `Imm2` limb reassembly lived only in
156/// `decode_output`, so a register or 128-bit value reaching a
157/// polymorphic node's input fell through to the fallback and arrived
158/// as its low limb, typed `U64`. The type system knew better at every
159/// step; only the fallback arm did not.
160pub(crate) fn decode_slot(slots: &[u64], ty: PortType) -> Value {
161    use crate::ast::{Bits128, RegLanes, SlotColor};
162    match ty.slot_color() {
163        SlotColor::Imm1 => match ty {
164            PortType::F64 => Value::F64(f64::from_bits(slots[0])),
165            PortType::Bool => Value::Bool(slots[0] != 0),
166            // A signed narrow carrier rides sign-extended (alignment
167            // §2) and is the `I64` value its `Wire` impl injects.
168            PortType::I64 | PortType::I8 | PortType::I16 | PortType::I32 => {
169                Value::I64(slots[0] as i64)
170            }
171            // Unsigned narrow carriers ride zero-extended, and `f32`
172            // and `f16` ride their bit patterns, all in the `U64`
173            // carrier their `Wire` impls inject.
174            PortType::U64
175            | PortType::U32
176            | PortType::U16
177            | PortType::U8
178            | PortType::F32
179            | PortType::F16 => Value::U64(slots[0]),
180            other => unreachable!("{other:?} is colored Imm1 but has no one-slot carrier"),
181        },
182        // Two consecutive slots of limb data, low word first
183        // (alignment §6).
184        SlotColor::Imm2 => {
185            let limbs = Bits128([slots[0], slots[1]]);
186            match ty {
187                PortType::U128 => Value::U128(limbs),
188                PortType::I128 => Value::I128(limbs),
189                PortType::Reg128 => Value::Reg128(limbs, RegLanes::Raw),
190                PortType::RegI8x16 => Value::Reg128(limbs, RegLanes::I8x16),
191                PortType::RegI16x8 => Value::Reg128(limbs, RegLanes::I16x8),
192                PortType::RegI32x4 => Value::Reg128(limbs, RegLanes::I32x4),
193                PortType::RegI64x2 => Value::Reg128(limbs, RegLanes::I64x2),
194                PortType::RegF16x8 => Value::Reg128(limbs, RegLanes::F16x8),
195                PortType::RegF32x4 => Value::Reg128(limbs, RegLanes::F32x4),
196                PortType::RegF64x2 => Value::Reg128(limbs, RegLanes::F64x2),
197                other => unreachable!("{other:?} is colored Imm2 but is not a 128-bit value"),
198            }
199        }
200        // SAFETY: the pair in a kernel's buffer was published by a
201        // producer whose storage is alive (axioms S3, S4).
202        SlotColor::Ref2 => unsafe { decode_pair(ty, slots[0], slots[1]) },
203    }
204}
205
206/// An output at `slot` of `buffer` as the `Value` its port type names.
207/// This is the typed read every compiled kernel's `get_value` makes.
208pub fn decode_output(buffer: &[u64], slot: usize, ty: PortType) -> Value {
209    decode_slot(&buffer[slot..], ty)
210}
211
212/// An argument's slots as a borrowed view of the value, decoded by its
213/// port type: nothing is copied. A string, byte string, or value is
214/// borrowed through its pair, valid while its producer's storage is.
215///
216/// # Safety
217///
218/// As for `decode_pair`.
219pub unsafe fn arg_ref<'a>(ty: PortType, slots: &'a [u64]) -> crate::ast::ValueRef<'a> {
220    use crate::ast::ValueRef;
221    let (p, n) = (
222        slots.first().copied().unwrap_or(0) as usize,
223        slots.get(1).copied().unwrap_or(0) as usize,
224    );
225    // SAFETY: as documented on the function.
226    unsafe {
227        match ty {
228            PortType::U64 => ValueRef::U64(slots[0]),
229            PortType::I64 | PortType::I8 | PortType::I16 | PortType::I32 => {
230                ValueRef::I64(slots[0] as i64)
231            }
232            PortType::F64 => ValueRef::F64(f64::from_bits(slots[0])),
233            PortType::Bool => ValueRef::Bool(slots[0] != 0),
234            PortType::Str => ValueRef::Str(std::str::from_utf8_unchecked(
235                std::slice::from_raw_parts(p as *const u8, n),
236            )),
237            PortType::Bytes => ValueRef::Bytes(std::slice::from_raw_parts(p as *const u8, n)),
238            PortType::Json | PortType::Ext | PortType::Handle => {
239                if n == 0 {
240                    ValueRef::None
241                } else {
242                    ValueRef::from(&*(p as *const Value))
243                }
244            }
245            _ => ValueRef::U64(slots[0]),
246        }
247    }
248}