Skip to main content

polydat_core/
ast.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Core types for Polydat nodes: values, ports, metadata, and the evaluation trait.
5//!
6//! The Polydat type system has three layers:
7//!
8//! 1. **Runtime values** ([`Value`]) — the enum that flows through
9//!    the DAG at evaluation time. Every interpreter buffer slot holds
10//!    a `Value`; compiled kernels carry the same values as typed
11//!    `u64` slots.
12//!
13//! 2. **Port types** ([`PortType`]) — compile-time type tags on
14//!    node input/output ports. The assembler validates that wiring
15//!    connects compatible types and auto-inserts adapters when not.
16//!
17//! 3. **Slot types** ([`SlotType`]) — distinguishes wire inputs
18//!    (cycle-time values) from constant parameters (baked at
19//!    construction). The DSL compiler uses these to decide whether
20//!    a literal in a function call is a wire promotion or a const arg.
21//!
22//! The [`PolydatNode`] trait is what every node function implements.
23//! A node declares its port metadata via [`NodeMeta`] and evaluates
24//! via `eval(&[Value], &mut [Value])`.
25
26use std::fmt;
27use std::ops::Deref;
28use std::sync::Arc;
29
30/// Arc-managed typed slice. Holds a borrow into a parent Arc'd
31/// owner — typically either an owned backing buffer (`Arc<[T]>`)
32/// or a long-lived resource like an mmap'd dataset. Cloning is
33/// one `Arc::clone` (atomic increment, zero allocations); the
34/// owner is type-erased as `Arc<dyn Any + Send + Sync>` so the
35/// same `SliceArc<T>` shape covers both modes.
36///
37/// Used by [`Value::VecF32`] / [`Value::VecI32`] to flow vector
38/// data on wires from accessors to native-binding adapters with:
39///   - zero per-cycle allocation when the source supports
40///     zero-copy reads (mmap-backed `VectorReader::get_slice`),
41///   - exactly one allocation when it doesn't (a `Vec<T>` from
42///     `VectorReader::get`, wrapped into an `Arc<[T]>`).
43///
44/// See SRD 53 §"Native Vector Binding".
45pub struct SliceArc<T: 'static> {
46    /// Keeps the storage alive. For owned data this is an
47    /// `Arc<OwnedSlice<T>>`; for mmap-backed data this is an
48    /// `Arc<UniformDataset<T>>` (or any other type whose Arc
49    /// keeps the underlying memory mapped).
50    _owner: Arc<dyn std::any::Any + Send + Sync>,
51    ptr: *const T,
52    len: usize,
53}
54
55// Send/Sync: the raw pointer is treated as a borrow into memory
56// owned by `_owner`, which is itself Send+Sync. T must be
57// Send+Sync for the slice contents to be safely shared.
58unsafe impl<T: Send + Sync + 'static> Send for SliceArc<T> {}
59unsafe impl<T: Send + Sync + 'static> Sync for SliceArc<T> {}
60
61/// Type-erasable wrapper for an owned `Arc<[T]>`. Used as the
62/// owner when the source isn't zero-copy — `Arc<[T]>` is unsized
63/// so it can't be cast to `Arc<dyn Any>` directly, but
64/// `OwnedSlice<T>` is sized and the cast works.
65// Field is unused at the type level — its only job is to keep the
66// Arc<[T]> reference count alive while the SliceArc holds the raw
67// pointer into the buffer. Hence the `dead_code` allow.
68#[allow(dead_code)]
69pub(crate) struct OwnedSlice<T: 'static>(pub(crate) Arc<[T]>);
70
71impl<T: Send + Sync + 'static> SliceArc<T> {
72    /// Build from an owned `Vec<T>`. One heap allocation
73    /// (`Vec → Arc<[T]>`); cloning the resulting `SliceArc<T>` is
74    /// one atomic increment.
75    pub fn from_vec(v: Vec<T>) -> Self {
76        let arc: Arc<[T]> = Arc::from(v);
77        let ptr = arc.as_ptr();
78        let len = arc.len();
79        let owner: Arc<dyn std::any::Any + Send + Sync> = Arc::new(OwnedSlice(arc));
80        Self {
81            _owner: owner,
82            ptr,
83            len,
84        }
85    }
86
87    /// Build from a `&[T]` borrowed from `owner`'s data.
88    ///
89    /// # Safety
90    ///
91    /// `slice` must point into memory owned by `owner` and
92    /// remain valid for at least as long as `owner` (i.e., until
93    /// the last clone of this Arc is dropped). The caller asserts
94    /// this — typical use is mmap-backed readers where the slice
95    /// is a view into a memory-mapped page kept alive by the
96    /// dataset Arc.
97    pub unsafe fn from_borrowed(owner: Arc<dyn std::any::Any + Send + Sync>, slice: &[T]) -> Self {
98        Self {
99            _owner: owner,
100            ptr: slice.as_ptr(),
101            len: slice.len(),
102        }
103    }
104}
105
106impl<T: 'static> SliceArc<T> {
107    /// Borrow as `&[T]`. The borrow lives as long as `&self`.
108    /// Defined here without Send+Sync bounds so it's reachable
109    /// from `Deref`/`PartialEq`/`Debug` impls that don't carry
110    /// those bounds.
111    #[inline]
112    pub fn as_slice(&self) -> &[T] {
113        // SAFETY: `_owner` keeps the storage alive; `ptr`/`len`
114        // were validated at construction. The returned reference
115        // is bounded by `&self`'s lifetime.
116        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
117    }
118}
119
120impl<T: Send + Sync + 'static> Clone for SliceArc<T> {
121    fn clone(&self) -> Self {
122        Self {
123            _owner: self._owner.clone(),
124            ptr: self.ptr,
125            len: self.len,
126        }
127    }
128}
129
130impl<T: 'static> Deref for SliceArc<T> {
131    type Target = [T];
132    fn deref(&self) -> &[T] {
133        // SAFETY: identical reasoning to as_slice().
134        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
135    }
136}
137
138impl<T: PartialEq + 'static> PartialEq for SliceArc<T> {
139    fn eq(&self, other: &Self) -> bool {
140        // Pointer-equal pair → trivially equal (zero-copy from the
141        // same source). Otherwise compare contents — two unrelated
142        // SliceArcs may hold equal data.
143        if std::ptr::eq(self.ptr, other.ptr) && self.len == other.len {
144            return true;
145        }
146        self.as_slice() == other.as_slice()
147    }
148}
149
150impl<T: fmt::Debug + 'static> fmt::Debug for SliceArc<T> {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.debug_struct("SliceArc")
153            .field("len", &self.len)
154            .field("first", &self.as_slice().first())
155            .finish_non_exhaustive()
156    }
157}
158
159/// Two-limb carrier for 128-bit integers inside [`Value`].
160///
161/// Limbs are little-endian (`[lo, hi]`). Using `[u64; 2]` instead
162/// of a raw `u128`/`i128` field keeps `Value`'s alignment at 8 and
163/// its size inside the 40-byte buffer-slot envelope; reassembly is
164/// two register moves.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166pub struct Bits128(pub [u64; 2]);
167
168impl Bits128 {
169    #[inline]
170    /// The two-word form of a `u128`, low word first.
171    pub fn from_u128(v: u128) -> Self {
172        Self([v as u64, (v >> 64) as u64])
173    }
174    #[inline]
175    /// The two-word form of an `i128`, low word first.
176    pub fn from_i128(v: i128) -> Self {
177        Self::from_u128(v as u128)
178    }
179    /// The word as a `u128`.
180    #[inline]
181    pub fn as_u128(self) -> u128 {
182        (self.0[0] as u128) | ((self.0[1] as u128) << 64)
183    }
184    /// The word as an `i128`.
185    #[inline]
186    pub fn as_i128(self) -> i128 {
187        self.as_u128() as i128
188    }
189
190    #[inline]
191    /// The word's sixteen bytes, little-endian.
192    pub fn to_le_bytes(self) -> [u8; 16] {
193        self.as_u128().to_le_bytes()
194    }
195
196    #[inline]
197    /// A word from sixteen little-endian bytes.
198    pub fn from_le_bytes(b: [u8; 16]) -> Self {
199        Self::from_u128(u128::from_le_bytes(b))
200    }
201}
202
203/// Lane-codec macro: `[T; N]` views over the 16-byte word,
204/// little-endian lane order (lane 0 = lowest address).
205macro_rules! bits128_lanes {
206    ($to:ident, $from:ident, $t:ty, $n:expr) => {
207        impl Bits128 {
208            #[inline]
209            /// The word as lanes of one element type, lane 0 at the lowest address.
210            pub fn $to(self) -> [$t; $n] {
211                let b = self.to_le_bytes();
212                let mut out = [<$t>::default(); $n];
213                let w = core::mem::size_of::<$t>();
214                for (i, lane) in out.iter_mut().enumerate() {
215                    let mut lb = [0u8; core::mem::size_of::<$t>()];
216                    lb.copy_from_slice(&b[i * w..(i + 1) * w]);
217                    *lane = <$t>::from_le_bytes(lb);
218                }
219                out
220            }
221            #[inline]
222            /// A word from lanes of one element type, lane 0 at the lowest address.
223            pub fn $from(lanes: [$t; $n]) -> Self {
224                let mut b = [0u8; 16];
225                let w = core::mem::size_of::<$t>();
226                for (i, lane) in lanes.iter().enumerate() {
227                    b[i * w..(i + 1) * w].copy_from_slice(&lane.to_le_bytes());
228                }
229                Self::from_le_bytes(b)
230            }
231        }
232    };
233}
234
235bits128_lanes!(lanes_i8, from_lanes_i8, i8, 16);
236bits128_lanes!(lanes_i16, from_lanes_i16, i16, 8);
237bits128_lanes!(lanes_i32, from_lanes_i32, i32, 4);
238bits128_lanes!(lanes_i64, from_lanes_i64, i64, 2);
239bits128_lanes!(lanes_f32, from_lanes_f32, f32, 4);
240bits128_lanes!(lanes_f64, from_lanes_f64, f64, 2);
241
242impl Bits128 {
243    /// f16 lanes go through the bit-pattern codec (`half::f16`
244    /// has no `to_le_bytes`).
245    #[inline]
246    pub fn lanes_f16(self) -> [half::f16; 8] {
247        self.lanes_i16().map(|b| half::f16::from_bits(b as u16))
248    }
249    #[inline]
250    /// A word from eight `f16` lanes, through the bit-pattern codec.
251    pub fn from_lanes_f16(lanes: [half::f16; 8]) -> Self {
252        Self::from_lanes_i16(lanes.map(|f| f.to_bits() as i16))
253    }
254}
255
256/// Lane-typing view tag for [`Value::Reg128`] — which
257/// interpretation a 128-bit register word currently carries
258/// (type_system_alignment.md §8.4 layer 2). `Raw` is the
259/// algorithm-defined buffer-state view (heterogeneous lane
260/// roles); the typed views are homogeneous `[T; N]` readings.
261/// All views are free bitcasts of one another.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
263pub enum RegLanes {
264    /// The algorithm-defined view: heterogeneous lane roles, no element type.
265    Raw,
266    /// Sixteen `i8` lanes.
267    I8x16,
268    /// Eight `i16` lanes.
269    I16x8,
270    /// Four `i32` lanes.
271    I32x4,
272    /// Two `i64` lanes.
273    I64x2,
274    /// Eight `f16` lanes.
275    F16x8,
276    /// Four `f32` lanes.
277    F32x4,
278    /// Two `f64` lanes.
279    F64x2,
280}
281
282#[derive(Debug, Clone)]
283/// A typed value on a wire: what a node reads and produces on the
284/// interpreter, and what a host sets and pulls on every engine.
285pub enum Value {
286    /// Unsigned 64-bit integer. The workhorse type for deterministic
287    /// data generation: hash outputs, modular arithmetic, bit
288    /// manipulation, cycle counters, primary keys.
289    U64(u64),
290    /// Unsigned 128-bit integer (cranelift I128, unsigned
291    /// interpretation). Carried as two u64 limbs ([`Bits128`],
292    /// little-endian limb order) so `Value` keeps alignment 8 —
293    /// see the `value_size_probe` test. Carried as two immediate
294    /// slots (`SlotColor::Imm2`) in compiled kernels. JSON
295    /// projection is a decimal string (JSON Number cannot carry
296    /// 128-bit magnitude).
297    U128(Bits128),
298    /// Signed 128-bit integer (cranelift I128, signed
299    /// interpretation). Same limb carrier and conventions as
300    /// [`Value::U128`].
301    I128(Bits128),
302    /// 128-bit SIMD register word (type_system_alignment.md
303    /// §8.4 layer 2). The [`RegLanes`] tag records the current
304    /// view — a homogeneous lane typing (`[f32; 4]`, `[i16; 8]`,
305    /// …) or `Raw` (algorithm-defined buffer state with
306    /// heterogeneous lane roles). Views are free bitcasts; the
307    /// word is a plain value (two u64 slots in compiled buffers,
308    /// no pointers, no lifetime).
309    Reg128(Bits128, RegLanes),
310    /// Signed 64-bit integer. The honest runtime carrier for
311    /// `PortType::I64` (and sign-extended `I32`) slots — matching
312    /// `serde_json::Number`'s `NegInt` leaf so display and JSON
313    /// projection render negatives as negatives instead of their
314    /// unsigned bit-reinterpretation. At the JIT boundary the bits
315    /// ride the same u64 slot (`i64 as u64` is a free bitcast), so
316    /// signedness costs nothing in compiled kernels. See
317    /// `polydat/docs/design/type_system_alignment.md` §5.
318    I64(i64),
319    /// IEEE 754 double-precision float. Used for distributions,
320    /// noise functions, trigonometry, interpolation, and any
321    /// computation that needs fractional precision.
322    F64(f64),
323    /// Boolean. Used for conditional ops (`if:` field), selection
324    /// nodes, and flag computation.
325    Bool(bool),
326    /// Shared, immutable UTF-8 string. Used for formatted output,
327    /// weighted string selection, template interpolation, and any
328    /// value that will appear directly in an op statement. Backed
329    /// by `Arc<str>` so cloning is one atomic increment with no
330    /// allocation — the per-cycle reads that materialize a `final`
331    /// or `init` string into op-template substitution are
332    /// pointer-share, not heap-copy.
333    Str(Arc<str>),
334    /// Shared, immutable raw byte buffer. Used for cryptographic
335    /// digests, binary encoding/decoding, and byte-level data
336    /// generation. Backed by `Arc<[u8]>` so cloning is one atomic
337    /// increment.
338    Bytes(Arc<[u8]>),
339    /// Shared, immutable structured JSON value. Used for
340    /// vector representations (JSON arrays), complex structured
341    /// data, and JSON merge ops. Backed by `Arc<serde_json::Value>`
342    /// so cloning is one atomic increment — the per-cycle reads
343    /// of result-body JSON wires (capture extraction, recall
344    /// evaluation, column projection) share the underlying
345    /// allocation rather than deep-cloning the tree. Consumers
346    /// that need an owned `serde_json::Value` (mutation,
347    /// serialization sinks) explicitly deep-clone via
348    /// `(*v).clone()` at the consume site.
349    Json(Arc<serde_json::Value>),
350    /// Adapter-contributed reflected value. Carries type info and
351    /// standard access methods (display, JSON, string, bytes).
352    /// Enables protocol-native types (UUIDs, timestamps, inet
353    /// addresses) to flow through Polydat without boxing to strings.
354    Ext(Box<dyn ReflectedValue>),
355    /// Type-erased Arc handle to a resolved resource (dataset,
356    /// prepared statement, ...). Cloning during input gather is one
357    /// `Arc::clone` — a single atomic increment, zero allocations.
358    /// Produced by resolver nodes (e.g. `dataset_open`) and consumed
359    /// by reader nodes that downcast to the concrete type. See
360    /// SRD 53 §"Dataset Handles" for the canonical use case.
361    Handle(Arc<dyn std::any::Any + Send + Sync>),
362    /// Typed `f32` vector carrier. Flows from vector accessors to
363    /// native-binding adapters without string formatting or byte
364    /// serialization on the cycle path. Cloning is one `Arc::clone`,
365    /// zero allocations. The underlying [`SliceArc`] supports both
366    /// owned (allocated `Arc<[f32]>`) and zero-copy (borrow into a
367    /// long-lived owner like an mmap'd dataset) storage modes.
368    /// `to_display_string()` renders as JSON array.
369    VecF32(SliceArc<f32>),
370    /// Typed `i32` vector carrier (e.g. neighbor indices). Same
371    /// shape as VecF32 — typed slice on the wire.
372    VecI32(SliceArc<i32>),
373    /// Typed `f64` vector carrier (`Arc<[f64]>`). Same shape as
374    /// VecF32. Used for double-precision embeddings / dense
375    /// numeric features bound to CQL `vector<double, N>` etc.
376    VecF64(SliceArc<f64>),
377    /// Typed `i64` vector carrier (`Arc<[i64]>`). 64-bit integer
378    /// vectors for CQL `vector<bigint, N>`.
379    VecI64(SliceArc<i64>),
380    /// Typed half-precision float vector (`Arc<[half::f16]>`).
381    /// 16-bit float carrier — stays at f16 on the wire so
382    /// embeddings stored as half-precision aren't widened on the
383    /// kernel side.
384    VecF16(SliceArc<half::f16>),
385    /// Typed `i16` vector carrier (`Arc<[i16]>`). 16-bit signed
386    /// integer vectors for CQL `vector<smallint, N>`.
387    VecI16(SliceArc<i16>),
388    /// Typed `i8` vector carrier (`Arc<[i8]>`). 8-bit signed
389    /// integer vectors (CQL `vector<tinyint, N>`); completes the
390    /// cranelift lane family {i8, i16, i32, i64, f16, f32, f64}
391    /// (type_system_alignment.md §8.2). Unsigned byte buffers are
392    /// spelled `Bytes`.
393    VecI8(SliceArc<i8>),
394    /// The absent value (SRD-74): fresh buffer slots start as
395    /// `None`, and the kernel propagates it through nodes that do
396    /// not `accepts_none_inputs`.
397    None,
398}
399
400impl PartialEq for Value {
401    fn eq(&self, other: &Self) -> bool {
402        match (self, other) {
403            (Value::U64(a), Value::U64(b)) => a == b,
404            (Value::I64(a), Value::I64(b)) => a == b,
405            (Value::U128(a), Value::U128(b)) => a == b,
406            (Value::I128(a), Value::I128(b)) => a == b,
407            (Value::Reg128(a, av), Value::Reg128(b, bv)) => a == b && av == bv,
408            (Value::F64(a), Value::F64(b)) => a == b,
409            (Value::Bool(a), Value::Bool(b)) => a == b,
410            // Arc-backed variants: pointer-eq fast path before
411            // any content compare. Hot per-cycle callers
412            // (notably `PolydatState::reset_inputs_from`'s
413            // "still at default?" probe) typically test a slot
414            // against a value that was Arc-cloned from the same
415            // source — `Arc::ptr_eq` is O(1) and lets the deep
416            // compare drop out of the per-cycle path.
417            (Value::Str(a), Value::Str(b)) => Arc::ptr_eq(a, b) || a == b,
418            (Value::Bytes(a), Value::Bytes(b)) => Arc::ptr_eq(a, b) || a == b,
419            (Value::Json(a), Value::Json(b)) => Arc::ptr_eq(a, b) || a == b,
420            (Value::None, Value::None) => true,
421            (Value::Ext(a), Value::Ext(b)) => {
422                a.type_name() == b.type_name() && a.display() == b.display()
423            }
424            (Value::Handle(a), Value::Handle(b)) => Arc::ptr_eq(a, b),
425            (Value::VecF32(a), Value::VecF32(b)) => a == b,
426            (Value::VecI32(a), Value::VecI32(b)) => a == b,
427            (Value::VecF64(a), Value::VecF64(b)) => a == b,
428            (Value::VecI64(a), Value::VecI64(b)) => a == b,
429            (Value::VecF16(a), Value::VecF16(b)) => a == b,
430            (Value::VecI16(a), Value::VecI16(b)) => a == b,
431            (Value::VecI8(a), Value::VecI8(b)) => a == b,
432            _ => false,
433        }
434    }
435}
436
437/// Trait for adapter-contributed value types.
438///
439/// Any type that flows through the Polydat Kernel as `Value::Ext` must
440/// implement this. It provides standard access patterns that work
441/// across adapter boundaries — stdout can display it, HTTP can
442/// serialize it, model adapter can capture it — without needing
443/// the concrete type.
444///
445/// The producing adapter can downcast via `as_any()` when it needs
446/// native protocol access (e.g., CQL binding a `uuid::Uuid`).
447pub trait ReflectedValue: Send + Sync + std::fmt::Debug {
448    /// Type name for diagnostics and describe output.
449    fn type_name(&self) -> &str;
450
451    /// Human-readable string representation.
452    /// Used by stdout adapter, logging, and diagnostics.
453    fn display(&self) -> String;
454
455    /// JSON representation for serialization and HTTP bodies.
456    fn to_json_value(&self) -> serde_json::Value {
457        serde_json::Value::String(self.display())
458    }
459
460    /// Try to represent as a string. Many types have a canonical
461    /// string form (UUIDs, timestamps, IP addresses).
462    fn try_as_str(&self) -> Option<String> {
463        Some(self.display())
464    }
465
466    /// Try to represent as u64.
467    fn try_as_u64(&self) -> Option<u64> {
468        None
469    }
470
471    /// Try to represent as f64.
472    fn try_as_f64(&self) -> Option<f64> {
473        None
474    }
475
476    /// Try to represent as bytes.
477    fn try_as_bytes(&self) -> Option<&[u8]> {
478        None
479    }
480
481    /// Downcast to the concrete type. Only works when the consuming
482    /// code has the concrete type in scope (same crate or shared dep).
483    fn as_any(&self) -> &dyn std::any::Any;
484
485    /// Clone into a new boxed trait object.
486    fn clone_reflected(&self) -> Box<dyn ReflectedValue>;
487}
488
489impl Clone for Box<dyn ReflectedValue> {
490    fn clone(&self) -> Self {
491        self.clone_reflected()
492    }
493}
494
495impl Value {
496    /// The `U64` payload; panics on any other variant, naming both types.
497    #[inline]
498    pub fn as_u64(&self) -> u64 {
499        match self {
500            Value::U64(v) => *v,
501            _ => panic!("expected U64, got {:?}", self.port_type()),
502        }
503    }
504
505    /// Read a signed 64-bit integer. Accepts the honest `Value::I64`
506    /// carrier and — during the bit-stuffed-to-honest migration —
507    /// a legacy `Value::U64` whose bits are reinterpreted (the
508    /// pre-alignment storage convention for `PortType::I64` slots).
509    #[inline]
510    pub fn as_i64(&self) -> i64 {
511        match self {
512            Value::I64(v) => *v,
513            Value::U64(v) => *v as i64,
514            _ => panic!("expected I64, got {:?}", self.port_type()),
515        }
516    }
517
518    /// Read an unsigned 128-bit integer. Accepts the honest
519    /// `Value::U128` carrier plus zero-extended `U64` (widening
520    /// is implicit at read sites the way `as_i64` accepts the
521    /// legacy stuffed form).
522    #[inline]
523    pub fn as_u128(&self) -> u128 {
524        match self {
525            Value::U128(b) => b.as_u128(),
526            Value::U64(v) => *v as u128,
527            _ => panic!("expected U128, got {:?}", self.port_type()),
528        }
529    }
530
531    /// Read a signed 128-bit integer. Accepts `Value::I128` plus
532    /// sign-extended `I64` and zero-extended `U64`.
533    #[inline]
534    pub fn as_i128(&self) -> i128 {
535        match self {
536            Value::I128(b) => b.as_i128(),
537            Value::I64(v) => *v as i128,
538            Value::U64(v) => *v as i128,
539            _ => panic!("expected I128, got {:?}", self.port_type()),
540        }
541    }
542
543    /// Read a 128-bit register word under any view (views are
544    /// free bitcasts — a consumer declaring a different lane
545    /// typing than the producer is the intended use).
546    #[inline]
547    pub fn as_reg_bits(&self) -> Bits128 {
548        match self {
549            Value::Reg128(b, _) => *b,
550            _ => panic!("expected Reg128, got {:?}", self.port_type()),
551        }
552    }
553
554    /// The `F64` payload; panics on any other variant, naming both types.
555    #[inline]
556    pub fn as_f64(&self) -> f64 {
557        match self {
558            Value::F64(v) => *v,
559            _ => panic!("expected F64, got {:?}", self.port_type()),
560        }
561    }
562
563    /// The `Bool` payload; panics on any other variant, naming both types.
564    #[inline]
565    pub fn as_bool(&self) -> bool {
566        match self {
567            Value::Bool(v) => *v,
568            _ => panic!("expected Bool, got {:?}", self.port_type()),
569        }
570    }
571
572    /// The `Str` payload as a string slice; panics on any other variant.
573    #[inline]
574    pub fn as_str(&self) -> &str {
575        match self {
576            Value::Str(v) => v,
577            _ => panic!("expected Str, got {:?}", self.port_type()),
578        }
579    }
580
581    /// The `Bytes` payload as a byte slice; panics on any other variant.
582    #[inline]
583    pub fn as_bytes(&self) -> &[u8] {
584        match self {
585            Value::Bytes(v) => v,
586            _ => panic!("expected Bytes, got {:?}", self.port_type()),
587        }
588    }
589
590    /// The `Json` payload by reference; panics on any other variant.
591    #[inline]
592    pub fn as_json(&self) -> &serde_json::Value {
593        match self {
594            Value::Json(v) => v,
595            _ => panic!("expected Json, got {:?}", self.port_type()),
596        }
597    }
598
599    /// Borrow the inner `Arc<serde_json::Value>` from a
600    /// `Value::Json` variant. Use when a consumer wants to
601    /// share the JSON tree across kernels without deep-cloning
602    /// the structure — e.g. capture extraction that writes the
603    /// same JSON wire to multiple downstream slots. Panics on
604    /// type mismatch.
605    #[inline]
606    pub fn as_json_arc(&self) -> &Arc<serde_json::Value> {
607        match self {
608            Value::Json(v) => v,
609            _ => panic!("expected Json, got {:?}", self.port_type()),
610        }
611    }
612
613    /// Return the `PortType` corresponding to this value's variant.
614    #[inline]
615    pub fn port_type(&self) -> PortType {
616        match self {
617            Value::U64(_) => PortType::U64,
618            Value::I64(_) => PortType::I64,
619            Value::U128(_) => PortType::U128,
620            Value::I128(_) => PortType::I128,
621            Value::Reg128(_, v) => match v {
622                RegLanes::Raw => PortType::Reg128,
623                RegLanes::I8x16 => PortType::RegI8x16,
624                RegLanes::I16x8 => PortType::RegI16x8,
625                RegLanes::I32x4 => PortType::RegI32x4,
626                RegLanes::I64x2 => PortType::RegI64x2,
627                RegLanes::F16x8 => PortType::RegF16x8,
628                RegLanes::F32x4 => PortType::RegF32x4,
629                RegLanes::F64x2 => PortType::RegF64x2,
630            },
631            Value::F64(_) => PortType::F64,
632            Value::Bool(_) => PortType::Bool,
633            Value::Str(_) => PortType::Str,
634            Value::Bytes(_) => PortType::Bytes,
635            Value::Json(_) => PortType::Json,
636            Value::Ext(_) => PortType::Ext,
637            Value::Handle(_) => PortType::Handle,
638            Value::VecF32(_) => PortType::VecF32,
639            Value::VecI32(_) => PortType::VecI32,
640            Value::VecF64(_) => PortType::VecF64,
641            Value::VecI64(_) => PortType::VecI64,
642            Value::VecF16(_) => PortType::VecF16,
643            Value::VecI16(_) => PortType::VecI16,
644            Value::VecI8(_) => PortType::VecI8,
645            Value::None => PortType::U64, // placeholder
646        }
647    }
648
649    /// Borrow a `VecF32` value as `&[f32]`. Panics on type mismatch.
650    #[inline]
651    pub fn as_vec_f32(&self) -> &[f32] {
652        match self {
653            Value::VecF32(arc) => arc,
654            _ => panic!("expected VecF32, got {:?}", self.port_type()),
655        }
656    }
657
658    /// Test whether this value's runtime variant is acceptable
659    /// to a slot declaring `slot_type`. `port_type() == slot_type`
660    /// is the strict case; this method also accepts the
661    /// **bit-stuffing equivalences** documented in
662    /// `polydat/docs/design/type_system.md` §1:
663    ///
664    /// - `Value::U64` is the runtime storage for `PortType` `U64`,
665    ///   `U32`, `I64`, and `I32` (narrow integers carry their
666    ///   bits in the low part of the u64; sign-extension for
667    ///   `I32` is part of the producer convention).
668    /// - `Value::F64` is the runtime storage for `PortType` `F64`
669    ///   and `F32` (`F32` carries its bits in the low 32 via
670    ///   `f32::to_bits() as u64`-style stuffing — but float
671    ///   stuffing uses `Value::F64` for the materialised float
672    ///   value, not the bit pattern).
673    /// - `Value::None` is acceptable for every slot type
674    ///   (SRD-74 absent sentinel).
675    ///
676    /// Used at the typed-write residual check
677    /// (`Dataflow::set_wire_idx`) AFTER the boundary adapter has
678    /// already converted/validated the value — see
679    /// `kernel/api_impl.rs`. The pre-adapter check in
680    /// `adapt_boundary_value` stays strict (`port_type ==
681    /// slot_type`) so an unadapted Value::U64 can never silently
682    /// truncate into a narrower slot.
683    #[inline]
684    pub fn satisfies_slot(&self, slot_type: PortType) -> bool {
685        if matches!(self, Value::None) {
686            return true;
687        }
688        let value_type = self.port_type();
689        if value_type == slot_type {
690            return true;
691        }
692        matches!(
693            (value_type, slot_type),
694            // Bit-stuffed forms: U8/U16/U32 zero-extend into U64
695            // storage, the signed narrow types may still arrive as
696            // U64 storage from a pre-alignment producer, and F32 and
697            // F16 ride their bit patterns in U64 (`Wire for f32` and
698            // `Wire for f16` inject them so).
699            (PortType::U64, PortType::U32 | PortType::I64 | PortType::I32
700                | PortType::U8 | PortType::U16 | PortType::I8 | PortType::I16
701                | PortType::F32 | PortType::F16)
702                | (PortType::F64, PortType::F32 | PortType::F16)
703                // Honest signed carrier: I64 storage serves the
704                // I64 slot and the sign-extended narrow signed
705                // projections.
706                | (PortType::I64, PortType::I32 | PortType::I8 | PortType::I16)
707                // Register views are free bitcasts: a word under
708                // any view satisfies a slot declaring any other
709                // (the consumer's declared lane typing IS the
710                // bitcast).
711                | (
712                    PortType::Reg128 | PortType::RegI8x16 | PortType::RegI16x8
713                        | PortType::RegI32x4 | PortType::RegI64x2
714                        | PortType::RegF16x8 | PortType::RegF32x4 | PortType::RegF64x2,
715                    PortType::Reg128 | PortType::RegI8x16 | PortType::RegI16x8
716                        | PortType::RegI32x4 | PortType::RegI64x2
717                        | PortType::RegF16x8 | PortType::RegF32x4 | PortType::RegF64x2,
718                )
719        )
720    }
721
722    /// Borrow a `VecI32` value as `&[i32]`. Panics on type mismatch.
723    #[inline]
724    pub fn as_vec_i32(&self) -> &[i32] {
725        match self {
726            Value::VecI32(arc) => arc,
727            _ => panic!("expected VecI32, got {:?}", self.port_type()),
728        }
729    }
730
731    /// Borrow a `VecF64` value as `&[f64]`. Panics on type mismatch.
732    #[inline]
733    pub fn as_vec_f64(&self) -> &[f64] {
734        match self {
735            Value::VecF64(arc) => arc,
736            _ => panic!("expected VecF64, got {:?}", self.port_type()),
737        }
738    }
739
740    /// Borrow a `VecI64` value as `&[i64]`. Panics on type mismatch.
741    #[inline]
742    pub fn as_vec_i64(&self) -> &[i64] {
743        match self {
744            Value::VecI64(arc) => arc,
745            _ => panic!("expected VecI64, got {:?}", self.port_type()),
746        }
747    }
748
749    /// Borrow a `VecF16` value as `&[half::f16]`. Panics on type mismatch.
750    #[inline]
751    pub fn as_vec_f16(&self) -> &[half::f16] {
752        match self {
753            Value::VecF16(arc) => arc,
754            _ => panic!("expected VecF16, got {:?}", self.port_type()),
755        }
756    }
757
758    /// Borrow a `VecI16` value as `&[i16]`. Panics on type mismatch.
759    #[inline]
760    pub fn as_vec_i16(&self) -> &[i16] {
761        match self {
762            Value::VecI16(arc) => arc,
763            _ => panic!("expected VecI16, got {:?}", self.port_type()),
764        }
765    }
766
767    /// Borrow a `VecI8` value as `&[i8]`. Panics on type mismatch.
768    #[inline]
769    pub fn as_vec_i8(&self) -> &[i8] {
770        match self {
771            Value::VecI8(arc) => arc,
772            _ => panic!("expected VecI8, got {:?}", self.port_type()),
773        }
774    }
775
776    /// Downcast a Handle value to a borrowed reference of its concrete
777    /// type. Panics if the variant isn't `Handle` or the type doesn't
778    /// match. Used by reader nodes that consume a typed-handle wire
779    /// produced by a resolver node (see SRD 53 §"Dataset Handles").
780    ///
781    /// The borrow lasts as long as `self` (the buffer slot's `Value`
782    /// is what holds the `Arc`). For per-cycle reads this is the
783    /// expected pattern — call methods on the borrowed dataset, then
784    /// return.
785    #[inline]
786    pub fn as_handle<T: std::any::Any + Send + Sync>(&self) -> &T {
787        match self {
788            Value::Handle(arc) => arc.downcast_ref::<T>().unwrap_or_else(|| {
789                panic!(
790                    "Handle downcast failed: expected {}",
791                    std::any::type_name::<T>()
792                )
793            }),
794            _ => panic!("expected Handle, got {:?}", self.port_type()),
795        }
796    }
797
798    /// Construct a `Value::Handle` from a typed `Arc<T>`. Convenience
799    /// wrapper that performs the type-erasure to `Arc<dyn Any + Send + Sync>`.
800    pub fn handle<T: std::any::Any + Send + Sync>(arc: Arc<T>) -> Self {
801        Value::Handle(arc as Arc<dyn std::any::Any + Send + Sync>)
802    }
803
804    /// Best-effort string representation for any value.
805    /// Works across all variants including Ext.
806    pub fn to_display_string(&self) -> String {
807        match self {
808            Value::U64(v) => v.to_string(),
809            Value::I64(v) => v.to_string(),
810            Value::U128(b) => b.as_u128().to_string(),
811            Value::I128(b) => b.as_i128().to_string(),
812            // Lane-typed register views render like the Vec*
813            // display forms; the raw view renders as 32 hex
814            // digits (the full word as buffer state).
815            Value::Reg128(b, view) => match view {
816                RegLanes::Raw => format!("{:032x}", b.as_u128()),
817                RegLanes::I8x16 => format!("{:?}", b.lanes_i8()),
818                RegLanes::I16x8 => format!("{:?}", b.lanes_i16()),
819                RegLanes::I32x4 => format!("{:?}", b.lanes_i32()),
820                RegLanes::I64x2 => format!("{:?}", b.lanes_i64()),
821                RegLanes::F16x8 => format!("{:?}", b.lanes_f16().map(|f| f.to_f32())),
822                RegLanes::F32x4 => format!("{:?}", b.lanes_f32()),
823                RegLanes::F64x2 => format!("{:?}", b.lanes_f64()),
824            },
825            // `{v:?}` (Rust Debug) for f64 always includes at
826            // least one fractional digit, so whole-number floats
827            // render as `1.0` instead of `1` — distinguishing
828            // them from integers in CQL OPTIONS strings, plot
829            // labels, and other surfaces where the type matters.
830            // Display-formatted (`v.to_string()`) strips the
831            // trailing zero, conflating ints with whole-number
832            // floats. Both forms produce identical output for
833            // non-whole floats (`1.5 → "1.5"`).
834            Value::F64(v) => format!("{v:?}"),
835            Value::Bool(v) => v.to_string(),
836            Value::Str(v) => v.to_string(),
837            Value::Bytes(v) => v.iter().map(|b| format!("{b:02x}")).collect(),
838            Value::Json(v) => v.to_string(),
839            Value::Ext(v) => v.display(),
840            Value::Handle(arc) => format!("<handle:{:?}>", arc.type_id()),
841            Value::VecF32(arc) => {
842                // JSON-array text. Per-element format-write into a
843                // pre-sized String avoids the intermediate Vec<String>.
844                // Debug formatter (`{v:?}`) matches the F64 element
845                // rule above: whole-number floats render as `1.0`
846                // so VecF32 stays distinguishable from VecI32 at the
847                // display surface.
848                let mut s = String::with_capacity(arc.len() * 8 + 2);
849                s.push('[');
850                let mut first = true;
851                for v in arc.iter() {
852                    if !first {
853                        s.push(',');
854                    }
855                    first = false;
856                    use std::fmt::Write;
857                    let _ = write!(&mut s, "{v:?}");
858                }
859                s.push(']');
860                s
861            }
862            Value::VecI32(arc) => {
863                let mut s = String::with_capacity(arc.len() * 4 + 2);
864                s.push('[');
865                let mut first = true;
866                for v in arc.iter() {
867                    if !first {
868                        s.push(',');
869                    }
870                    first = false;
871                    use std::fmt::Write;
872                    let _ = write!(&mut s, "{v}");
873                }
874                s.push(']');
875                s
876            }
877            Value::VecF64(arc) => {
878                let mut s = String::with_capacity(arc.len() * 8 + 2);
879                s.push('[');
880                let mut first = true;
881                for v in arc.iter() {
882                    if !first {
883                        s.push(',');
884                    }
885                    first = false;
886                    use std::fmt::Write;
887                    let _ = write!(&mut s, "{v:?}");
888                }
889                s.push(']');
890                s
891            }
892            Value::VecI64(arc) => {
893                let mut s = String::with_capacity(arc.len() * 4 + 2);
894                s.push('[');
895                let mut first = true;
896                for v in arc.iter() {
897                    if !first {
898                        s.push(',');
899                    }
900                    first = false;
901                    use std::fmt::Write;
902                    let _ = write!(&mut s, "{v}");
903                }
904                s.push(']');
905                s
906            }
907            Value::VecF16(arc) => {
908                let mut s = String::with_capacity(arc.len() * 6 + 2);
909                s.push('[');
910                let mut first = true;
911                for v in arc.iter() {
912                    if !first {
913                        s.push(',');
914                    }
915                    first = false;
916                    use std::fmt::Write;
917                    // Render as the f32 widening so the JSON form
918                    // is the standard "1.0" / "1.5" surface — f16
919                    // Display has its own form but it isn't valid
920                    // JSON, so widening makes the array shape
921                    // parseable downstream.
922                    let _ = write!(&mut s, "{:?}", v.to_f32());
923                }
924                s.push(']');
925                s
926            }
927            Value::VecI16(arc) => {
928                let mut s = String::with_capacity(arc.len() * 4 + 2);
929                s.push('[');
930                let mut first = true;
931                for v in arc.iter() {
932                    if !first {
933                        s.push(',');
934                    }
935                    first = false;
936                    use std::fmt::Write;
937                    let _ = write!(&mut s, "{v}");
938                }
939                s.push(']');
940                s
941            }
942            Value::VecI8(arc) => {
943                let mut s = String::with_capacity(arc.len() * 4 + 2);
944                s.push('[');
945                let mut first = true;
946                for v in arc.iter() {
947                    if !first {
948                        s.push(',');
949                    }
950                    first = false;
951                    use std::fmt::Write;
952                    let _ = write!(&mut s, "{v}");
953                }
954                s.push(']');
955                s
956            }
957            Value::None => String::new(),
958        }
959    }
960
961    /// Strict-render variant of [`Self::to_display_string`] for use
962    /// at wire-protocol render sites (op-template substitution,
963    /// adapter byte-emission paths).
964    ///
965    /// Returns `None` for [`Value::None`] instead of converting it
966    /// to `""`. The empty-string mapping in `to_display_string` is
967    /// convenient for diagnostic / log contexts but lethal at the
968    /// wire boundary — it silently coerces "absent" into "present
969    /// but empty," corrupting downstream bytes (e.g. sending
970    /// `'source_model': ''` to a CQL cluster when the intended
971    /// shadow didn't bind). Render paths use this primitive and
972    /// surface a clear error when an unresolved bind-point reaches
973    /// them. See `crates/polydat/docs/design/none_semantics.md`
974    /// (the render-refuses-silent-None rule).
975    pub fn to_display_strict(&self) -> Option<String> {
976        match self {
977            Value::None => None,
978            other => Some(other.to_display_string()),
979        }
980    }
981
982    /// JSON representation for any value. Works across all variants.
983    pub fn to_json_value(&self) -> serde_json::Value {
984        match self {
985            Value::U64(v) => serde_json::Value::from(*v),
986            Value::I64(v) => serde_json::Value::from(*v),
987            // JSON Number is bounded by u64/i64/f64 leaves
988            // (serde_json without arbitrary_precision); 128-bit
989            // magnitudes project as decimal strings, the same
990            // string-convention family as Bytes-as-hex.
991            Value::U128(b) => serde_json::Value::String(b.as_u128().to_string()),
992            Value::I128(b) => serde_json::Value::String(b.as_i128().to_string()),
993            // Lane-typed views project as homogeneous arrays
994            // (same shape as the matching Vec*); the raw view as
995            // a hex string (lane roles are algorithm-defined, so
996            // no numeric reading exists).
997            Value::Reg128(b, view) => match view {
998                RegLanes::Raw => serde_json::Value::String(format!("{:032x}", b.as_u128())),
999                RegLanes::I8x16 => serde_json::Value::Array(
1000                    b.lanes_i8()
1001                        .iter()
1002                        .map(|i| serde_json::Value::from(*i as i32))
1003                        .collect(),
1004                ),
1005                RegLanes::I16x8 => serde_json::Value::Array(
1006                    b.lanes_i16()
1007                        .iter()
1008                        .map(|i| serde_json::Value::from(*i as i32))
1009                        .collect(),
1010                ),
1011                RegLanes::I32x4 => serde_json::Value::Array(
1012                    b.lanes_i32()
1013                        .iter()
1014                        .map(|i| serde_json::Value::from(*i))
1015                        .collect(),
1016                ),
1017                RegLanes::I64x2 => serde_json::Value::Array(
1018                    b.lanes_i64()
1019                        .iter()
1020                        .map(|i| serde_json::Value::from(*i))
1021                        .collect(),
1022                ),
1023                RegLanes::F16x8 => serde_json::Value::Array(
1024                    b.lanes_f16()
1025                        .iter()
1026                        .map(|f| serde_json::json!(f.to_f32()))
1027                        .collect(),
1028                ),
1029                RegLanes::F32x4 => serde_json::Value::Array(
1030                    b.lanes_f32()
1031                        .iter()
1032                        .map(|f| serde_json::json!(*f))
1033                        .collect(),
1034                ),
1035                RegLanes::F64x2 => serde_json::Value::Array(
1036                    b.lanes_f64()
1037                        .iter()
1038                        .map(|f| serde_json::json!(*f))
1039                        .collect(),
1040                ),
1041            },
1042            Value::F64(v) => serde_json::json!(*v),
1043            Value::Bool(v) => serde_json::Value::from(*v),
1044            Value::Str(v) => serde_json::Value::from(&**v),
1045            Value::Bytes(v) => {
1046                serde_json::Value::from(v.iter().map(|b| format!("{b:02x}")).collect::<String>())
1047            }
1048            Value::Json(v) => (**v).clone(),
1049            Value::Ext(v) => v.to_json_value(),
1050            Value::Handle(_) => serde_json::Value::Null,
1051            Value::VecF32(arc) => {
1052                serde_json::Value::Array(arc.iter().map(|f| serde_json::json!(*f)).collect())
1053            }
1054            Value::VecI32(arc) => {
1055                serde_json::Value::Array(arc.iter().map(|i| serde_json::Value::from(*i)).collect())
1056            }
1057            Value::VecF64(arc) => {
1058                serde_json::Value::Array(arc.iter().map(|f| serde_json::json!(*f)).collect())
1059            }
1060            Value::VecI64(arc) => {
1061                serde_json::Value::Array(arc.iter().map(|i| serde_json::Value::from(*i)).collect())
1062            }
1063            Value::VecF16(arc) => serde_json::Value::Array(
1064                arc.iter().map(|f| serde_json::json!(f.to_f32())).collect(),
1065            ),
1066            Value::VecI16(arc) => serde_json::Value::Array(
1067                arc.iter()
1068                    .map(|i| serde_json::Value::from(*i as i32))
1069                    .collect(),
1070            ),
1071            Value::VecI8(arc) => serde_json::Value::Array(
1072                arc.iter()
1073                    .map(|i| serde_json::Value::from(*i as i32))
1074                    .collect(),
1075            ),
1076            Value::None => serde_json::Value::Null,
1077        }
1078    }
1079}
1080
1081pub use polydat_grammar::PortType;
1082
1083/// What a port type means to a compiled buffer: its slot color, the
1084/// width that follows from it, and the scratch element a by-reference
1085/// producer owns. The type itself is the grammar's
1086/// (`polydat_grammar::PortType`); these are the runtime's reading of
1087/// it, and every layout, codegen, and guard decision derives from
1088/// them.
1089pub trait SlotShape {
1090    /// Slot color in compiled (P2/P3/hybrid) kernel buffers —
1091    /// axiom S1 (`jit_boundary.md` §"Slot-state axioms"). The
1092    /// single chokepoint: width and every layout/codegen/guard
1093    /// decision derive from this, never restate it.
1094    fn slot_color(&self) -> SlotColor;
1095    /// The scratch element a `Ref2`-colored port's producer owns
1096    /// (axiom S3); `None` for an immediate color.
1097    fn scratch_elem(&self) -> Option<ScratchElem>;
1098    /// Buffer slots this type occupies — derived from
1099    /// [`Self::slot_color`] per axiom S1.
1100    fn slot_width(&self) -> usize;
1101}
1102
1103impl SlotShape for PortType {
1104    #[inline]
1105    fn slot_color(&self) -> SlotColor {
1106        match self {
1107            // 128-bit immediates: two slots of limb DATA —
1108            // register words and 128-bit integers are values,
1109            // never addresses.
1110            Self::U128
1111            | Self::I128
1112            | Self::Reg128
1113            | Self::RegI8x16
1114            | Self::RegI16x8
1115            | Self::RegI32x4
1116            | Self::RegI64x2
1117            | Self::RegF16x8
1118            | Self::RegF32x4
1119            | Self::RegF64x2 => SlotColor::Imm2,
1120            // Heap slices: a (ptr, len) reference pair viewing
1121            // kernel-owned scratch (§8.4 layer 3). A string and a
1122            // byte string are slices of bytes; a JSON, extension, or
1123            // handle value is a one-element slice holding the value.
1124            Self::VecF32
1125            | Self::VecI32
1126            | Self::VecF64
1127            | Self::VecI64
1128            | Self::VecF16
1129            | Self::VecI16
1130            | Self::VecI8
1131            | Self::Str
1132            | Self::Bytes
1133            | Self::Json
1134            | Self::Ext
1135            | Self::Handle => SlotColor::Ref2,
1136            // Everything else (incl. all narrow widths riding
1137            // their 64-bit carriers): one slot of immediate data.
1138            _ => SlotColor::Imm1,
1139        }
1140    }
1141
1142    #[inline]
1143    fn scratch_elem(&self) -> Option<ScratchElem> {
1144        Some(match self {
1145            Self::VecF32 => ScratchElem::F32,
1146            Self::VecF64 => ScratchElem::F64,
1147            Self::VecF16 => ScratchElem::F16,
1148            Self::VecI8 => ScratchElem::I8,
1149            Self::VecI16 => ScratchElem::I16,
1150            Self::VecI32 => ScratchElem::I32,
1151            Self::VecI64 => ScratchElem::I64,
1152            Self::Str => ScratchElem::Str,
1153            Self::Bytes => ScratchElem::Bytes,
1154            Self::Json | Self::Ext | Self::Handle => ScratchElem::Value,
1155            _ => return None,
1156        })
1157    }
1158
1159    #[inline]
1160    fn slot_width(&self) -> usize {
1161        match self.slot_color() {
1162            SlotColor::Imm1 => 1,
1163            SlotColor::Imm2 | SlotColor::Ref2 => 2,
1164        }
1165    }
1166}
1167
1168/// The lifecycle of a port's value.
1169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1170pub enum Lifecycle {
1171    /// Cycle-time: value changes per evaluation.
1172    Cycle,
1173    /// Init-time: value is frozen at assembly, immutable at runtime.
1174    /// Wiring a cycle-time value to an init port is an assembly error.
1175    Init,
1176}
1177
1178/// Cost class for an input wire, indicating how expensive it is
1179/// to change the value on this port.
1180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1181pub enum WireCost {
1182    /// Data wire: cheap per-cycle input. The node's primary
1183    /// computation path. Default for most ports.
1184    #[default]
1185    Data,
1186    /// Config wire: changing this input invalidates expensive
1187    /// internal state (LUT, distribution table). Expected to be
1188    /// wired to init-time constants or rarely-changing values.
1189    /// The compiler warns when a config wire connects to a
1190    /// cycle-time binding.
1191    Config,
1192}
1193
1194/// Descriptor for a single input or output port on a node.
1195#[derive(Debug, Clone)]
1196pub struct Port {
1197    /// The port's name, as bindings and diagnostics refer to it.
1198    pub name: String,
1199    /// The port's declared type.
1200    pub typ: PortType,
1201    /// When the port's value changes: per cycle, at init, or as configuration.
1202    pub lifecycle: Lifecycle,
1203    /// Cost class for input ports. Ignored for output ports.
1204    pub wire_cost: WireCost,
1205    /// Optional value contract this wire must satisfy at runtime
1206    /// (SRD 15 §"Strict Wire Mode"). The compiler uses this to
1207    /// decide whether to auto-insert a value assertion when the
1208    /// upstream source can't statically be proven to deliver a
1209    /// satisfying value. `None` = no constraint declared.
1210    ///
1211    /// Constraints reuse the same vocabulary as
1212    /// [`crate::dsl::const_constraints::ConstConstraint`] — the
1213    /// difference is just where the value comes from (a literal
1214    /// for `ConstU64`, a wire for `Slot::Wire`).
1215    pub constraint: Option<crate::dsl::const_constraints::ConstConstraint>,
1216}
1217
1218impl Port {
1219    /// A cycle-lifecycle port of the given type with no constraint.
1220    pub fn new(name: impl Into<String>, typ: PortType) -> Self {
1221        Self {
1222            name: name.into(),
1223            typ,
1224            lifecycle: Lifecycle::Cycle,
1225            wire_cost: WireCost::Data,
1226            constraint: None,
1227        }
1228    }
1229
1230    /// Create a port with explicit lifecycle.
1231    pub fn with_lifecycle(name: impl Into<String>, typ: PortType, lifecycle: Lifecycle) -> Self {
1232        Self {
1233            name: name.into(),
1234            typ,
1235            lifecycle,
1236            wire_cost: WireCost::Data,
1237            constraint: None,
1238        }
1239    }
1240
1241    /// A `u64` port.
1242    pub fn u64(name: impl Into<String>) -> Self {
1243        Self::new(name, PortType::U64)
1244    }
1245
1246    /// An `f64` port.
1247    pub fn f64(name: impl Into<String>) -> Self {
1248        Self::new(name, PortType::F64)
1249    }
1250
1251    /// A string port.
1252    pub fn str(name: impl Into<String>) -> Self {
1253        Self::new(name, PortType::Str)
1254    }
1255
1256    /// A boolean port.
1257    pub fn bool(name: impl Into<String>) -> Self {
1258        Self::new(name, PortType::Bool)
1259    }
1260
1261    /// A JSON port.
1262    pub fn json(name: impl Into<String>) -> Self {
1263        Self::new(name, PortType::Json)
1264    }
1265
1266    /// A handle port.
1267    pub fn handle(name: impl Into<String>) -> Self {
1268        Self::new(name, PortType::Handle)
1269    }
1270
1271    /// An `f32` vector port.
1272    pub fn vec_f32(name: impl Into<String>) -> Self {
1273        Self::new(name, PortType::VecF32)
1274    }
1275
1276    /// An `i32` vector port.
1277    pub fn vec_i32(name: impl Into<String>) -> Self {
1278        Self::new(name, PortType::VecI32)
1279    }
1280
1281    /// Create an init-time port (frozen at assembly).
1282    pub fn init(name: impl Into<String>, typ: PortType) -> Self {
1283        Self::with_lifecycle(name, typ, Lifecycle::Init)
1284    }
1285
1286    /// Attach a value constraint. Used by node authors that want
1287    /// to declare "this wire must satisfy X" so strict-wire-mode
1288    /// can auto-insert the right value assertion. See SRD 15
1289    /// §"Strict Wire Mode".
1290    pub fn with_constraint(mut self, c: crate::dsl::const_constraints::ConstConstraint) -> Self {
1291        self.constraint = Some(c);
1292        self
1293    }
1294
1295    /// Mark this port as a config wire (expensive to change).
1296    pub fn config(mut self) -> Self {
1297        self.wire_cost = WireCost::Config;
1298        self
1299    }
1300
1301    /// Set the wire cost directly. Used by the macro to thread
1302    /// `Wire::WIRE_COST` from the trait through to the slot.
1303    pub fn with_cost(mut self, cost: WireCost) -> Self {
1304        self.wire_cost = cost;
1305        self
1306    }
1307}
1308
1309// ---------------------------------------------------------------------------
1310// Unified slot model (SRD 36 §Variadic)
1311// ---------------------------------------------------------------------------
1312
1313/// The type discriminant for a slot: wire or typed constant.
1314///
1315/// This is the shared vocabulary between `FuncSig` (static registry)
1316/// and `NodeMeta` (owned instance). It replaces the former `ParamKind`,
1317/// `ConstType`, and `SlotKind` enums with a single type.
1318#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1319pub enum SlotType {
1320    /// A runtime wire input carrying a value each cycle.
1321    Wire,
1322    /// A u64 constant literal.
1323    ConstU64,
1324    /// An f64 constant literal.
1325    ConstF64,
1326    /// A string constant literal.
1327    ConstStr,
1328    /// A `Vec<u64>` constant (from array literal).
1329    ConstVecU64,
1330    /// A `Vec<f64>` constant (from array literal).
1331    ConstVecF64,
1332    /// SRD-80b Phase C — typed-element variadic-const slot for
1333    /// `Const<Vec<C>>` operator-side shape. Element type
1334    /// discrimination rides through the `<C as ConstSource>::extract`
1335    /// trait dispatch at the build-closure call site; the slot tag
1336    /// only signals "this is a list" to the DSL type-checker.
1337    ConstVec,
1338}
1339
1340impl SlotType {
1341    /// Whether this is a constant (not a wire).
1342    pub fn is_const(self) -> bool {
1343        !matches!(self, SlotType::Wire)
1344    }
1345
1346    /// Whether this is a wire (not a constant).
1347    pub fn is_wire(self) -> bool {
1348        matches!(self, SlotType::Wire)
1349    }
1350}
1351
1352/// JIT-compatible primitive carriers.
1353///
1354/// The carriers that ride compiled slot buffers: the 64-bit scalars
1355/// (`u64` as-is, `i64` and `f64` as their bits, `bool` as 0/1), the
1356/// narrow integers and floats zero/sign-extended or as bits, and the
1357/// 128-bit words in two slots. The 64-bit core is the CL ∩ JSON
1358/// scalar set from `polydat/docs/design/type_system_alignment.md` §4.
1359///
1360/// Referenced by `polydat::derive_support::Wire::JIT` to tag each
1361/// Wire-typed Rust value with its JIT carrier (or `None`).
1362#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1363pub enum JitType {
1364    /// An unsigned 64-bit carrier.
1365    U64,
1366    /// A signed 64-bit carrier.
1367    I64,
1368    /// An `f64` carrier, as its bits.
1369    F64,
1370    /// A boolean carrier, 0 or 1.
1371    Bool,
1372    /// A `u8` carrier, zero-extended.
1373    U8,
1374    /// A `u16` carrier, zero-extended.
1375    U16,
1376    /// A `u32` carrier, zero-extended.
1377    U32,
1378    /// An `i8` carrier, sign-extended.
1379    I8,
1380    /// An `i16` carrier, sign-extended.
1381    I16,
1382    /// An `i32` carrier, sign-extended.
1383    I32,
1384    /// An `f32` carrier, as its bits.
1385    F32,
1386    /// An `f16` carrier, as its bits.
1387    F16,
1388    /// A `u128`, in two slots.
1389    U128,
1390    /// An `i128`, in two slots.
1391    I128,
1392    /// A 128-bit register word, in two slots.
1393    Reg128,
1394}
1395
1396/// A concrete constant value stored in node metadata.
1397///
1398/// Assembly-time values baked into the node at construction. The
1399/// variant determines the `SlotType` — no separate type discriminant
1400/// is needed.
1401#[derive(Debug, Clone, PartialEq)]
1402pub enum ConstValue {
1403    /// An unsigned integer.
1404    U64(u64),
1405    /// A floating-point number.
1406    F64(f64),
1407    /// A string.
1408    Str(String),
1409    /// A list of unsigned integers.
1410    VecU64(Vec<u64>),
1411    /// A list of floating-point numbers.
1412    VecF64(Vec<f64>),
1413}
1414
1415impl ConstValue {
1416    /// Return the `SlotType` for this value.
1417    pub fn slot_type(&self) -> SlotType {
1418        match self {
1419            ConstValue::U64(_) => SlotType::ConstU64,
1420            ConstValue::F64(_) => SlotType::ConstF64,
1421            ConstValue::Str(_) => SlotType::ConstStr,
1422            ConstValue::VecU64(_) => SlotType::ConstVecU64,
1423            ConstValue::VecF64(_) => SlotType::ConstVecF64,
1424        }
1425    }
1426
1427    /// Encode to the JIT's u64 representation.
1428    pub fn to_jit_u64s(&self) -> Vec<u64> {
1429        match self {
1430            ConstValue::U64(v) => vec![*v],
1431            ConstValue::F64(v) => vec![v.to_bits()],
1432            ConstValue::Str(_) => vec![],
1433            ConstValue::VecU64(v) => v.clone(),
1434            ConstValue::VecF64(v) => v.iter().map(|f| f.to_bits()).collect(),
1435        }
1436    }
1437}
1438
1439/// A single logical input to a node: either a runtime wire or an
1440/// assembly-time constant. The positional order in `NodeMeta.slots`
1441/// matches the function call syntax in the DSL.
1442#[derive(Debug, Clone)]
1443pub enum Slot {
1444    /// A runtime wire input carrying a value each cycle.
1445    Wire(Port),
1446    /// An assembly-time constant, baked into the node at construction.
1447    Const {
1448        /// The constant's name, as the node's signature calls it.
1449        name: String,
1450        /// The baked value.
1451        value: ConstValue,
1452    },
1453}
1454
1455impl Slot {
1456    /// Return the `SlotType` discriminant for this slot.
1457    pub fn slot_type(&self) -> SlotType {
1458        match self {
1459            Slot::Wire(_) => SlotType::Wire,
1460            Slot::Const { value, .. } => value.slot_type(),
1461        }
1462    }
1463
1464    /// Create a wire slot.
1465    pub fn wire(port: Port) -> Self {
1466        Slot::Wire(port)
1467    }
1468
1469    /// Create a u64 constant slot.
1470    pub fn const_u64(name: impl Into<String>, v: u64) -> Self {
1471        Slot::Const {
1472            name: name.into(),
1473            value: ConstValue::U64(v),
1474        }
1475    }
1476
1477    /// Create an f64 constant slot.
1478    pub fn const_f64(name: impl Into<String>, v: f64) -> Self {
1479        Slot::Const {
1480            name: name.into(),
1481            value: ConstValue::F64(v),
1482        }
1483    }
1484
1485    /// Create a string constant slot.
1486    pub fn const_str(name: impl Into<String>, v: impl Into<String>) -> Self {
1487        Slot::Const {
1488            name: name.into(),
1489            value: ConstValue::Str(v.into()),
1490        }
1491    }
1492
1493    /// Create a `Vec<u64>` constant slot.
1494    pub fn const_vec_u64(name: impl Into<String>, v: Vec<u64>) -> Self {
1495        Slot::Const {
1496            name: name.into(),
1497            value: ConstValue::VecU64(v),
1498        }
1499    }
1500
1501    /// Create a `Vec<f64>` constant slot.
1502    pub fn const_vec_f64(name: impl Into<String>, v: Vec<f64>) -> Self {
1503        Slot::Const {
1504            name: name.into(),
1505            value: ConstValue::VecF64(v),
1506        }
1507    }
1508}
1509
1510/// Declares which inputs of a node are interchangeable.
1511///
1512/// Used by the fusion pattern matcher to recognize equivalent
1513/// subgraphs regardless of operand order, and by future passes
1514/// (e.g., canonical ordering, common subexpression elimination).
1515#[derive(Debug, Clone, PartialEq, Eq, Default)]
1516pub enum Commutativity {
1517    /// Input order matters. No permutations attempted during
1518    /// pattern matching. This is the default for unary nodes and
1519    /// any node where operand order affects the result.
1520    ///
1521    /// Examples: `mod(dividend, divisor)`, `div(x, K)`,
1522    /// `concat(left, right)`, `sub(a, b)`.
1523    #[default]
1524    Positional,
1525
1526    /// All inputs are interchangeable, including variadic.
1527    /// For small arity (2-3), the matcher tries all permutations.
1528    /// For larger arity, it uses set-matching.
1529    ///
1530    /// Examples: `sum(a, b, ..., n)`, `product(a, b, ..., n)`,
1531    /// `min(a, b, ..., n)`, `max(a, b, ..., n)`.
1532    AllCommutative,
1533
1534    /// Specific groups of input port indices are interchangeable
1535    /// within each group. Inputs not listed in any group are
1536    /// positional.
1537    ///
1538    /// Example: `fma(x, y, z) = x + y * z`
1539    /// The multiplicands `y` (index 1) and `z` (index 2) commute,
1540    /// but the addend `x` (index 0) does not.
1541    /// `Groups(vec![vec![1, 2]])`
1542    Groups(Vec<Vec<usize>>),
1543}
1544
1545/// Metadata describing a node's interface: its input slots and output ports.
1546///
1547/// Generated per-node-type and queryable at runtime for assembly-time
1548/// validation, compilation, optimization passes, and describe output.
1549///
1550/// Wire inputs are `Slot::Wire(Port)`. Constants are `Slot::Const { name, value }`.
1551/// Use `wire_inputs()` to extract just the wire ports.
1552#[derive(Debug, Clone)]
1553pub struct NodeMeta {
1554    /// The node's function name, as programs call it.
1555    pub name: String,
1556    /// All inputs in positional order: wires and constants.
1557    pub ins: Vec<Slot>,
1558    /// The output ports, in positional order.
1559    pub outs: Vec<Port>,
1560}
1561
1562impl NodeMeta {
1563    /// Wire-only input ports extracted from `ins`.
1564    pub fn wire_inputs(&self) -> Vec<&Port> {
1565        self.ins
1566            .iter()
1567            .filter_map(|s| match s {
1568                Slot::Wire(p) => Some(p),
1569                Slot::Const { .. } => None,
1570            })
1571            .collect()
1572    }
1573
1574    /// Constant names and values extracted from `ins`.
1575    pub fn const_slots(&self) -> Vec<(&str, &ConstValue)> {
1576        self.ins
1577            .iter()
1578            .filter_map(|s| match s {
1579                Slot::Const { name, value } => Some((name.as_str(), value)),
1580                Slot::Wire(_) => None,
1581            })
1582            .collect()
1583    }
1584
1585    /// Encode all constants from `ins` to JIT u64 representation.
1586    pub fn jit_constants_from_slots(&self) -> Vec<u64> {
1587        self.const_slots()
1588            .iter()
1589            .flat_map(|(_, v)| v.to_jit_u64s())
1590            .collect()
1591    }
1592}
1593
1594/// A compiled u64-only evaluation step.
1595///
1596/// The closure captures all assembly-time parameters. At runtime it
1597/// reads from input slots and writes to output slots in a flat `[u64]`
1598/// buffer — no `Value` enum, no virtual dispatch.
1599pub type CompiledU64Op = Box<dyn Fn(&[u64], &mut [u64]) + Send + Sync>;
1600
1601/// Element type of one kernel-owned scratch buffer
1602/// (type_system_alignment.md §8.4 layer 3). One entry per
1603/// `Ref2`-colored output port of a slot-compiled node: a typed
1604/// vector, a string, a byte string, or a value held by reference.
1605#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1606pub enum ScratchElem {
1607    /// `f32` elements.
1608    F32,
1609    /// `f64` elements.
1610    F64,
1611    /// `f16` elements.
1612    F16,
1613    /// `i8` elements.
1614    I8,
1615    /// `i16` elements.
1616    I16,
1617    /// `i32` elements.
1618    I32,
1619    /// `i64` elements.
1620    I64,
1621    /// The UTF-8 bytes of a string.
1622    Str,
1623    /// The bytes of a byte string.
1624    Bytes,
1625    /// One value held by reference (`Json`, `Ext`, `Handle`): the
1626    /// pair is `(&Value, 1)`.
1627    Value,
1628    /// A buffer of 64-bit slots: a native cone's own slot buffer,
1629    /// owned by the state that evaluates it.
1630    Slots,
1631    /// The kernels a tile render keeps over its projection bodies,
1632    /// owned by the state that renders.
1633    Kernels,
1634    /// State a node defines for itself per evaluating kernel state, a
1635    /// memo of what it last derived from its inputs, created by the
1636    /// node on first use; a clone starts empty.
1637    State,
1638}
1639
1640/// Node-defined state held by a kernel state (`ScratchElem::State`):
1641/// what a node keeps between its evaluations in one state, typed by
1642/// the node and never shared between states. Empty until the node
1643/// first fills it; a clone is empty, since a clone of a state is a
1644/// new state (compiled_handles.md §3).
1645#[derive(Default)]
1646pub struct NodeState(Option<Box<dyn std::any::Any + Send + Sync>>);
1647
1648impl NodeState {
1649    /// The state as `T`, created by `init` when the entry is empty or
1650    /// holds another type.
1651    pub fn get_or_insert_with<T: std::any::Any + Send + Sync>(
1652        &mut self,
1653        init: impl FnOnce() -> T,
1654    ) -> &mut T {
1655        if !self.0.as_ref().is_some_and(|b| b.is::<T>()) {
1656            self.0 = Some(Box::new(init()));
1657        }
1658        self.0
1659            .as_mut()
1660            .and_then(|b| b.downcast_mut::<T>())
1661            .expect("the entry holds a T")
1662    }
1663
1664    /// The state as `T`, if the node has filled it with one.
1665    pub fn get<T: std::any::Any + Send + Sync>(&self) -> Option<&T> {
1666        self.0.as_ref().and_then(|b| b.downcast_ref::<T>())
1667    }
1668}
1669
1670impl Clone for NodeState {
1671    fn clone(&self) -> Self {
1672        NodeState(None)
1673    }
1674}
1675
1676impl std::fmt::Debug for NodeState {
1677    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1678        write!(
1679            f,
1680            "NodeState({})",
1681            if self.0.is_some() { "filled" } else { "empty" }
1682        )
1683    }
1684}
1685
1686/// Slot color of a `PortType` in compiled kernel buffers —
1687/// axiom S1: static, total, three-valued. `Imm*` slots carry
1688/// immediate data only (never addresses); `Ref2` pairs carry a
1689/// `(ptr, len)` reference to storage with a proven owner: the
1690/// step's own scratch, an extern's stored value, an interned
1691/// constant, or a boundary value alive for the call. They are
1692/// engine-internal per axiom S2.
1693#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1694pub enum SlotColor {
1695    /// One slot of immediate data.
1696    Imm1,
1697    /// Two slots of immediate limb data (128-bit values).
1698    Imm2,
1699    /// Two slots holding a (ptr, len) reference pair.
1700    Ref2,
1701}
1702
1703/// One kernel-owned scratch buffer. A `Ref2` output port's
1704/// `(ptr, len)` buffer slots view its scratch — the kernel owns
1705/// the allocation, so the pointer is valid exactly as long as the
1706/// producing step doesn't rerun (and a rerun rewrites the slots
1707/// before any consumer reads them). No Arc traffic, no allocation
1708/// after warmup: a string or byte string is rewritten in place, a
1709/// value is replaced.
1710#[derive(Debug, Clone)]
1711pub enum ScratchBuf {
1712    /// An `f32` buffer.
1713    F32(Vec<f32>),
1714    /// An `f64` buffer.
1715    F64(Vec<f64>),
1716    /// An `f16` buffer.
1717    F16(Vec<half::f16>),
1718    /// An `i8` buffer.
1719    I8(Vec<i8>),
1720    /// An `i16` buffer.
1721    I16(Vec<i16>),
1722    /// An `i32` buffer.
1723    I32(Vec<i32>),
1724    /// An `i64` buffer.
1725    I64(Vec<i64>),
1726    /// The UTF-8 bytes of a string.
1727    Str(Vec<u8>),
1728    /// The bytes of a byte string.
1729    Bytes(Vec<u8>),
1730    /// One value held by reference; empty until the step first runs.
1731    Value(Vec<Value>),
1732    /// A buffer of 64-bit slots (a native cone's own).
1733    Slots(Vec<u64>),
1734    /// The kernels a tile render keeps over its projection bodies. A
1735    /// clone is empty: a new state builds its own.
1736    Kernels(crate::library::tile_render::BodyKernels),
1737    /// State a node defines for itself, per kernel state. A clone is
1738    /// empty: a new state derives its own.
1739    State(NodeState),
1740}
1741
1742impl ScratchBuf {
1743    /// The `(ptr, len)` pair this entry currently publishes —
1744    /// the ground truth axiom S9(a)'s validator compares buffer
1745    /// slots against.
1746    pub fn ptr_len(&self) -> (u64, u64) {
1747        match self {
1748            ScratchBuf::F32(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1749            ScratchBuf::F64(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1750            ScratchBuf::F16(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1751            ScratchBuf::I8(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1752            ScratchBuf::I16(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1753            ScratchBuf::I32(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1754            ScratchBuf::I64(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1755            ScratchBuf::Str(v) | ScratchBuf::Bytes(v) => {
1756                (v.as_ptr() as usize as u64, v.len() as u64)
1757            }
1758            ScratchBuf::Value(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1759            ScratchBuf::Slots(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1760            ScratchBuf::Kernels(_) | ScratchBuf::State(_) => (0, 0),
1761        }
1762    }
1763
1764    /// What this entry holds as an owned `Value`, copied out: the
1765    /// typed read of a `Ref2` output on a compiled kernel, which is
1766    /// what the interpreter's `pull` returns for the same port. A
1767    /// value entry that has not been written reads as `None`.
1768    pub fn to_value(&self) -> Value {
1769        match self {
1770            ScratchBuf::F32(v) => Value::VecF32(SliceArc::from_vec(v.clone())),
1771            ScratchBuf::F64(v) => Value::VecF64(SliceArc::from_vec(v.clone())),
1772            ScratchBuf::F16(v) => Value::VecF16(SliceArc::from_vec(v.clone())),
1773            ScratchBuf::I8(v) => Value::VecI8(SliceArc::from_vec(v.clone())),
1774            ScratchBuf::I16(v) => Value::VecI16(SliceArc::from_vec(v.clone())),
1775            ScratchBuf::I32(v) => Value::VecI32(SliceArc::from_vec(v.clone())),
1776            ScratchBuf::I64(v) => Value::VecI64(SliceArc::from_vec(v.clone())),
1777            // SAFETY: a `Str` entry is written only from `&str` bytes.
1778            ScratchBuf::Str(v) => {
1779                Value::Str(Arc::from(unsafe { std::str::from_utf8_unchecked(v) }))
1780            }
1781            ScratchBuf::Bytes(v) => Value::Bytes(Arc::from(&v[..])),
1782            ScratchBuf::Value(v) => v.first().cloned().unwrap_or(Value::None),
1783            ScratchBuf::Slots(_) => panic!("a slot buffer is not a value"),
1784            ScratchBuf::Kernels(_) => panic!("a body kernel set is not a value"),
1785            ScratchBuf::State(_) => panic!("a node's own state is not a value"),
1786        }
1787    }
1788
1789    /// The node-defined state this entry holds. The entry must be a
1790    /// `State` entry.
1791    pub fn node_state(&mut self) -> &mut NodeState {
1792        match self {
1793            ScratchBuf::State(s) => s,
1794            other => panic!("scratch entry holds {other:?}, not a node's state"),
1795        }
1796    }
1797
1798    /// Replace the string this entry holds, reusing its allocation.
1799    /// The entry must be a `Str` entry.
1800    #[inline]
1801    pub fn set_str(&mut self, s: &str) {
1802        match self {
1803            ScratchBuf::Str(v) => {
1804                v.clear();
1805                v.extend_from_slice(s.as_bytes());
1806            }
1807            other => panic!("scratch entry holds {other:?}, not a string"),
1808        }
1809    }
1810
1811    /// Replace the byte string this entry holds, reusing its
1812    /// allocation. The entry must be a `Bytes` entry.
1813    #[inline]
1814    pub fn set_bytes(&mut self, b: &[u8]) {
1815        match self {
1816            ScratchBuf::Bytes(v) => {
1817                v.clear();
1818                v.extend_from_slice(b);
1819            }
1820            other => panic!("scratch entry holds {other:?}, not a byte string"),
1821        }
1822    }
1823
1824    /// Replace the value this entry holds. The entry must be a
1825    /// `Value` entry.
1826    #[inline]
1827    pub fn set_value(&mut self, value: Value) {
1828        match self {
1829            ScratchBuf::Value(v) => {
1830                v.clear();
1831                v.push(value);
1832            }
1833            other => panic!("scratch entry holds {other:?}, not a value"),
1834        }
1835    }
1836
1837    /// An empty buffer of the element type.
1838    pub fn new(elem: ScratchElem) -> Self {
1839        match elem {
1840            ScratchElem::F32 => ScratchBuf::F32(Vec::new()),
1841            ScratchElem::F64 => ScratchBuf::F64(Vec::new()),
1842            ScratchElem::F16 => ScratchBuf::F16(Vec::new()),
1843            ScratchElem::I8 => ScratchBuf::I8(Vec::new()),
1844            ScratchElem::I16 => ScratchBuf::I16(Vec::new()),
1845            ScratchElem::I32 => ScratchBuf::I32(Vec::new()),
1846            ScratchElem::I64 => ScratchBuf::I64(Vec::new()),
1847            ScratchElem::Str => ScratchBuf::Str(Vec::new()),
1848            ScratchElem::Bytes => ScratchBuf::Bytes(Vec::new()),
1849            ScratchElem::Value => ScratchBuf::Value(Vec::new()),
1850            ScratchElem::Slots => ScratchBuf::Slots(Vec::new()),
1851            ScratchElem::Kernels => ScratchBuf::Kernels(Default::default()),
1852            ScratchElem::State => ScratchBuf::State(NodeState::default()),
1853        }
1854    }
1855}
1856
1857/// Compiled closure for a node with typed-slice ports (§8.4
1858/// layer 3). Same calling shape as [`CompiledU64Op`] plus the
1859/// step's scratch buffers: slice inputs arrive as `(ptr, len)`
1860/// slot pairs in `inputs`; vector outputs are written into
1861/// scratch and their `(ptr, len)` into `outputs`.
1862pub type CompiledSlotOp = Box<dyn Fn(&[u64], &mut [u64], &mut [ScratchBuf]) + Send + Sync>;
1863
1864/// A slot-compiled node's closure plus its scratch declaration
1865/// (one [`ScratchElem`] per vector-producing output, in port
1866/// order). Returned by [`PolydatNode::compiled_slot`].
1867pub struct CompiledSlotKit {
1868    /// The closure: slice inputs as slot pairs, vector outputs into scratch.
1869    pub op: CompiledSlotOp,
1870    /// One element type per vector-producing output, in port order.
1871    pub scratch: Vec<ScratchElem>,
1872}
1873
1874/// Per-node purity classification per
1875/// [`runtime_model.md`'s D2 axiom][spec] and
1876/// [`composition_substrate.md`'s T1+T2 axioms][substrate].
1877///
1878/// Every node declares its purity status via
1879/// [`PolydatNode::purity`]. The default is [`Purity::Pure`]; nodes
1880/// with observable side channels (logging, file I/O, network)
1881/// or eval-call-spanning state override to declare
1882/// [`Purity::SideChannel`] or [`Purity::Nondeterministic`].
1883///
1884/// **D1 (Typed Return Determinism) holds for every purity
1885/// class.** The slot contract carries only typed return
1886/// values; impure nodes still produce typed-deterministic
1887/// returns. What varies between purity classes is the
1888/// *observable side channels* (D2): pure nodes have none;
1889/// SideChannel nodes have declared side channels; Stateful
1890/// nodes additionally have internal eval-call-spanning state
1891/// that affects future evaluations.
1892///
1893/// [spec]: https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/runtime_model.md
1894/// [substrate]: https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/composition_substrate.md
1895#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1896pub enum Purity {
1897    /// Pure function — `eval(inputs)` is a function of inputs,
1898    /// no observable side effects, byte-identical determinism
1899    /// across calls with identical inputs.
1900    Pure,
1901
1902    /// Has an observable side channel (logging, file I/O,
1903    /// network, etc.) but the typed return value is still a
1904    /// function of inputs. Hosts that care about side-channel
1905    /// observability examine the `sink` to know what
1906    /// observable surface this node writes to.
1907    SideChannel {
1908        /// The observable surface the node writes to.
1909        sink: SideChannelSink,
1910    },
1911
1912    /// The typed return value is not a function of declared
1913    /// inputs alone — it depends on external sources (system
1914    /// clock, entropy, thread identity, environment) or on
1915    /// eval-call-spanning internal state mutated by prior calls.
1916    /// In either case, the runtime's `node_clean` caching model
1917    /// must opt the node out of within-cycle memoization
1918    /// suppression; the assembler's lifecycle classes mark the node
1919    /// as nondeterministic (`PolydatProgram::nondeterministic`).
1920    /// The `reason` string documents the source of
1921    /// non-determinism (e.g., "reads system clock",
1922    /// "monotonic counter incremented per call",
1923    /// "accumulates signal buffer across calls").
1924    ///
1925    /// This is the intrinsic-volatility marker referenced by
1926    /// runtime_model.md R1.v: certain library nodes declare
1927    /// themselves volatile via this variant; no user opt-in is
1928    /// required, and the workload author cannot remove the
1929    /// marker. User-opt-in volatility via the `volatile`
1930    /// modifier is a separate surface that produces the same
1931    /// runtime effect (see R1.v).
1932    Nondeterministic {
1933        /// The source of the non-determinism, for diagnostics.
1934        reason: &'static str,
1935    },
1936}
1937
1938/// Where a [`Purity::SideChannel`] node writes its observable
1939/// side effects. Hosts reasoning about side-channel
1940/// determinism (D2) pattern-match on this to know what
1941/// observable surface to expect.
1942#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1943pub enum SideChannelSink {
1944    /// Writes to the process's stderr.
1945    Stderr,
1946    /// Writes to the process's stdout.
1947    Stdout,
1948    /// Writes to a log buffer (e.g. tracing/log crate sink).
1949    LogBuffer,
1950    /// Writes to a file path determined at construction time.
1951    File,
1952    /// Writes to a network endpoint determined at
1953    /// construction time.
1954    Network,
1955    /// Writes to an observable surface not covered by the
1956    /// other variants. The host should consult the node's
1957    /// documentation for the specific contract.
1958    Other,
1959}
1960
1961/// Semantic contract for a scalar node's explicitly registered SIMD variant.
1962///
1963/// This metadata is deliberately attached to the scalar node rather than
1964/// inferred from function names. A promotion pass may use it only after it
1965/// also validates the scalar/register port shapes and proves that the complete
1966/// vector cone lowers for the effective host ISA.
1967#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1968pub struct SimdVariant {
1969    /// DSL name of the register-typed, lane-wise equivalent node.
1970    pub vector_node: &'static str,
1971    /// Whether every lane is exactly equivalent to one scalar invocation.
1972    pub exact: bool,
1973    /// Whether evaluation is total for every bit pattern admitted by the
1974    /// scalar input types. Tier-1 padded execution requires this flag.
1975    pub total: bool,
1976    /// Whether one lane can be evaluated without reading or changing another
1977    /// lane. Scalar-flow auto-promotion requires this flag.
1978    pub lane_independent: bool,
1979}
1980
1981impl SimdVariant {
1982    /// Exact, total, element-wise variant used by the first promotion tier.
1983    pub const fn exact_total(vector_node: &'static str) -> Self {
1984        Self {
1985            vector_node,
1986            exact: true,
1987            total: true,
1988            lane_independent: true,
1989        }
1990    }
1991
1992    /// Exact element-wise variant which may fault for some lane values.
1993    ///
1994    /// Such a variant can be used only when the planner proves the admitted
1995    /// value range or implements ordered lane-error attribution.
1996    pub const fn exact_fallible(vector_node: &'static str) -> Self {
1997        Self {
1998            vector_node,
1999            exact: true,
2000            total: false,
2001            lane_independent: true,
2002        }
2003    }
2004}
2005
2006/// Runtime evaluation interface for a Polydat node.
2007///
2008/// Every engine drives this trait: the interpreter through `eval`,
2009/// the closure and native engines through `compiled_u64` /
2010/// `compiled_slot` where a node offers them and the node's own
2011/// closure elsewhere.
2012pub trait PolydatNode: Send + Sync {
2013    /// Return this node's metadata (port names and types).
2014    fn meta(&self) -> &NodeMeta;
2015
2016    /// Evaluate the node: read from `inputs`, write to `outputs`.
2017    ///
2018    /// The assembly phase guarantees that `inputs` and `outputs` have
2019    /// the correct length and types matching `meta()`.
2020    fn eval(&self, inputs: &[Value], outputs: &mut [Value]);
2021
2022    /// The scratch entries a state owns for this node's evaluation
2023    /// (axiom S3), one per entry in the order the node expects them
2024    /// in [`Self::eval_in`]. Empty for a node that evaluates over
2025    /// `Value`s alone, which is every node but a native cone.
2026    fn scratch_layout(&self) -> Vec<ScratchElem> {
2027        Vec::new()
2028    }
2029
2030    /// [`Self::eval`] with the node's scratch, which the evaluating
2031    /// state owns and hands in: storage belongs to the state, never to
2032    /// the node, which is shared by every state of the program.
2033    fn eval_in(&self, scratch: &mut [ScratchBuf], inputs: &[Value], outputs: &mut [Value]) {
2034        let _ = scratch;
2035        self.eval(inputs, outputs)
2036    }
2037
2038    /// Declare which inputs are interchangeable for this node.
2039    ///
2040    /// Override for commutative operations like `sum`, `product`,
2041    /// `min`, `max`. The default is `Positional` (order matters).
2042    fn commutativity(&self) -> Commutativity {
2043        Commutativity::Positional
2044    }
2045
2046    /// True iff this node should receive `Value::None` inputs
2047    /// directly rather than have the kernel propagate None through
2048    /// it. Default: false — most nodes follow SRD-74 Rule 1
2049    /// (None in → None out, no eval invocation).
2050    ///
2051    /// Override to true for nodes whose semantics explicitly
2052    /// consume None: coalesce-style fallbacks (`default_or`),
2053    /// optional/maybe handlers, anything that distinguishes
2054    /// "present" from "absent" as part of its contract.
2055    /// Override-true nodes are responsible for handling
2056    /// `Value::None` in their own `eval` implementation.
2057    ///
2058    /// See `crates/polydat/docs/design/none_semantics.md`
2059    /// (string-interpolation propagates None) — the
2060    /// rule is general (lifted to the kernel level) rather than
2061    /// per-node; this flag is the opt-out for legitimate None-
2062    /// aware operators.
2063    fn accepts_none_inputs(&self) -> bool {
2064        false
2065    }
2066
2067    /// Return a compiled u64-only evaluation closure, if this node
2068    /// operates entirely in u64 space.
2069    ///
2070    /// The closure reads from an input slice and writes to an output
2071    /// slice, both `&[u64]` / `&mut [u64]`. Assembly-time parameters
2072    /// are captured in the closure.
2073    ///
2074    /// Return `None` if the node has non-u64 ports or cannot be
2075    /// compiled. The assembly phase will fall back to Phase 1.
2076    fn compiled_u64(&self) -> Option<CompiledU64Op> {
2077        None
2078    }
2079
2080    /// Return a slot-compiled closure for nodes with typed-slice
2081    /// ports (§8.4 layer 3): slice inputs read `(ptr, len)` slot
2082    /// pairs; vector outputs write into kernel-owned scratch.
2083    /// Checked by the compiled-kernel builders AFTER
2084    /// [`Self::compiled_u64`] — pure-scalar nodes never need it.
2085    /// Default `None`: the node stays on typed eval.
2086    fn compiled_slot(&self, _wire_types: &[PortType]) -> Option<CompiledSlotKit> {
2087        None
2088    }
2089
2090    /// Return assembly-time constants for JIT compilation.
2091    ///
2092    /// Nodes with baked-in constants (Mod's modulus, Add's addend, etc.)
2093    /// override this to expose their constants to the JIT compiler.
2094    /// Returns a list of u64 constants in the order the JIT expects.
2095    ///
2096    /// Default: empty (no constants to expose).
2097    fn jit_constants(&self) -> Vec<u64> {
2098        Vec::new()
2099    }
2100
2101    /// Declare this node's purity status per the
2102    /// [`runtime_model.md`'s D2 axiom][spec]. Default:
2103    /// [`Purity::Pure`]. Override to declare an observable
2104    /// side channel ([`Purity::SideChannel`]) or
2105    /// eval-call-spanning state ([`Purity::Nondeterministic`]).
2106    ///
2107    /// **What this affects:**
2108    ///
2109    /// - The runtime's `node_clean` cache (R1) holds for
2110    ///   `Purity::Pure` and `Purity::SideChannel`. The
2111    ///   typed return value is cached after one eval;
2112    ///   subsequent pulls with identical inputs reuse the
2113    ///   cache. For `SideChannel` nodes, this means the
2114    ///   side channel fires once per dirty-to-clean
2115    ///   transition (not on every pull).
2116    /// - `Purity::Nondeterministic` nodes opt out of `node_clean`
2117    ///   caching at the construction tier (the assembler's
2118    ///   lifecycle classes mark them as nondeterministic,
2119    ///   `PolydatProgram::nondeterministic`).
2120    /// - Hosts inspecting an expression's determinism
2121    ///   profile via D2 read this declaration to know
2122    ///   whether the constituent node has side channels.
2123    ///
2124    /// Default: `Purity::Pure`. Most nodes are pure
2125    /// functions over their inputs.
2126    ///
2127    /// [spec]: https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/runtime_model.md
2128    fn purity(&self) -> Purity {
2129        Purity::Pure
2130    }
2131
2132    /// Explicit SIMD-native implementation of this scalar node, if one has
2133    /// been registered with a semantic contract.
2134    ///
2135    /// Returning metadata does not itself make a node promotable. The planner
2136    /// must still validate types, purity, source replay, packet ownership, and
2137    /// successful lowering by the same Cranelift ISA used for code generation.
2138    fn simd_variant(&self) -> Option<SimdVariant> {
2139        None
2140    }
2141
2142    /// A synthetic fusion node's view of the subgraph it stands in
2143    /// for (SRD-105 cone extraction). Program-identity hashing
2144    /// (`PolydatProgram::canonical_hash`) walks THROUGH fusion
2145    /// nodes into this subgraph, so identity is invariant to the
2146    /// engine mix: `jit=off` and `jit=auto` compiles of the same
2147    /// source hash identically, and resume-skip matching survives
2148    /// mode changes. Default `None`: ordinary nodes hash as
2149    /// themselves.
2150    fn fusion_subgraph(&self) -> Option<FusionSubgraph<'_>> {
2151        None
2152    }
2153}
2154
2155/// Borrowed view of the subgraph a fusion node replaced. Local
2156/// wiring convention: `WireSource::Input(i)` refers to the fusion
2157/// node's i-th input wire in the OUTER graph; `NodeOutput(j, p)`
2158/// refers to member `j`'s port `p`.
2159pub struct FusionSubgraph<'a> {
2160    /// The original member nodes, verbatim.
2161    pub members: &'a [Box<dyn PolydatNode>],
2162    /// Per-member local wiring (see convention above).
2163    pub wiring: &'a [Vec<crate::kernel::WireSource>],
2164    /// Per fusion output port: `(member index, member port)` —
2165    /// the original producer behind that port.
2166    pub out_ports: &'a [(usize, usize)],
2167}
2168
2169/// Determine the compile level of a node (works on trait objects).
2170pub fn compile_level_of(node: &dyn PolydatNode) -> CompileLevel {
2171    #[cfg(feature = "jit")]
2172    {
2173        let jit_op = crate::compile::jit::classify_node(node);
2174        if !matches!(jit_op, crate::compile::jit::JitOp::Fallback) {
2175            return CompileLevel::Phase3;
2176        }
2177    }
2178
2179    if node.compiled_u64().is_some() {
2180        CompileLevel::Phase2
2181    } else {
2182        CompileLevel::Phase1
2183    }
2184}
2185
2186/// The maximum compilation level a node supports.
2187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2188pub enum CompileLevel {
2189    /// Runtime interpreter: `dyn PolydatNode` + `Value` enum.
2190    Phase1,
2191    /// Compiled closure: `Box<dyn Fn(&[u64], &mut [u64])>`.
2192    Phase2,
2193    /// JIT native code via Cranelift.
2194    Phase3,
2195}
2196
2197#[cfg(test)]
2198mod purity_tests {
2199    use super::*;
2200
2201    /// A minimal pure node — defaults to `Purity::Pure` via
2202    /// the trait default impl.
2203    struct DefaultPureNode {
2204        meta: NodeMeta,
2205    }
2206
2207    impl PolydatNode for DefaultPureNode {
2208        fn meta(&self) -> &NodeMeta {
2209            &self.meta
2210        }
2211        fn eval(&self, _inputs: &[Value], outputs: &mut [Value]) {
2212            outputs[0] = Value::U64(42);
2213        }
2214    }
2215
2216    /// A node that explicitly declares a side channel.
2217    struct SideChannelNode {
2218        meta: NodeMeta,
2219    }
2220
2221    impl PolydatNode for SideChannelNode {
2222        fn meta(&self) -> &NodeMeta {
2223            &self.meta
2224        }
2225        fn eval(&self, _inputs: &[Value], _outputs: &mut [Value]) {}
2226        fn purity(&self) -> Purity {
2227            Purity::SideChannel {
2228                sink: SideChannelSink::Stderr,
2229            }
2230        }
2231    }
2232
2233    /// A node that explicitly declares stateful behaviour.
2234    struct StatefulNode {
2235        meta: NodeMeta,
2236    }
2237
2238    impl PolydatNode for StatefulNode {
2239        fn meta(&self) -> &NodeMeta {
2240            &self.meta
2241        }
2242        fn eval(&self, _inputs: &[Value], _outputs: &mut [Value]) {}
2243        fn purity(&self) -> Purity {
2244            Purity::Nondeterministic {
2245                reason: "test fixture",
2246            }
2247        }
2248    }
2249
2250    fn empty_meta() -> NodeMeta {
2251        NodeMeta {
2252            name: "test".into(),
2253            ins: vec![],
2254            outs: vec![Port::u64("out")],
2255        }
2256    }
2257
2258    #[test]
2259    fn default_purity_is_pure() {
2260        let n = DefaultPureNode { meta: empty_meta() };
2261        assert_eq!(n.purity(), Purity::Pure);
2262    }
2263
2264    #[test]
2265    fn side_channel_declaration_is_observable() {
2266        let n = SideChannelNode { meta: empty_meta() };
2267        match n.purity() {
2268            Purity::SideChannel { sink } => assert_eq!(sink, SideChannelSink::Stderr),
2269            other => panic!("expected SideChannel, got {other:?}"),
2270        }
2271    }
2272
2273    #[test]
2274    fn stateful_declaration_is_observable() {
2275        let n = StatefulNode { meta: empty_meta() };
2276        match n.purity() {
2277            Purity::Nondeterministic { reason } => assert_eq!(reason, "test fixture"),
2278            other => panic!("expected Stateful, got {other:?}"),
2279        }
2280    }
2281
2282    #[test]
2283    fn inspect_node_declares_stderr_side_channel() {
2284        let n = crate::library::diagnostic::Inspect::new(PortType::U64, "x".to_string());
2285        match n.purity() {
2286            Purity::SideChannel { sink } => assert_eq!(sink, SideChannelSink::Stderr),
2287            other => panic!("inspect should declare Stderr SideChannel, got {other:?}"),
2288        }
2289    }
2290
2291    #[test]
2292    fn log_passthrough_declares_log_buffer_side_channel() {
2293        let n = crate::library::log_levels::LogInfo::new(PortType::U64);
2294        match n.purity() {
2295            Purity::SideChannel { sink } => assert_eq!(sink, SideChannelSink::LogBuffer),
2296            other => panic!("log_passthrough should declare LogBuffer SideChannel, got {other:?}"),
2297        }
2298    }
2299}
2300
2301#[cfg(test)]
2302mod value_size_probe {
2303    /// The `Value` enum rides per-slot in every node buffer; its
2304    /// size is a load-bearing budget: 40 bytes (the `SliceArc`
2305    /// borrow shape) at alignment 8. The 128-bit integer variants
2306    /// deliberately ride as two u64 limbs ([`super::Bits128`])
2307    /// instead of raw `u128`/`i128` payloads — a native 128-bit
2308    /// field would force the enum to alignment 16 and grow every
2309    /// buffer slot to 48 bytes for a rarely-carried type
2310    /// (type_system_alignment.md §8.1). This test pins the
2311    /// envelope so an accidental payload regression is caught at
2312    /// the door.
2313    #[test]
2314    fn value_fits_size_envelope() {
2315        assert!(
2316            std::mem::size_of::<super::Value>() <= 40,
2317            "Value grew past the 40-byte envelope: {}",
2318            std::mem::size_of::<super::Value>()
2319        );
2320        assert_eq!(
2321            std::mem::align_of::<super::Value>(),
2322            8,
2323            "Value alignment must stay 8 — a 16-aligned payload \
2324             (raw u128/i128?) snuck in"
2325        );
2326    }
2327}
2328
2329/// A borrowed view of a [`Value`] (SRD 115 §6.1): what a compiled helper
2330/// or closure sees for an argument it does not own. A scalar is carried
2331/// by value, a string or byte string by reference into the arena or the
2332/// interner, a JSON value by reference into the value table, and any
2333/// other variant by reference to the `Value` itself. The P1 nodes build
2334/// the same view from their `Value` inputs, so one body serves both
2335/// tiers without copying a string argument to inspect it.
2336#[derive(Clone, Copy, Debug)]
2337pub enum ValueRef<'a> {
2338    /// An unsigned integer.
2339    U64(u64),
2340    /// A signed integer.
2341    I64(i64),
2342    /// A float.
2343    F64(f64),
2344    /// A boolean.
2345    Bool(bool),
2346    /// A string, borrowed from the arena or the interner.
2347    Str(&'a str),
2348    /// A byte string, borrowed.
2349    Bytes(&'a [u8]),
2350    /// A JSON value, by reference into the value table.
2351    Json(&'a serde_json::Value),
2352    /// No value.
2353    None,
2354    /// Any other variant, by reference to the value.
2355    Other(&'a Value),
2356}
2357
2358impl<'a> From<&'a Value> for ValueRef<'a> {
2359    fn from(v: &'a Value) -> Self {
2360        match v {
2361            Value::U64(x) => ValueRef::U64(*x),
2362            Value::I64(x) => ValueRef::I64(*x),
2363            Value::F64(x) => ValueRef::F64(*x),
2364            Value::Bool(b) => ValueRef::Bool(*b),
2365            Value::Str(s) => ValueRef::Str(s),
2366            Value::Bytes(b) => ValueRef::Bytes(b),
2367            Value::Json(j) => ValueRef::Json(j),
2368            Value::None => ValueRef::None,
2369            other => ValueRef::Other(other),
2370        }
2371    }
2372}
2373
2374impl<'a> ValueRef<'a> {
2375    /// The port type of the value viewed.
2376    pub fn port_type(&self) -> PortType {
2377        match self {
2378            ValueRef::U64(_) => PortType::U64,
2379            ValueRef::I64(_) => PortType::I64,
2380            ValueRef::F64(_) => PortType::F64,
2381            ValueRef::Bool(_) => PortType::Bool,
2382            ValueRef::Str(_) => PortType::Str,
2383            ValueRef::Bytes(_) => PortType::Bytes,
2384            ValueRef::Json(_) => PortType::Json,
2385            ValueRef::None => Value::None.port_type(),
2386            ValueRef::Other(v) => v.port_type(),
2387        }
2388    }
2389
2390    /// The display form, exactly as [`Value::to_display_string`] gives
2391    /// it; a string is borrowed rather than copied.
2392    pub fn display(&self) -> std::borrow::Cow<'a, str> {
2393        use std::borrow::Cow;
2394        match self {
2395            ValueRef::Str(s) => Cow::Borrowed(s),
2396            ValueRef::U64(v) => Cow::Owned(v.to_string()),
2397            ValueRef::I64(v) => Cow::Owned(v.to_string()),
2398            ValueRef::F64(v) => Cow::Owned(format!("{v:?}")),
2399            ValueRef::Bool(v) => Cow::Owned(v.to_string()),
2400            ValueRef::Bytes(b) => Cow::Owned(b.iter().map(|b| format!("{b:02x}")).collect()),
2401            ValueRef::Json(j) => Cow::Owned(j.to_string()),
2402            ValueRef::None => Cow::Owned(Value::None.to_display_string()),
2403            ValueRef::Other(v) => Cow::Owned(v.to_display_string()),
2404        }
2405    }
2406
2407    /// The display form as an owned string.
2408    pub fn to_display_string(&self) -> String {
2409        self.display().into_owned()
2410    }
2411
2412    /// The JSON projection, exactly as [`Value::to_json_value`] gives it.
2413    pub fn to_json_value(&self) -> serde_json::Value {
2414        match self {
2415            ValueRef::U64(v) => serde_json::Value::from(*v),
2416            ValueRef::I64(v) => serde_json::Value::from(*v),
2417            ValueRef::F64(v) => serde_json::json!(*v),
2418            ValueRef::Bool(v) => serde_json::Value::from(*v),
2419            ValueRef::Str(s) => serde_json::Value::from(*s),
2420            ValueRef::Bytes(b) => {
2421                serde_json::Value::from(b.iter().map(|b| format!("{b:02x}")).collect::<String>())
2422            }
2423            ValueRef::Json(j) => (*j).clone(),
2424            ValueRef::None => Value::None.to_json_value(),
2425            ValueRef::Other(v) => v.to_json_value(),
2426        }
2427    }
2428}
2429
2430#[cfg(test)]
2431mod satisfies_slot_tests {
2432    use super::*;
2433
2434    /// A float node output rides its bit pattern in `Value::U64`
2435    /// (`Wire for f32` / `Wire for f16` inject it so), and a host may
2436    /// write the materialised `Value::F64` instead; a float slot
2437    /// accepts both, and a `U64` slot does not accept a float.
2438    #[test]
2439    fn float_slots_accept_the_bit_stuffed_and_materialised_forms() {
2440        let f32_bits = Value::U64(1.5f32.to_bits() as u64);
2441        let f16_bits = Value::U64(half::f16::from_f32(1.5).to_bits() as u64);
2442        assert!(f32_bits.satisfies_slot(PortType::F32));
2443        assert!(f16_bits.satisfies_slot(PortType::F16));
2444        assert!(Value::F64(1.5).satisfies_slot(PortType::F32));
2445        assert!(Value::F64(1.5).satisfies_slot(PortType::F16));
2446        assert!(!Value::F64(1.5).satisfies_slot(PortType::U64));
2447        assert!(!Value::Str("1.5".into()).satisfies_slot(PortType::F32));
2448    }
2449}