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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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.type_name()),
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            // `None` is the absence of a value, which no port type
646            // names. `U64` is what this has always answered, and
647            // callers that care read it through
648            // [`Self::type_name`] or test for `None` first
649            // ([`Self::satisfies_slot`] does).
650            Value::None => PortType::U64,
651        }
652    }
653
654    /// The name of this value's type, for a diagnostic.
655    ///
656    /// Distinct from [`Self::port_type`] in the one case that
657    /// matters: an absent value reads as "none" rather than as the
658    /// `u64` its port type answers. A reader told "expected Handle,
659    /// got U64" goes looking for a number; the value was not there
660    /// at all, which is a different fault with a different cause.
661    pub fn type_name(&self) -> String {
662        match self {
663            Value::None => "none".to_string(),
664            other => other.port_type().to_string(),
665        }
666    }
667
668    /// Borrow a `VecF32` value as `&[f32]`. Panics on type mismatch.
669    #[inline]
670    pub fn as_vec_f32(&self) -> &[f32] {
671        match self {
672            Value::VecF32(arc) => arc,
673            _ => panic!("expected VecF32, got {}", self.type_name()),
674        }
675    }
676
677    /// Test whether this value's runtime variant is acceptable
678    /// to a slot declaring `slot_type`. `port_type() == slot_type`
679    /// is the strict case; this method also accepts the
680    /// **bit-stuffing equivalences** documented in
681    /// `polydat/docs/design/type_system.md` §1:
682    ///
683    /// - `Value::U64` is the runtime storage for `PortType` `U64`,
684    ///   `U32`, `I64`, and `I32` (narrow integers carry their
685    ///   bits in the low part of the u64; sign-extension for
686    ///   `I32` is part of the producer convention).
687    /// - `Value::F64` is the runtime storage for `PortType` `F64`
688    ///   and `F32` (`F32` carries its bits in the low 32 via
689    ///   `f32::to_bits() as u64`-style stuffing — but float
690    ///   stuffing uses `Value::F64` for the materialised float
691    ///   value, not the bit pattern).
692    /// - `Value::None` is acceptable for every slot type
693    ///   (SRD-74 absent sentinel).
694    ///
695    /// Used at the typed-write residual check
696    /// (`Dataflow::set_wire_idx`) AFTER the boundary adapter has
697    /// already converted/validated the value — see
698    /// `kernel/api_impl.rs`. The pre-adapter check in
699    /// `adapt_boundary_value` stays strict (`port_type ==
700    /// slot_type`) so an unadapted Value::U64 can never silently
701    /// truncate into a narrower slot.
702    #[inline]
703    pub fn satisfies_slot(&self, slot_type: PortType) -> bool {
704        if matches!(self, Value::None) {
705            return true;
706        }
707        let value_type = self.port_type();
708        if value_type == slot_type {
709            return true;
710        }
711        matches!(
712            (value_type, slot_type),
713            // Bit-stuffed forms: U8/U16/U32 zero-extend into U64
714            // storage, the signed narrow types may still arrive as
715            // U64 storage from a pre-alignment producer, and F32 and
716            // F16 ride their bit patterns in U64 (`Wire for f32` and
717            // `Wire for f16` inject them so).
718            (PortType::U64, PortType::U32 | PortType::I64 | PortType::I32
719                | PortType::U8 | PortType::U16 | PortType::I8 | PortType::I16
720                | PortType::F32 | PortType::F16)
721                | (PortType::F64, PortType::F32 | PortType::F16)
722                // Honest signed carrier: I64 storage serves the
723                // I64 slot and the sign-extended narrow signed
724                // projections.
725                | (PortType::I64, PortType::I32 | PortType::I8 | PortType::I16)
726                // Register views are free bitcasts: a word under
727                // any view satisfies a slot declaring any other
728                // (the consumer's declared lane typing IS the
729                // bitcast).
730                | (
731                    PortType::Reg128 | PortType::RegI8x16 | PortType::RegI16x8
732                        | PortType::RegI32x4 | PortType::RegI64x2
733                        | PortType::RegF16x8 | PortType::RegF32x4 | PortType::RegF64x2,
734                    PortType::Reg128 | PortType::RegI8x16 | PortType::RegI16x8
735                        | PortType::RegI32x4 | PortType::RegI64x2
736                        | PortType::RegF16x8 | PortType::RegF32x4 | PortType::RegF64x2,
737                )
738        )
739    }
740
741    /// Borrow a `VecI32` value as `&[i32]`. Panics on type mismatch.
742    #[inline]
743    pub fn as_vec_i32(&self) -> &[i32] {
744        match self {
745            Value::VecI32(arc) => arc,
746            _ => panic!("expected VecI32, got {}", self.type_name()),
747        }
748    }
749
750    /// Borrow a `VecF64` value as `&[f64]`. Panics on type mismatch.
751    #[inline]
752    pub fn as_vec_f64(&self) -> &[f64] {
753        match self {
754            Value::VecF64(arc) => arc,
755            _ => panic!("expected VecF64, got {}", self.type_name()),
756        }
757    }
758
759    /// Borrow a `VecI64` value as `&[i64]`. Panics on type mismatch.
760    #[inline]
761    pub fn as_vec_i64(&self) -> &[i64] {
762        match self {
763            Value::VecI64(arc) => arc,
764            _ => panic!("expected VecI64, got {}", self.type_name()),
765        }
766    }
767
768    /// Borrow a `VecF16` value as `&[half::f16]`. Panics on type mismatch.
769    #[inline]
770    pub fn as_vec_f16(&self) -> &[half::f16] {
771        match self {
772            Value::VecF16(arc) => arc,
773            _ => panic!("expected VecF16, got {}", self.type_name()),
774        }
775    }
776
777    /// Borrow a `VecI16` value as `&[i16]`. Panics on type mismatch.
778    #[inline]
779    pub fn as_vec_i16(&self) -> &[i16] {
780        match self {
781            Value::VecI16(arc) => arc,
782            _ => panic!("expected VecI16, got {}", self.type_name()),
783        }
784    }
785
786    /// Borrow a `VecI8` value as `&[i8]`. Panics on type mismatch.
787    #[inline]
788    pub fn as_vec_i8(&self) -> &[i8] {
789        match self {
790            Value::VecI8(arc) => arc,
791            _ => panic!("expected VecI8, got {}", self.type_name()),
792        }
793    }
794
795    /// Downcast a Handle value to a borrowed reference of its concrete
796    /// type. Panics if the variant isn't `Handle` or the type doesn't
797    /// match. Used by reader nodes that consume a typed-handle wire
798    /// produced by a resolver node (see SRD 53 §"Dataset Handles").
799    ///
800    /// The borrow lasts as long as `self` (the buffer slot's `Value`
801    /// is what holds the `Arc`). For per-cycle reads this is the
802    /// expected pattern — call methods on the borrowed dataset, then
803    /// return.
804    #[inline]
805    pub fn as_handle<T: std::any::Any + Send + Sync>(&self) -> &T {
806        match self {
807            Value::Handle(arc) => arc.downcast_ref::<T>().unwrap_or_else(|| {
808                panic!(
809                    "Handle downcast failed: expected {}",
810                    std::any::type_name::<T>()
811                )
812            }),
813            _ => panic!("expected Handle, got {}", self.type_name()),
814        }
815    }
816
817    /// Construct a `Value::Handle` from a typed `Arc<T>`. Convenience
818    /// wrapper that performs the type-erasure to `Arc<dyn Any + Send + Sync>`.
819    pub fn handle<T: std::any::Any + Send + Sync>(arc: Arc<T>) -> Self {
820        Value::Handle(arc as Arc<dyn std::any::Any + Send + Sync>)
821    }
822
823    /// Best-effort string representation for any value.
824    /// Works across all variants including Ext.
825    pub fn to_display_string(&self) -> String {
826        match self {
827            Value::U64(v) => v.to_string(),
828            Value::I64(v) => v.to_string(),
829            Value::U128(b) => b.as_u128().to_string(),
830            Value::I128(b) => b.as_i128().to_string(),
831            // Lane-typed register views render like the Vec*
832            // display forms; the raw view renders as 32 hex
833            // digits (the full word as buffer state).
834            Value::Reg128(b, view) => match view {
835                RegLanes::Raw => format!("{:032x}", b.as_u128()),
836                RegLanes::I8x16 => format!("{:?}", b.lanes_i8()),
837                RegLanes::I16x8 => format!("{:?}", b.lanes_i16()),
838                RegLanes::I32x4 => format!("{:?}", b.lanes_i32()),
839                RegLanes::I64x2 => format!("{:?}", b.lanes_i64()),
840                RegLanes::F16x8 => format!("{:?}", b.lanes_f16().map(|f| f.to_f32())),
841                RegLanes::F32x4 => format!("{:?}", b.lanes_f32()),
842                RegLanes::F64x2 => format!("{:?}", b.lanes_f64()),
843            },
844            // `{v:?}` (Rust Debug) for f64 always includes at
845            // least one fractional digit, so whole-number floats
846            // render as `1.0` instead of `1` — distinguishing
847            // them from integers in CQL OPTIONS strings, plot
848            // labels, and other surfaces where the type matters.
849            // Display-formatted (`v.to_string()`) strips the
850            // trailing zero, conflating ints with whole-number
851            // floats. Both forms produce identical output for
852            // non-whole floats (`1.5 → "1.5"`).
853            Value::F64(v) => format!("{v:?}"),
854            Value::Bool(v) => v.to_string(),
855            Value::Str(v) => v.to_string(),
856            Value::Bytes(v) => v.iter().map(|b| format!("{b:02x}")).collect(),
857            Value::Json(v) => v.to_string(),
858            Value::Ext(v) => v.display(),
859            Value::Handle(arc) => format!("<handle:{:?}>", arc.type_id()),
860            Value::VecF32(arc) => {
861                // JSON-array text. Per-element format-write into a
862                // pre-sized String avoids the intermediate Vec<String>.
863                // Debug formatter (`{v:?}`) matches the F64 element
864                // rule above: whole-number floats render as `1.0`
865                // so VecF32 stays distinguishable from VecI32 at the
866                // display surface.
867                let mut s = String::with_capacity(arc.len() * 8 + 2);
868                s.push('[');
869                let mut first = true;
870                for v in arc.iter() {
871                    if !first {
872                        s.push(',');
873                    }
874                    first = false;
875                    use std::fmt::Write;
876                    let _ = write!(&mut s, "{v:?}");
877                }
878                s.push(']');
879                s
880            }
881            Value::VecI32(arc) => {
882                let mut s = String::with_capacity(arc.len() * 4 + 2);
883                s.push('[');
884                let mut first = true;
885                for v in arc.iter() {
886                    if !first {
887                        s.push(',');
888                    }
889                    first = false;
890                    use std::fmt::Write;
891                    let _ = write!(&mut s, "{v}");
892                }
893                s.push(']');
894                s
895            }
896            Value::VecF64(arc) => {
897                let mut s = String::with_capacity(arc.len() * 8 + 2);
898                s.push('[');
899                let mut first = true;
900                for v in arc.iter() {
901                    if !first {
902                        s.push(',');
903                    }
904                    first = false;
905                    use std::fmt::Write;
906                    let _ = write!(&mut s, "{v:?}");
907                }
908                s.push(']');
909                s
910            }
911            Value::VecI64(arc) => {
912                let mut s = String::with_capacity(arc.len() * 4 + 2);
913                s.push('[');
914                let mut first = true;
915                for v in arc.iter() {
916                    if !first {
917                        s.push(',');
918                    }
919                    first = false;
920                    use std::fmt::Write;
921                    let _ = write!(&mut s, "{v}");
922                }
923                s.push(']');
924                s
925            }
926            Value::VecF16(arc) => {
927                let mut s = String::with_capacity(arc.len() * 6 + 2);
928                s.push('[');
929                let mut first = true;
930                for v in arc.iter() {
931                    if !first {
932                        s.push(',');
933                    }
934                    first = false;
935                    use std::fmt::Write;
936                    // Render as the f32 widening so the JSON form
937                    // is the standard "1.0" / "1.5" surface — f16
938                    // Display has its own form but it isn't valid
939                    // JSON, so widening makes the array shape
940                    // parseable downstream.
941                    let _ = write!(&mut s, "{:?}", v.to_f32());
942                }
943                s.push(']');
944                s
945            }
946            Value::VecI16(arc) => {
947                let mut s = String::with_capacity(arc.len() * 4 + 2);
948                s.push('[');
949                let mut first = true;
950                for v in arc.iter() {
951                    if !first {
952                        s.push(',');
953                    }
954                    first = false;
955                    use std::fmt::Write;
956                    let _ = write!(&mut s, "{v}");
957                }
958                s.push(']');
959                s
960            }
961            Value::VecI8(arc) => {
962                let mut s = String::with_capacity(arc.len() * 4 + 2);
963                s.push('[');
964                let mut first = true;
965                for v in arc.iter() {
966                    if !first {
967                        s.push(',');
968                    }
969                    first = false;
970                    use std::fmt::Write;
971                    let _ = write!(&mut s, "{v}");
972                }
973                s.push(']');
974                s
975            }
976            Value::None => String::new(),
977        }
978    }
979
980    /// Strict-render variant of [`Self::to_display_string`] for use
981    /// at wire-protocol render sites (op-template substitution,
982    /// adapter byte-emission paths).
983    ///
984    /// Returns `None` for [`Value::None`] instead of converting it
985    /// to `""`. The empty-string mapping in `to_display_string` is
986    /// convenient for diagnostic / log contexts but lethal at the
987    /// wire boundary — it silently coerces "absent" into "present
988    /// but empty," corrupting downstream bytes (e.g. sending
989    /// `'source_model': ''` to a CQL cluster when the intended
990    /// shadow didn't bind). Render paths use this primitive and
991    /// surface a clear error when an unresolved bind-point reaches
992    /// them. See `crates/polydat/docs/design/none_semantics.md`
993    /// (the render-refuses-silent-None rule).
994    pub fn to_display_strict(&self) -> Option<String> {
995        match self {
996            Value::None => None,
997            other => Some(other.to_display_string()),
998        }
999    }
1000
1001    /// JSON representation for any value. Works across all variants.
1002    pub fn to_json_value(&self) -> serde_json::Value {
1003        match self {
1004            Value::U64(v) => serde_json::Value::from(*v),
1005            Value::I64(v) => serde_json::Value::from(*v),
1006            // JSON Number is bounded by u64/i64/f64 leaves
1007            // (serde_json without arbitrary_precision); 128-bit
1008            // magnitudes project as decimal strings, the same
1009            // string-convention family as Bytes-as-hex.
1010            Value::U128(b) => serde_json::Value::String(b.as_u128().to_string()),
1011            Value::I128(b) => serde_json::Value::String(b.as_i128().to_string()),
1012            // Lane-typed views project as homogeneous arrays
1013            // (same shape as the matching Vec*); the raw view as
1014            // a hex string (lane roles are algorithm-defined, so
1015            // no numeric reading exists).
1016            Value::Reg128(b, view) => match view {
1017                RegLanes::Raw => serde_json::Value::String(format!("{:032x}", b.as_u128())),
1018                RegLanes::I8x16 => serde_json::Value::Array(
1019                    b.lanes_i8()
1020                        .iter()
1021                        .map(|i| serde_json::Value::from(*i as i32))
1022                        .collect(),
1023                ),
1024                RegLanes::I16x8 => serde_json::Value::Array(
1025                    b.lanes_i16()
1026                        .iter()
1027                        .map(|i| serde_json::Value::from(*i as i32))
1028                        .collect(),
1029                ),
1030                RegLanes::I32x4 => serde_json::Value::Array(
1031                    b.lanes_i32()
1032                        .iter()
1033                        .map(|i| serde_json::Value::from(*i))
1034                        .collect(),
1035                ),
1036                RegLanes::I64x2 => serde_json::Value::Array(
1037                    b.lanes_i64()
1038                        .iter()
1039                        .map(|i| serde_json::Value::from(*i))
1040                        .collect(),
1041                ),
1042                RegLanes::F16x8 => serde_json::Value::Array(
1043                    b.lanes_f16()
1044                        .iter()
1045                        .map(|f| serde_json::json!(f.to_f32()))
1046                        .collect(),
1047                ),
1048                RegLanes::F32x4 => serde_json::Value::Array(
1049                    b.lanes_f32()
1050                        .iter()
1051                        .map(|f| serde_json::json!(*f))
1052                        .collect(),
1053                ),
1054                RegLanes::F64x2 => serde_json::Value::Array(
1055                    b.lanes_f64()
1056                        .iter()
1057                        .map(|f| serde_json::json!(*f))
1058                        .collect(),
1059                ),
1060            },
1061            Value::F64(v) => serde_json::json!(*v),
1062            Value::Bool(v) => serde_json::Value::from(*v),
1063            Value::Str(v) => serde_json::Value::from(&**v),
1064            Value::Bytes(v) => {
1065                serde_json::Value::from(v.iter().map(|b| format!("{b:02x}")).collect::<String>())
1066            }
1067            Value::Json(v) => (**v).clone(),
1068            Value::Ext(v) => v.to_json_value(),
1069            Value::Handle(_) => serde_json::Value::Null,
1070            Value::VecF32(arc) => {
1071                serde_json::Value::Array(arc.iter().map(|f| serde_json::json!(*f)).collect())
1072            }
1073            Value::VecI32(arc) => {
1074                serde_json::Value::Array(arc.iter().map(|i| serde_json::Value::from(*i)).collect())
1075            }
1076            Value::VecF64(arc) => {
1077                serde_json::Value::Array(arc.iter().map(|f| serde_json::json!(*f)).collect())
1078            }
1079            Value::VecI64(arc) => {
1080                serde_json::Value::Array(arc.iter().map(|i| serde_json::Value::from(*i)).collect())
1081            }
1082            Value::VecF16(arc) => serde_json::Value::Array(
1083                arc.iter().map(|f| serde_json::json!(f.to_f32())).collect(),
1084            ),
1085            Value::VecI16(arc) => serde_json::Value::Array(
1086                arc.iter()
1087                    .map(|i| serde_json::Value::from(*i as i32))
1088                    .collect(),
1089            ),
1090            Value::VecI8(arc) => serde_json::Value::Array(
1091                arc.iter()
1092                    .map(|i| serde_json::Value::from(*i as i32))
1093                    .collect(),
1094            ),
1095            Value::None => serde_json::Value::Null,
1096        }
1097    }
1098}
1099
1100pub use polydat_grammar::{NumericDomain, PortType};
1101
1102/// What a port type means to a compiled buffer: its slot color, the
1103/// width that follows from it, and the scratch element a by-reference
1104/// producer owns. The type itself is the grammar's
1105/// (`polydat_grammar::PortType`); these are the runtime's reading of
1106/// it, and every layout, codegen, and guard decision derives from
1107/// them.
1108pub trait SlotShape {
1109    /// Slot color in compiled (P2/P3/hybrid) kernel buffers —
1110    /// axiom S1 (`jit_boundary.md` §"Slot-state axioms"). The
1111    /// single chokepoint: width and every layout/codegen/guard
1112    /// decision derive from this, never restate it.
1113    fn slot_color(&self) -> SlotColor;
1114    /// The scratch element a `Ref2`-colored port's producer owns
1115    /// (axiom S3); `None` for an immediate color.
1116    fn scratch_elem(&self) -> Option<ScratchElem>;
1117    /// Buffer slots this type occupies — derived from
1118    /// [`Self::slot_color`] per axiom S1.
1119    fn slot_width(&self) -> usize;
1120}
1121
1122impl SlotShape for PortType {
1123    #[inline]
1124    fn slot_color(&self) -> SlotColor {
1125        match self {
1126            // 128-bit immediates: two slots of limb DATA —
1127            // register words and 128-bit integers are values,
1128            // never addresses.
1129            Self::U128
1130            | Self::I128
1131            | Self::Reg128
1132            | Self::RegI8x16
1133            | Self::RegI16x8
1134            | Self::RegI32x4
1135            | Self::RegI64x2
1136            | Self::RegF16x8
1137            | Self::RegF32x4
1138            | Self::RegF64x2 => SlotColor::Imm2,
1139            // Heap slices: a (ptr, len) reference pair viewing
1140            // kernel-owned scratch (§8.4 layer 3). A string and a
1141            // byte string are slices of bytes; a JSON, extension, or
1142            // handle value is a one-element slice holding the value.
1143            Self::VecF32
1144            | Self::VecI32
1145            | Self::VecF64
1146            | Self::VecI64
1147            | Self::VecF16
1148            | Self::VecI16
1149            | Self::VecI8
1150            | Self::Str
1151            | Self::Bytes
1152            | Self::Json
1153            | Self::Ext
1154            | Self::Handle => SlotColor::Ref2,
1155            // Everything else (incl. all narrow widths riding
1156            // their 64-bit carriers): one slot of immediate data.
1157            _ => SlotColor::Imm1,
1158        }
1159    }
1160
1161    #[inline]
1162    fn scratch_elem(&self) -> Option<ScratchElem> {
1163        Some(match self {
1164            Self::VecF32 => ScratchElem::F32,
1165            Self::VecF64 => ScratchElem::F64,
1166            Self::VecF16 => ScratchElem::F16,
1167            Self::VecI8 => ScratchElem::I8,
1168            Self::VecI16 => ScratchElem::I16,
1169            Self::VecI32 => ScratchElem::I32,
1170            Self::VecI64 => ScratchElem::I64,
1171            Self::Str => ScratchElem::Str,
1172            Self::Bytes => ScratchElem::Bytes,
1173            Self::Json | Self::Ext | Self::Handle => ScratchElem::Value,
1174            _ => return None,
1175        })
1176    }
1177
1178    #[inline]
1179    fn slot_width(&self) -> usize {
1180        match self.slot_color() {
1181            SlotColor::Imm1 => 1,
1182            SlotColor::Imm2 | SlotColor::Ref2 => 2,
1183        }
1184    }
1185}
1186
1187/// The lifecycle of a port's value.
1188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1189pub enum Lifecycle {
1190    /// Cycle-time: value changes per evaluation.
1191    Cycle,
1192    /// Init-time: value is frozen at assembly, immutable at runtime.
1193    /// Wiring a cycle-time value to an init port is an assembly error.
1194    Init,
1195}
1196
1197/// Cost class for an input wire, indicating how expensive it is
1198/// to change the value on this port.
1199#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1200pub enum WireCost {
1201    /// Data wire: cheap per-cycle input. The node's primary
1202    /// computation path. Default for most ports.
1203    #[default]
1204    Data,
1205    /// Config wire: changing this input invalidates expensive
1206    /// internal state (LUT, distribution table). Expected to be
1207    /// wired to init-time constants or rarely-changing values.
1208    /// The compiler warns when a config wire connects to a
1209    /// cycle-time binding.
1210    Config,
1211}
1212
1213/// Descriptor for a single input or output port on a node.
1214#[derive(Debug, Clone)]
1215pub struct Port {
1216    /// The port's name, as bindings and diagnostics refer to it.
1217    pub name: String,
1218    /// The port's declared type.
1219    pub typ: PortType,
1220    /// When the port's value changes: per cycle, at init, or as configuration.
1221    pub lifecycle: Lifecycle,
1222    /// Cost class for input ports. Ignored for output ports.
1223    pub wire_cost: WireCost,
1224    /// Optional value contract this wire must satisfy at runtime
1225    /// (SRD 15 §"Strict Wire Mode"). The compiler uses this to
1226    /// decide whether to auto-insert a value assertion when the
1227    /// upstream source can't statically be proven to deliver a
1228    /// satisfying value. `None` = no constraint declared.
1229    ///
1230    /// Constraints reuse the same vocabulary as
1231    /// [`crate::dsl::const_constraints::ConstConstraint`] — the
1232    /// difference is just where the value comes from (a literal
1233    /// for `ConstU64`, a wire for `Slot::Wire`).
1234    pub constraint: Option<crate::dsl::const_constraints::ConstConstraint>,
1235    /// Whether this port takes the wire's value as it is, whatever
1236    /// type the wire carries — in which case [`Self::typ`] is a
1237    /// nominal placeholder and the assembler inserts no adapter into
1238    /// this port.
1239    ///
1240    /// The one shape that needs it is an element of a `&[Value]`
1241    /// variadic: the node inspects the `Value` variant itself, so
1242    /// converting the wire to the port's declared type would change
1243    /// what the node sees — `json_array(cycle)` would hold the text
1244    /// of a number rather than the number. A plain `Value` argument
1245    /// does not need it, because the assembler resolves that port's
1246    /// type from its wire and hands it to the constructor.
1247    ///
1248    /// The assembler used to decide this from a list of thirteen node
1249    /// names, which was both a name-keyed table and the wrong
1250    /// granularity: `pick`'s selector wires must be `Bool` while its
1251    /// value wires are polymorphic, and one flag per node cannot say
1252    /// that.
1253    pub accepts_any_type: bool,
1254}
1255
1256impl Port {
1257    /// A cycle-lifecycle port of the given type with no constraint.
1258    pub fn new(name: impl Into<String>, typ: PortType) -> Self {
1259        Self {
1260            name: name.into(),
1261            typ,
1262            lifecycle: Lifecycle::Cycle,
1263            wire_cost: WireCost::Data,
1264            constraint: None,
1265            accepts_any_type: false,
1266        }
1267    }
1268
1269    /// This port, taking the wire as it is whatever its type. See
1270    /// [`Self::accepts_any_type`].
1271    pub fn any_type(mut self) -> Self {
1272        self.accepts_any_type = true;
1273        self
1274    }
1275
1276    /// Create a port with explicit lifecycle.
1277    pub fn with_lifecycle(name: impl Into<String>, typ: PortType, lifecycle: Lifecycle) -> Self {
1278        Self {
1279            name: name.into(),
1280            typ,
1281            lifecycle,
1282            wire_cost: WireCost::Data,
1283            constraint: None,
1284            accepts_any_type: false,
1285        }
1286    }
1287
1288    /// A `u64` port.
1289    pub fn u64(name: impl Into<String>) -> Self {
1290        Self::new(name, PortType::U64)
1291    }
1292
1293    /// An `f64` port.
1294    pub fn f64(name: impl Into<String>) -> Self {
1295        Self::new(name, PortType::F64)
1296    }
1297
1298    /// A string port.
1299    pub fn str(name: impl Into<String>) -> Self {
1300        Self::new(name, PortType::Str)
1301    }
1302
1303    /// A boolean port.
1304    pub fn bool(name: impl Into<String>) -> Self {
1305        Self::new(name, PortType::Bool)
1306    }
1307
1308    /// A JSON port.
1309    pub fn json(name: impl Into<String>) -> Self {
1310        Self::new(name, PortType::Json)
1311    }
1312
1313    /// A handle port.
1314    pub fn handle(name: impl Into<String>) -> Self {
1315        Self::new(name, PortType::Handle)
1316    }
1317
1318    /// An `f32` vector port.
1319    pub fn vec_f32(name: impl Into<String>) -> Self {
1320        Self::new(name, PortType::VecF32)
1321    }
1322
1323    /// An `i32` vector port.
1324    pub fn vec_i32(name: impl Into<String>) -> Self {
1325        Self::new(name, PortType::VecI32)
1326    }
1327
1328    /// Create an init-time port (frozen at assembly).
1329    pub fn init(name: impl Into<String>, typ: PortType) -> Self {
1330        Self::with_lifecycle(name, typ, Lifecycle::Init)
1331    }
1332
1333    /// Attach a value constraint. Used by node authors that want
1334    /// to declare "this wire must satisfy X" so strict-wire-mode
1335    /// can auto-insert the right value assertion. See SRD 15
1336    /// §"Strict Wire Mode".
1337    pub fn with_constraint(mut self, c: crate::dsl::const_constraints::ConstConstraint) -> Self {
1338        self.constraint = Some(c);
1339        self
1340    }
1341
1342    /// Mark this port as a config wire (expensive to change).
1343    pub fn config(mut self) -> Self {
1344        self.wire_cost = WireCost::Config;
1345        self
1346    }
1347
1348    /// Set the wire cost directly. Used by the macro to thread
1349    /// `Wire::WIRE_COST` from the trait through to the slot.
1350    pub fn with_cost(mut self, cost: WireCost) -> Self {
1351        self.wire_cost = cost;
1352        self
1353    }
1354}
1355
1356// ---------------------------------------------------------------------------
1357// Unified slot model (SRD 36 §Variadic)
1358// ---------------------------------------------------------------------------
1359
1360/// The type discriminant for a slot: wire or typed constant.
1361///
1362/// This is the shared vocabulary between `FuncSig` (static registry)
1363/// and `NodeMeta` (owned instance). It replaces the former `ParamKind`,
1364/// `ConstType`, and `SlotKind` enums with a single type.
1365#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1366pub enum SlotType {
1367    /// A runtime wire input carrying a value each cycle.
1368    Wire,
1369    /// A u64 constant literal.
1370    ConstU64,
1371    /// An f64 constant literal.
1372    ConstF64,
1373    /// A string constant literal.
1374    ConstStr,
1375    /// A `Vec<u64>` constant (from array literal).
1376    ConstVecU64,
1377    /// A `Vec<f64>` constant (from array literal).
1378    ConstVecF64,
1379    /// SRD-80b Phase C — typed-element variadic-const slot for
1380    /// `Const<Vec<C>>` operator-side shape. Element type
1381    /// discrimination is emitted inline by the macro at the
1382    /// build-closure call site, from the element type it read out of
1383    /// the signature; the slot tag only signals "this is a list" to
1384    /// the DSL type-checker.
1385    ConstVec,
1386}
1387
1388impl SlotType {
1389    /// Whether this is a constant (not a wire).
1390    pub fn is_const(self) -> bool {
1391        !matches!(self, SlotType::Wire)
1392    }
1393
1394    /// Whether this is a wire (not a constant).
1395    pub fn is_wire(self) -> bool {
1396        matches!(self, SlotType::Wire)
1397    }
1398}
1399
1400/// A concrete constant value stored in node metadata.
1401///
1402/// Assembly-time values baked into the node at construction. The
1403/// variant determines the `SlotType` — no separate type discriminant
1404/// is needed.
1405#[derive(Debug, Clone, PartialEq)]
1406pub enum ConstValue {
1407    /// An unsigned integer.
1408    U64(u64),
1409    /// A floating-point number.
1410    F64(f64),
1411    /// A string.
1412    Str(String),
1413    /// A list of unsigned integers.
1414    VecU64(Vec<u64>),
1415    /// A list of floating-point numbers.
1416    VecF64(Vec<f64>),
1417}
1418
1419impl ConstValue {
1420    /// Return the `SlotType` for this value.
1421    pub fn slot_type(&self) -> SlotType {
1422        match self {
1423            ConstValue::U64(_) => SlotType::ConstU64,
1424            ConstValue::F64(_) => SlotType::ConstF64,
1425            ConstValue::Str(_) => SlotType::ConstStr,
1426            ConstValue::VecU64(_) => SlotType::ConstVecU64,
1427            ConstValue::VecF64(_) => SlotType::ConstVecF64,
1428        }
1429    }
1430
1431    /// Encode to the JIT's u64 representation.
1432    pub fn to_jit_u64s(&self) -> Vec<u64> {
1433        match self {
1434            ConstValue::U64(v) => vec![*v],
1435            ConstValue::F64(v) => vec![v.to_bits()],
1436            ConstValue::Str(_) => vec![],
1437            ConstValue::VecU64(v) => v.clone(),
1438            ConstValue::VecF64(v) => v.iter().map(|f| f.to_bits()).collect(),
1439        }
1440    }
1441}
1442
1443/// A single logical input to a node: either a runtime wire or an
1444/// assembly-time constant. The positional order in `NodeMeta.slots`
1445/// matches the function call syntax in the DSL.
1446#[derive(Debug, Clone)]
1447pub enum Slot {
1448    /// A runtime wire input carrying a value each cycle.
1449    Wire(Port),
1450    /// An assembly-time constant, baked into the node at construction.
1451    Const {
1452        /// The constant's name, as the node's signature calls it.
1453        name: String,
1454        /// The baked value.
1455        value: ConstValue,
1456    },
1457}
1458
1459impl Slot {
1460    /// Return the `SlotType` discriminant for this slot.
1461    pub fn slot_type(&self) -> SlotType {
1462        match self {
1463            Slot::Wire(_) => SlotType::Wire,
1464            Slot::Const { value, .. } => value.slot_type(),
1465        }
1466    }
1467
1468    /// Create a wire slot.
1469    pub fn wire(port: Port) -> Self {
1470        Slot::Wire(port)
1471    }
1472
1473    /// Create a u64 constant slot.
1474    pub fn const_u64(name: impl Into<String>, v: u64) -> Self {
1475        Slot::Const {
1476            name: name.into(),
1477            value: ConstValue::U64(v),
1478        }
1479    }
1480
1481    /// Create an f64 constant slot.
1482    pub fn const_f64(name: impl Into<String>, v: f64) -> Self {
1483        Slot::Const {
1484            name: name.into(),
1485            value: ConstValue::F64(v),
1486        }
1487    }
1488
1489    /// Create a string constant slot.
1490    pub fn const_str(name: impl Into<String>, v: impl Into<String>) -> Self {
1491        Slot::Const {
1492            name: name.into(),
1493            value: ConstValue::Str(v.into()),
1494        }
1495    }
1496
1497    /// Create a `Vec<u64>` constant slot.
1498    pub fn const_vec_u64(name: impl Into<String>, v: Vec<u64>) -> Self {
1499        Slot::Const {
1500            name: name.into(),
1501            value: ConstValue::VecU64(v),
1502        }
1503    }
1504
1505    /// Create a `Vec<f64>` constant slot.
1506    pub fn const_vec_f64(name: impl Into<String>, v: Vec<f64>) -> Self {
1507        Slot::Const {
1508            name: name.into(),
1509            value: ConstValue::VecF64(v),
1510        }
1511    }
1512}
1513
1514/// Declares which inputs of a node are interchangeable.
1515///
1516/// Used by the fusion pattern matcher to recognize equivalent
1517/// subgraphs regardless of operand order, and by future passes
1518/// (e.g., canonical ordering, common subexpression elimination).
1519#[derive(Debug, Clone, PartialEq, Eq, Default)]
1520pub enum Commutativity {
1521    /// Input order matters. No permutations attempted during
1522    /// pattern matching. This is the default for unary nodes and
1523    /// any node where operand order affects the result.
1524    ///
1525    /// Examples: `mod(dividend, divisor)`, `div(x, K)`,
1526    /// `concat(left, right)`, `sub(a, b)`.
1527    #[default]
1528    Positional,
1529
1530    /// All inputs are interchangeable, including variadic.
1531    /// For small arity (2-3), the matcher tries all permutations.
1532    /// For larger arity, it uses set-matching.
1533    ///
1534    /// Examples: `sum(a, b, ..., n)`, `product(a, b, ..., n)`,
1535    /// `min(a, b, ..., n)`, `max(a, b, ..., n)`.
1536    AllCommutative,
1537
1538    /// Specific groups of input port indices are interchangeable
1539    /// within each group. Inputs not listed in any group are
1540    /// positional.
1541    ///
1542    /// Example: `fma(x, y, z) = x + y * z`
1543    /// The multiplicands `y` (index 1) and `z` (index 2) commute,
1544    /// but the addend `x` (index 0) does not.
1545    /// `Groups(vec![vec![1, 2]])`
1546    Groups(Vec<Vec<usize>>),
1547}
1548
1549/// Metadata describing a node's interface: its input slots and output ports.
1550///
1551/// Generated per-node-type and queryable at runtime for assembly-time
1552/// validation, compilation, optimization passes, and describe output.
1553///
1554/// Wire inputs are `Slot::Wire(Port)`. Constants are `Slot::Const { name, value }`.
1555/// Use `wire_inputs()` to extract just the wire ports.
1556#[derive(Debug, Clone)]
1557pub struct NodeMeta {
1558    /// The node's function name, as programs call it.
1559    pub name: String,
1560    /// All inputs in positional order: wires and constants.
1561    pub ins: Vec<Slot>,
1562    /// The output ports, in positional order.
1563    pub outs: Vec<Port>,
1564}
1565
1566impl NodeMeta {
1567    /// Wire-only input ports extracted from `ins`.
1568    pub fn wire_inputs(&self) -> Vec<&Port> {
1569        self.ins
1570            .iter()
1571            .filter_map(|s| match s {
1572                Slot::Wire(p) => Some(p),
1573                Slot::Const { .. } => None,
1574            })
1575            .collect()
1576    }
1577
1578    /// Constant names and values extracted from `ins`.
1579    pub fn const_slots(&self) -> Vec<(&str, &ConstValue)> {
1580        self.ins
1581            .iter()
1582            .filter_map(|s| match s {
1583                Slot::Const { name, value } => Some((name.as_str(), value)),
1584                Slot::Wire(_) => None,
1585            })
1586            .collect()
1587    }
1588
1589    /// Encode all constants from `ins` to JIT u64 representation.
1590    pub fn jit_constants_from_slots(&self) -> Vec<u64> {
1591        self.const_slots()
1592            .iter()
1593            .flat_map(|(_, v)| v.to_jit_u64s())
1594            .collect()
1595    }
1596}
1597
1598/// A compiled u64-only evaluation step.
1599///
1600/// The closure captures all assembly-time parameters. At runtime it
1601/// reads from input slots and writes to output slots in a flat `[u64]`
1602/// buffer — no `Value` enum, no virtual dispatch.
1603pub type CompiledU64Op = Box<dyn Fn(&[u64], &mut [u64]) + Send + Sync>;
1604
1605/// Element type of one kernel-owned scratch buffer
1606/// (type_system_alignment.md §8.4 layer 3). One entry per
1607/// `Ref2`-colored output port of a slot-compiled node: a typed
1608/// vector, a string, a byte string, or a value held by reference.
1609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1610pub enum ScratchElem {
1611    /// `f32` elements.
1612    F32,
1613    /// `f64` elements.
1614    F64,
1615    /// `f16` elements.
1616    F16,
1617    /// `i8` elements.
1618    I8,
1619    /// `i16` elements.
1620    I16,
1621    /// `i32` elements.
1622    I32,
1623    /// `i64` elements.
1624    I64,
1625    /// The UTF-8 bytes of a string.
1626    Str,
1627    /// The bytes of a byte string.
1628    Bytes,
1629    /// One value held by reference (`Json`, `Ext`, `Handle`): the
1630    /// pair is `(&Value, 1)`.
1631    Value,
1632    /// A buffer of 64-bit slots: a native cone's own slot buffer,
1633    /// owned by the state that evaluates it.
1634    Slots,
1635    /// The kernels a tile render keeps over its projection bodies,
1636    /// owned by the state that renders.
1637    Kernels,
1638    /// State a node defines for itself per evaluating kernel state, a
1639    /// memo of what it last derived from its inputs, created by the
1640    /// node on first use; a clone starts empty.
1641    State,
1642}
1643
1644/// Node-defined state held by a kernel state (`ScratchElem::State`):
1645/// what a node keeps between its evaluations in one state, typed by
1646/// the node and never shared between states. Empty until the node
1647/// first fills it; a clone is empty, since a clone of a state is a
1648/// new state (compiled_handles.md §3).
1649#[derive(Default)]
1650pub struct NodeState(Option<Box<dyn std::any::Any + Send + Sync>>);
1651
1652impl NodeState {
1653    /// The state as `T`, created by `init` when the entry is empty or
1654    /// holds another type.
1655    pub fn get_or_insert_with<T: std::any::Any + Send + Sync>(
1656        &mut self,
1657        init: impl FnOnce() -> T,
1658    ) -> &mut T {
1659        if !self.0.as_ref().is_some_and(|b| b.is::<T>()) {
1660            self.0 = Some(Box::new(init()));
1661        }
1662        self.0
1663            .as_mut()
1664            .and_then(|b| b.downcast_mut::<T>())
1665            .expect("the entry holds a T")
1666    }
1667
1668    /// The state as `T`, if the node has filled it with one.
1669    pub fn get<T: std::any::Any + Send + Sync>(&self) -> Option<&T> {
1670        self.0.as_ref().and_then(|b| b.downcast_ref::<T>())
1671    }
1672}
1673
1674impl Clone for NodeState {
1675    fn clone(&self) -> Self {
1676        NodeState(None)
1677    }
1678}
1679
1680impl std::fmt::Debug for NodeState {
1681    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1682        write!(
1683            f,
1684            "NodeState({})",
1685            if self.0.is_some() { "filled" } else { "empty" }
1686        )
1687    }
1688}
1689
1690/// Slot color of a `PortType` in compiled kernel buffers —
1691/// axiom S1: static, total, three-valued. `Imm*` slots carry
1692/// immediate data only (never addresses); `Ref2` pairs carry a
1693/// `(ptr, len)` reference to storage with a proven owner: the
1694/// step's own scratch, an extern's stored value, an interned
1695/// constant, or a boundary value alive for the call. They are
1696/// engine-internal per axiom S2.
1697#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1698pub enum SlotColor {
1699    /// One slot of immediate data.
1700    Imm1,
1701    /// Two slots of immediate limb data (128-bit values).
1702    Imm2,
1703    /// Two slots holding a (ptr, len) reference pair.
1704    Ref2,
1705}
1706
1707/// One kernel-owned scratch buffer. A `Ref2` output port's
1708/// `(ptr, len)` buffer slots view its scratch — the kernel owns
1709/// the allocation, so the pointer is valid exactly as long as the
1710/// producing step doesn't rerun (and a rerun rewrites the slots
1711/// before any consumer reads them). No Arc traffic, no allocation
1712/// after warmup: a string or byte string is rewritten in place, a
1713/// value is replaced.
1714#[derive(Debug, Clone)]
1715pub enum ScratchBuf {
1716    /// An `f32` buffer.
1717    F32(Vec<f32>),
1718    /// An `f64` buffer.
1719    F64(Vec<f64>),
1720    /// An `f16` buffer.
1721    F16(Vec<half::f16>),
1722    /// An `i8` buffer.
1723    I8(Vec<i8>),
1724    /// An `i16` buffer.
1725    I16(Vec<i16>),
1726    /// An `i32` buffer.
1727    I32(Vec<i32>),
1728    /// An `i64` buffer.
1729    I64(Vec<i64>),
1730    /// The UTF-8 bytes of a string.
1731    Str(Vec<u8>),
1732    /// The bytes of a byte string.
1733    Bytes(Vec<u8>),
1734    /// One value held by reference; empty until the step first runs.
1735    Value(Vec<Value>),
1736    /// A buffer of 64-bit slots (a native cone's own).
1737    Slots(Vec<u64>),
1738    /// The kernels a tile render keeps over its projection bodies. A
1739    /// clone is empty: a new state builds its own.
1740    Kernels(crate::library::tile_render::BodyKernels),
1741    /// State a node defines for itself, per kernel state. A clone is
1742    /// empty: a new state derives its own.
1743    State(NodeState),
1744}
1745
1746impl ScratchBuf {
1747    /// The `(ptr, len)` pair this entry currently publishes —
1748    /// the ground truth axiom S9(a)'s validator compares buffer
1749    /// slots against.
1750    pub fn ptr_len(&self) -> (u64, u64) {
1751        match self {
1752            ScratchBuf::F32(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1753            ScratchBuf::F64(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1754            ScratchBuf::F16(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1755            ScratchBuf::I8(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1756            ScratchBuf::I16(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1757            ScratchBuf::I32(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1758            ScratchBuf::I64(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1759            ScratchBuf::Str(v) | ScratchBuf::Bytes(v) => {
1760                (v.as_ptr() as usize as u64, v.len() as u64)
1761            }
1762            ScratchBuf::Value(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1763            ScratchBuf::Slots(v) => (v.as_ptr() as usize as u64, v.len() as u64),
1764            ScratchBuf::Kernels(_) | ScratchBuf::State(_) => (0, 0),
1765        }
1766    }
1767
1768    /// What this entry holds as an owned `Value`, copied out: the
1769    /// typed read of a `Ref2` output on a compiled kernel, which is
1770    /// what the interpreter's `pull` returns for the same port. A
1771    /// value entry that has not been written reads as `None`.
1772    pub fn to_value(&self) -> Value {
1773        match self {
1774            ScratchBuf::F32(v) => Value::VecF32(SliceArc::from_vec(v.clone())),
1775            ScratchBuf::F64(v) => Value::VecF64(SliceArc::from_vec(v.clone())),
1776            ScratchBuf::F16(v) => Value::VecF16(SliceArc::from_vec(v.clone())),
1777            ScratchBuf::I8(v) => Value::VecI8(SliceArc::from_vec(v.clone())),
1778            ScratchBuf::I16(v) => Value::VecI16(SliceArc::from_vec(v.clone())),
1779            ScratchBuf::I32(v) => Value::VecI32(SliceArc::from_vec(v.clone())),
1780            ScratchBuf::I64(v) => Value::VecI64(SliceArc::from_vec(v.clone())),
1781            // SAFETY: a `Str` entry is written only from `&str` bytes.
1782            ScratchBuf::Str(v) => {
1783                Value::Str(Arc::from(unsafe { std::str::from_utf8_unchecked(v) }))
1784            }
1785            ScratchBuf::Bytes(v) => Value::Bytes(Arc::from(&v[..])),
1786            ScratchBuf::Value(v) => v.first().cloned().unwrap_or(Value::None),
1787            ScratchBuf::Slots(_) => panic!("a slot buffer is not a value"),
1788            ScratchBuf::Kernels(_) => panic!("a body kernel set is not a value"),
1789            ScratchBuf::State(_) => panic!("a node's own state is not a value"),
1790        }
1791    }
1792
1793    /// The node-defined state this entry holds. The entry must be a
1794    /// `State` entry.
1795    pub fn node_state(&mut self) -> &mut NodeState {
1796        match self {
1797            ScratchBuf::State(s) => s,
1798            other => panic!("scratch entry holds {other:?}, not a node's state"),
1799        }
1800    }
1801
1802    /// Replace the string this entry holds, reusing its allocation.
1803    /// The entry must be a `Str` entry.
1804    #[inline]
1805    pub fn set_str(&mut self, s: &str) {
1806        match self {
1807            ScratchBuf::Str(v) => {
1808                v.clear();
1809                v.extend_from_slice(s.as_bytes());
1810            }
1811            other => panic!("scratch entry holds {other:?}, not a string"),
1812        }
1813    }
1814
1815    /// Replace the byte string this entry holds, reusing its
1816    /// allocation. The entry must be a `Bytes` entry.
1817    #[inline]
1818    pub fn set_bytes(&mut self, b: &[u8]) {
1819        match self {
1820            ScratchBuf::Bytes(v) => {
1821                v.clear();
1822                v.extend_from_slice(b);
1823            }
1824            other => panic!("scratch entry holds {other:?}, not a byte string"),
1825        }
1826    }
1827
1828    /// Fill this entry from `v`, whatever kind of entry it is.
1829    ///
1830    /// The entry's own variant decides, and it was allocated from the
1831    /// step's declared [`ScratchElem`] — so the type the graph resolved
1832    /// picks the write, rather than a match over `Value` that has to be
1833    /// extended every time the language grows a carrier. A value that
1834    /// does not fit the entry is a graph that mis-typed the slot, and
1835    /// the inner setters say so.
1836    #[inline]
1837    pub fn set_from_value(&mut self, v: &Value) {
1838        match self {
1839            ScratchBuf::Str(_) => self.set_str(v.as_str()),
1840            ScratchBuf::Bytes(_) => self.set_bytes(v.as_bytes()),
1841            ScratchBuf::Value(_) => self.set_value(v.clone()),
1842            ScratchBuf::F32(_)
1843            | ScratchBuf::F64(_)
1844            | ScratchBuf::F16(_)
1845            | ScratchBuf::I8(_)
1846            | ScratchBuf::I16(_)
1847            | ScratchBuf::I32(_)
1848            | ScratchBuf::I64(_) => self.set_vector(v),
1849            other => {
1850                panic!("scratch entry holds {other:?}, which no by-reference value is written into")
1851            }
1852        }
1853    }
1854
1855    /// Replace the numeric vector this entry holds, reusing its
1856    /// allocation. The entry must be the matching element type.
1857    ///
1858    /// The typed write path reaches a vector entry through the node's
1859    /// declared element type; this is the same write for the path that
1860    /// only has a [`Value`] in hand ([`crate::derive_support::write_poly`]),
1861    /// which is how a vector reaches a polymorphic node's output.
1862    #[inline]
1863    pub fn set_vector(&mut self, value: &Value) {
1864        macro_rules! fill {
1865            ($v:expr, $src:expr) => {{
1866                $v.clear();
1867                $v.extend_from_slice($src);
1868            }};
1869        }
1870        match (self, value) {
1871            (ScratchBuf::F32(v), Value::VecF32(s)) => fill!(v, s.as_slice()),
1872            (ScratchBuf::F64(v), Value::VecF64(s)) => fill!(v, s.as_slice()),
1873            (ScratchBuf::F16(v), Value::VecF16(s)) => fill!(v, s.as_slice()),
1874            (ScratchBuf::I8(v), Value::VecI8(s)) => fill!(v, s.as_slice()),
1875            (ScratchBuf::I16(v), Value::VecI16(s)) => fill!(v, s.as_slice()),
1876            (ScratchBuf::I32(v), Value::VecI32(s)) => fill!(v, s.as_slice()),
1877            (ScratchBuf::I64(v), Value::VecI64(s)) => fill!(v, s.as_slice()),
1878            (entry, v) => panic!(
1879                "scratch entry holds {entry:?}, which does not carry a {:?}",
1880                v.port_type()
1881            ),
1882        }
1883    }
1884
1885    /// Replace the value this entry holds. The entry must be a
1886    /// `Value` entry.
1887    #[inline]
1888    pub fn set_value(&mut self, value: Value) {
1889        match self {
1890            ScratchBuf::Value(v) => {
1891                v.clear();
1892                v.push(value);
1893            }
1894            other => panic!("scratch entry holds {other:?}, not a value"),
1895        }
1896    }
1897
1898    /// An empty buffer of the element type.
1899    pub fn new(elem: ScratchElem) -> Self {
1900        match elem {
1901            ScratchElem::F32 => ScratchBuf::F32(Vec::new()),
1902            ScratchElem::F64 => ScratchBuf::F64(Vec::new()),
1903            ScratchElem::F16 => ScratchBuf::F16(Vec::new()),
1904            ScratchElem::I8 => ScratchBuf::I8(Vec::new()),
1905            ScratchElem::I16 => ScratchBuf::I16(Vec::new()),
1906            ScratchElem::I32 => ScratchBuf::I32(Vec::new()),
1907            ScratchElem::I64 => ScratchBuf::I64(Vec::new()),
1908            ScratchElem::Str => ScratchBuf::Str(Vec::new()),
1909            ScratchElem::Bytes => ScratchBuf::Bytes(Vec::new()),
1910            ScratchElem::Value => ScratchBuf::Value(Vec::new()),
1911            ScratchElem::Slots => ScratchBuf::Slots(Vec::new()),
1912            ScratchElem::Kernels => ScratchBuf::Kernels(Default::default()),
1913            ScratchElem::State => ScratchBuf::State(NodeState::default()),
1914        }
1915    }
1916}
1917
1918/// Compiled closure for a node with typed-slice ports (§8.4
1919/// layer 3). Same calling shape as [`CompiledU64Op`] plus the
1920/// step's scratch buffers: slice inputs arrive as `(ptr, len)`
1921/// slot pairs in `inputs`; vector outputs are written into
1922/// scratch and their `(ptr, len)` into `outputs`.
1923pub type CompiledSlotOp = Box<dyn Fn(&[u64], &mut [u64], &mut [ScratchBuf]) + Send + Sync>;
1924
1925/// A slot-compiled node's closure plus its scratch declaration
1926/// (one [`ScratchElem`] per vector-producing output, in port
1927/// order). Returned by [`PolydatNode::compiled_slot`].
1928pub struct CompiledSlotKit {
1929    /// The closure: slice inputs as slot pairs, vector outputs into scratch.
1930    pub op: CompiledSlotOp,
1931    /// One element type per vector-producing output, in port order.
1932    pub scratch: Vec<ScratchElem>,
1933}
1934
1935/// Per-node purity classification per
1936/// [`runtime_model.md`'s D2 axiom][spec] and
1937/// [`composition_substrate.md`'s T1+T2 axioms][substrate].
1938///
1939/// Every node declares its purity status via
1940/// [`PolydatNode::purity`]. The default is [`Purity::Pure`]; nodes
1941/// with observable side channels (logging, file I/O, network)
1942/// or eval-call-spanning state override to declare
1943/// [`Purity::SideChannel`] or [`Purity::Nondeterministic`].
1944///
1945/// **D1 (Typed Return Determinism) holds for every purity
1946/// class.** The slot contract carries only typed return
1947/// values; impure nodes still produce typed-deterministic
1948/// returns. What varies between purity classes is the
1949/// *observable side channels* (D2): pure nodes have none;
1950/// SideChannel nodes have declared side channels; Stateful
1951/// nodes additionally have internal eval-call-spanning state
1952/// that affects future evaluations.
1953///
1954/// [spec]: https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/runtime_model.md
1955/// [substrate]: https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/composition_substrate.md
1956#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1957pub enum Purity {
1958    /// Pure function — `eval(inputs)` is a function of inputs,
1959    /// no observable side effects, byte-identical determinism
1960    /// across calls with identical inputs.
1961    Pure,
1962
1963    /// Has an observable side channel (logging, file I/O,
1964    /// network, etc.) but the typed return value is still a
1965    /// function of inputs. Hosts that care about side-channel
1966    /// observability examine the `sink` to know what
1967    /// observable surface this node writes to.
1968    SideChannel {
1969        /// The observable surface the node writes to.
1970        sink: SideChannelSink,
1971    },
1972
1973    /// The typed return value is not a function of declared
1974    /// inputs alone — it depends on external sources (system
1975    /// clock, entropy, thread identity, environment) or on
1976    /// eval-call-spanning internal state mutated by prior calls.
1977    /// In either case, the runtime's `node_clean` caching model
1978    /// must opt the node out of within-cycle memoization
1979    /// suppression; the assembler's lifecycle classes mark the node
1980    /// as nondeterministic (`PolydatProgram::nondeterministic`).
1981    /// The `reason` string documents the source of
1982    /// non-determinism (e.g., "reads system clock",
1983    /// "monotonic counter incremented per call",
1984    /// "accumulates signal buffer across calls").
1985    ///
1986    /// This is the intrinsic-volatility marker referenced by
1987    /// runtime_model.md R1.v: certain library nodes declare
1988    /// themselves volatile via this variant; no user opt-in is
1989    /// required, and the workload author cannot remove the
1990    /// marker. User-opt-in volatility via the `volatile`
1991    /// modifier is a separate surface that produces the same
1992    /// runtime effect (see R1.v).
1993    Nondeterministic {
1994        /// The source of the non-determinism, for diagnostics.
1995        reason: &'static str,
1996    },
1997}
1998
1999/// Where a [`Purity::SideChannel`] node writes its observable
2000/// side effects. Hosts reasoning about side-channel
2001/// determinism (D2) pattern-match on this to know what
2002/// observable surface to expect.
2003#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2004pub enum SideChannelSink {
2005    /// Writes to the process's stderr.
2006    Stderr,
2007    /// Writes to the process's stdout.
2008    Stdout,
2009    /// Writes to a log buffer (e.g. tracing/log crate sink).
2010    LogBuffer,
2011    /// Writes to a file path determined at construction time.
2012    File,
2013    /// Writes to a network endpoint determined at
2014    /// construction time.
2015    Network,
2016    /// Writes to an observable surface not covered by the
2017    /// other variants. The host should consult the node's
2018    /// documentation for the specific contract.
2019    Other,
2020}
2021
2022/// Semantic contract for a scalar node's explicitly registered SIMD variant.
2023///
2024/// This metadata is deliberately attached to the scalar node rather than
2025/// inferred from function names. A promotion pass may use it only after it
2026/// also validates the scalar/register port shapes and proves that the complete
2027/// vector cone lowers for the effective host ISA.
2028#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2029pub struct SimdVariant {
2030    /// DSL name of the register-typed, lane-wise equivalent node.
2031    pub vector_node: &'static str,
2032    /// Whether every lane is exactly equivalent to one scalar invocation.
2033    pub exact: bool,
2034    /// Whether evaluation is total for every bit pattern admitted by the
2035    /// scalar input types. Tier-1 padded execution requires this flag.
2036    pub total: bool,
2037    /// Whether one lane can be evaluated without reading or changing another
2038    /// lane. Scalar-flow auto-promotion requires this flag.
2039    pub lane_independent: bool,
2040}
2041
2042impl SimdVariant {
2043    /// Exact, total, element-wise variant used by the first promotion tier.
2044    pub const fn exact_total(vector_node: &'static str) -> Self {
2045        Self {
2046            vector_node,
2047            exact: true,
2048            total: true,
2049            lane_independent: true,
2050        }
2051    }
2052
2053    /// Exact element-wise variant which may fault for some lane values.
2054    ///
2055    /// Such a variant can be used only when the planner proves the admitted
2056    /// value range or implements ordered lane-error attribution.
2057    pub const fn exact_fallible(vector_node: &'static str) -> Self {
2058        Self {
2059            vector_node,
2060            exact: true,
2061            total: false,
2062            lane_independent: true,
2063        }
2064    }
2065}
2066
2067/// Runtime evaluation interface for a Polydat node.
2068///
2069/// Every engine drives this trait: the interpreter through `eval`,
2070/// the closure and native engines through `compiled_u64` /
2071/// `compiled_slot` where a node offers them and the node's own
2072/// closure elsewhere.
2073pub trait PolydatNode: Send + Sync {
2074    /// Return this node's metadata (port names and types).
2075    fn meta(&self) -> &NodeMeta;
2076
2077    /// Evaluate the node: read from `inputs`, write to `outputs`.
2078    ///
2079    /// The assembly phase guarantees that `inputs` and `outputs` have
2080    /// the correct length and types matching `meta()`.
2081    fn eval(&self, inputs: &[Value], outputs: &mut [Value]);
2082
2083    /// The scratch entries a state owns for this node's evaluation
2084    /// (axiom S3), one per entry in the order the node expects them
2085    /// in [`Self::eval_in`]. Empty for a node that evaluates over
2086    /// `Value`s alone, which is every node but a native cone.
2087    fn scratch_layout(&self) -> Vec<ScratchElem> {
2088        Vec::new()
2089    }
2090
2091    /// [`Self::eval`] with the node's scratch, which the evaluating
2092    /// state owns and hands in: storage belongs to the state, never to
2093    /// the node, which is shared by every state of the program.
2094    fn eval_in(&self, scratch: &mut [ScratchBuf], inputs: &[Value], outputs: &mut [Value]) {
2095        let _ = scratch;
2096        self.eval(inputs, outputs)
2097    }
2098
2099    /// Declare which inputs are interchangeable for this node.
2100    ///
2101    /// Override for commutative operations like `sum`, `product`,
2102    /// `min`, `max`. The default is `Positional` (order matters).
2103    fn commutativity(&self) -> Commutativity {
2104        Commutativity::Positional
2105    }
2106
2107    /// True iff this node should receive `Value::None` inputs
2108    /// directly rather than have the kernel propagate None through
2109    /// it. Default: false — most nodes follow SRD-74 Rule 1
2110    /// (None in → None out, no eval invocation).
2111    ///
2112    /// Override to true for nodes whose semantics explicitly
2113    /// consume None: coalesce-style fallbacks (`default_or`),
2114    /// optional/maybe handlers, anything that distinguishes
2115    /// "present" from "absent" as part of its contract.
2116    /// Override-true nodes are responsible for handling
2117    /// `Value::None` in their own `eval` implementation.
2118    ///
2119    /// See `crates/polydat/docs/design/none_semantics.md`
2120    /// (string-interpolation propagates None) — the
2121    /// rule is general (lifted to the kernel level) rather than
2122    /// per-node; this flag is the opt-out for legitimate None-
2123    /// aware operators.
2124    fn accepts_none_inputs(&self) -> bool {
2125        false
2126    }
2127
2128    /// Return a compiled u64-only evaluation closure, if this node
2129    /// operates entirely in u64 space.
2130    ///
2131    /// The closure reads from an input slice and writes to an output
2132    /// slice, both `&[u64]` / `&mut [u64]`. Assembly-time parameters
2133    /// are captured in the closure.
2134    ///
2135    /// Return `None` if the node has non-u64 ports or cannot be
2136    /// compiled. The assembly phase will fall back to Phase 1.
2137    fn compiled_u64(&self) -> Option<CompiledU64Op> {
2138        None
2139    }
2140
2141    /// Return a slot-compiled closure for nodes with typed-slice
2142    /// ports (§8.4 layer 3): slice inputs read `(ptr, len)` slot
2143    /// pairs; vector outputs write into kernel-owned scratch.
2144    /// Checked by the compiled-kernel builders AFTER
2145    /// [`Self::compiled_u64`] — pure-scalar nodes never need it.
2146    /// Default `None`: the node stays on typed eval.
2147    ///
2148    /// `engine` is the engine the kit is being built for, which a node
2149    /// needs when its closure runs a program of its own: a tile's
2150    /// projection body belongs to the kernel rendering it, the way a
2151    /// `for` body belongs to the kernel that opened it, and the kit is
2152    /// the only place a closure can learn which that is.
2153    fn compiled_slot(
2154        &self,
2155        _wire_types: &[PortType],
2156        _engine: crate::compile::select::Engine,
2157    ) -> Option<CompiledSlotKit> {
2158        None
2159    }
2160
2161    /// Return assembly-time constants for JIT compilation.
2162    ///
2163    /// Nodes with baked-in constants (Mod's modulus, Add's addend, etc.)
2164    /// override this to expose their constants to the JIT compiler.
2165    /// Returns a list of u64 constants in the order the JIT expects.
2166    ///
2167    /// Default: empty (no constants to expose).
2168    fn jit_constants(&self) -> Vec<u64> {
2169        Vec::new()
2170    }
2171
2172    /// Declare this node's purity status per the
2173    /// [`runtime_model.md`'s D2 axiom][spec]. Default:
2174    /// [`Purity::Pure`]. Override to declare an observable
2175    /// side channel ([`Purity::SideChannel`]) or
2176    /// eval-call-spanning state ([`Purity::Nondeterministic`]).
2177    ///
2178    /// **What this affects:**
2179    ///
2180    /// - The runtime's `node_clean` cache (R1) holds for
2181    ///   `Purity::Pure` and `Purity::SideChannel`. The
2182    ///   typed return value is cached after one eval;
2183    ///   subsequent pulls with identical inputs reuse the
2184    ///   cache. For `SideChannel` nodes, this means the
2185    ///   side channel fires once per dirty-to-clean
2186    ///   transition (not on every pull).
2187    /// - `Purity::Nondeterministic` nodes opt out of `node_clean`
2188    ///   caching at the construction tier (the assembler's
2189    ///   lifecycle classes mark them as nondeterministic,
2190    ///   `PolydatProgram::nondeterministic`).
2191    /// - Hosts inspecting an expression's determinism
2192    ///   profile via D2 read this declaration to know
2193    ///   whether the constituent node has side channels.
2194    ///
2195    /// Default: `Purity::Pure`. Most nodes are pure
2196    /// functions over their inputs.
2197    ///
2198    /// [spec]: https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/runtime_model.md
2199    fn purity(&self) -> Purity {
2200        Purity::Pure
2201    }
2202
2203    /// Explicit SIMD-native implementation of this scalar node, if one has
2204    /// been registered with a semantic contract.
2205    ///
2206    /// Returning metadata does not itself make a node promotable. The planner
2207    /// must still validate types, purity, source replay, packet ownership, and
2208    /// successful lowering by the same Cranelift ISA used for code generation.
2209    fn simd_variant(&self) -> Option<SimdVariant> {
2210        None
2211    }
2212
2213    /// A synthetic fusion node's view of the subgraph it stands in
2214    /// for (SRD-105 cone extraction). Program-identity hashing
2215    /// (`PolydatProgram::canonical_hash`) walks THROUGH fusion
2216    /// nodes into this subgraph, so identity is invariant to the
2217    /// engine mix: `jit=off` and `jit=auto` compiles of the same
2218    /// source hash identically, and resume-skip matching survives
2219    /// mode changes. Default `None`: ordinary nodes hash as
2220    /// themselves.
2221    fn fusion_subgraph(&self) -> Option<FusionSubgraph<'_>> {
2222        None
2223    }
2224}
2225
2226/// Borrowed view of the subgraph a fusion node replaced. Local
2227/// wiring convention: `WireSource::Input(i)` refers to the fusion
2228/// node's i-th input wire in the OUTER graph; `NodeOutput(j, p)`
2229/// refers to member `j`'s port `p`.
2230pub struct FusionSubgraph<'a> {
2231    /// The original member nodes, verbatim.
2232    pub members: &'a [Box<dyn PolydatNode>],
2233    /// Per-member local wiring (see convention above).
2234    pub wiring: &'a [Vec<crate::kernel::WireSource>],
2235    /// Per fusion output port: `(member index, member port)` —
2236    /// the original producer behind that port.
2237    pub out_ports: &'a [(usize, usize)],
2238}
2239
2240/// The compile level of a node, given the types of the wires feeding
2241/// it. One call to [`crate::compile::node_tier`], which is the order
2242/// every builder walks; the types are needed because a node's slot kit
2243/// is offered per call site with the types the kernel fixed.
2244///
2245/// Prefer [`crate::kernel::PolydatProgram::node_compile_level`], which
2246/// reads the types out of the program rather than asking the caller
2247/// for them.
2248pub fn compile_level_of(node: &dyn PolydatNode, wire_types: &[PortType]) -> CompileLevel {
2249    crate::compile::node_tier(node, wire_types)
2250}
2251
2252/// The maximum compilation level a node supports.
2253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2254pub enum CompileLevel {
2255    /// Runtime interpreter: `dyn PolydatNode` + `Value` enum.
2256    Phase1,
2257    /// Compiled closure: `Box<dyn Fn(&[u64], &mut [u64])>`.
2258    Phase2,
2259    /// JIT native code via Cranelift.
2260    Phase3,
2261}
2262
2263#[cfg(test)]
2264mod purity_tests {
2265    use super::*;
2266
2267    /// A minimal pure node — defaults to `Purity::Pure` via
2268    /// the trait default impl.
2269    struct DefaultPureNode {
2270        meta: NodeMeta,
2271    }
2272
2273    impl PolydatNode for DefaultPureNode {
2274        fn meta(&self) -> &NodeMeta {
2275            &self.meta
2276        }
2277        fn eval(&self, _inputs: &[Value], outputs: &mut [Value]) {
2278            outputs[0] = Value::U64(42);
2279        }
2280    }
2281
2282    /// A node that explicitly declares a side channel.
2283    struct SideChannelNode {
2284        meta: NodeMeta,
2285    }
2286
2287    impl PolydatNode for SideChannelNode {
2288        fn meta(&self) -> &NodeMeta {
2289            &self.meta
2290        }
2291        fn eval(&self, _inputs: &[Value], _outputs: &mut [Value]) {}
2292        fn purity(&self) -> Purity {
2293            Purity::SideChannel {
2294                sink: SideChannelSink::Stderr,
2295            }
2296        }
2297    }
2298
2299    /// A node that explicitly declares stateful behaviour.
2300    struct StatefulNode {
2301        meta: NodeMeta,
2302    }
2303
2304    impl PolydatNode for StatefulNode {
2305        fn meta(&self) -> &NodeMeta {
2306            &self.meta
2307        }
2308        fn eval(&self, _inputs: &[Value], _outputs: &mut [Value]) {}
2309        fn purity(&self) -> Purity {
2310            Purity::Nondeterministic {
2311                reason: "test fixture",
2312            }
2313        }
2314    }
2315
2316    fn empty_meta() -> NodeMeta {
2317        NodeMeta {
2318            name: "test".into(),
2319            ins: vec![],
2320            outs: vec![Port::u64("out")],
2321        }
2322    }
2323
2324    #[test]
2325    fn default_purity_is_pure() {
2326        let n = DefaultPureNode { meta: empty_meta() };
2327        assert_eq!(n.purity(), Purity::Pure);
2328    }
2329
2330    #[test]
2331    fn side_channel_declaration_is_observable() {
2332        let n = SideChannelNode { meta: empty_meta() };
2333        match n.purity() {
2334            Purity::SideChannel { sink } => assert_eq!(sink, SideChannelSink::Stderr),
2335            other => panic!("expected SideChannel, got {other:?}"),
2336        }
2337    }
2338
2339    #[test]
2340    fn stateful_declaration_is_observable() {
2341        let n = StatefulNode { meta: empty_meta() };
2342        match n.purity() {
2343            Purity::Nondeterministic { reason } => assert_eq!(reason, "test fixture"),
2344            other => panic!("expected Stateful, got {other:?}"),
2345        }
2346    }
2347
2348    #[test]
2349    fn inspect_node_declares_stderr_side_channel() {
2350        let n = crate::library::diagnostic::Inspect::new(PortType::U64, "x".to_string());
2351        match n.purity() {
2352            Purity::SideChannel { sink } => assert_eq!(sink, SideChannelSink::Stderr),
2353            other => panic!("inspect should declare Stderr SideChannel, got {other:?}"),
2354        }
2355    }
2356
2357    #[test]
2358    fn log_passthrough_declares_log_buffer_side_channel() {
2359        let n = crate::library::log_levels::LogInfo::new(PortType::U64);
2360        match n.purity() {
2361            Purity::SideChannel { sink } => assert_eq!(sink, SideChannelSink::LogBuffer),
2362            other => panic!("log_passthrough should declare LogBuffer SideChannel, got {other:?}"),
2363        }
2364    }
2365}
2366
2367#[cfg(test)]
2368mod value_size_probe {
2369    /// The `Value` enum rides per-slot in every node buffer; its
2370    /// size is a load-bearing budget: 40 bytes (the `SliceArc`
2371    /// borrow shape) at alignment 8. The 128-bit integer variants
2372    /// deliberately ride as two u64 limbs ([`super::Bits128`])
2373    /// instead of raw `u128`/`i128` payloads — a native 128-bit
2374    /// field would force the enum to alignment 16 and grow every
2375    /// buffer slot to 48 bytes for a rarely-carried type
2376    /// (type_system_alignment.md §8.1). This test pins the
2377    /// envelope so an accidental payload regression is caught at
2378    /// the door.
2379    #[test]
2380    fn value_fits_size_envelope() {
2381        assert!(
2382            std::mem::size_of::<super::Value>() <= 40,
2383            "Value grew past the 40-byte envelope: {}",
2384            std::mem::size_of::<super::Value>()
2385        );
2386        assert_eq!(
2387            std::mem::align_of::<super::Value>(),
2388            8,
2389            "Value alignment must stay 8 — a 16-aligned payload \
2390             (raw u128/i128?) snuck in"
2391        );
2392    }
2393}
2394
2395/// A borrowed view of a [`Value`] (SRD 115 §6.1): what a compiled helper
2396/// or closure sees for an argument it does not own. A scalar is carried
2397/// by value, a string or byte string by reference into the arena or the
2398/// interner, a JSON value by reference into the value table, and any
2399/// other variant by reference to the `Value` itself. The P1 nodes build
2400/// the same view from their `Value` inputs, so one body serves both
2401/// tiers without copying a string argument to inspect it.
2402#[derive(Clone, Copy, Debug)]
2403pub enum ValueRef<'a> {
2404    /// An unsigned integer.
2405    U64(u64),
2406    /// A signed integer.
2407    I64(i64),
2408    /// A float.
2409    F64(f64),
2410    /// A boolean.
2411    Bool(bool),
2412    /// A string, borrowed from the arena or the interner.
2413    Str(&'a str),
2414    /// A byte string, borrowed.
2415    Bytes(&'a [u8]),
2416    /// A JSON value, by reference into the value table.
2417    Json(&'a serde_json::Value),
2418    /// No value.
2419    None,
2420    /// Any other variant, by reference to the value.
2421    Other(&'a Value),
2422}
2423
2424impl<'a> From<&'a Value> for ValueRef<'a> {
2425    fn from(v: &'a Value) -> Self {
2426        match v {
2427            Value::U64(x) => ValueRef::U64(*x),
2428            Value::I64(x) => ValueRef::I64(*x),
2429            Value::F64(x) => ValueRef::F64(*x),
2430            Value::Bool(b) => ValueRef::Bool(*b),
2431            Value::Str(s) => ValueRef::Str(s),
2432            Value::Bytes(b) => ValueRef::Bytes(b),
2433            Value::Json(j) => ValueRef::Json(j),
2434            Value::None => ValueRef::None,
2435            other => ValueRef::Other(other),
2436        }
2437    }
2438}
2439
2440impl<'a> ValueRef<'a> {
2441    /// The port type of the value viewed.
2442    pub fn port_type(&self) -> PortType {
2443        match self {
2444            ValueRef::U64(_) => PortType::U64,
2445            ValueRef::I64(_) => PortType::I64,
2446            ValueRef::F64(_) => PortType::F64,
2447            ValueRef::Bool(_) => PortType::Bool,
2448            ValueRef::Str(_) => PortType::Str,
2449            ValueRef::Bytes(_) => PortType::Bytes,
2450            ValueRef::Json(_) => PortType::Json,
2451            ValueRef::None => Value::None.port_type(),
2452            ValueRef::Other(v) => v.port_type(),
2453        }
2454    }
2455
2456    /// The display form, exactly as [`Value::to_display_string`] gives
2457    /// it; a string is borrowed rather than copied.
2458    pub fn display(&self) -> std::borrow::Cow<'a, str> {
2459        use std::borrow::Cow;
2460        match self {
2461            ValueRef::Str(s) => Cow::Borrowed(s),
2462            ValueRef::U64(v) => Cow::Owned(v.to_string()),
2463            ValueRef::I64(v) => Cow::Owned(v.to_string()),
2464            ValueRef::F64(v) => Cow::Owned(format!("{v:?}")),
2465            ValueRef::Bool(v) => Cow::Owned(v.to_string()),
2466            ValueRef::Bytes(b) => Cow::Owned(b.iter().map(|b| format!("{b:02x}")).collect()),
2467            ValueRef::Json(j) => Cow::Owned(j.to_string()),
2468            ValueRef::None => Cow::Owned(Value::None.to_display_string()),
2469            ValueRef::Other(v) => Cow::Owned(v.to_display_string()),
2470        }
2471    }
2472
2473    /// The display form as an owned string.
2474    pub fn to_display_string(&self) -> String {
2475        self.display().into_owned()
2476    }
2477
2478    /// The JSON projection, exactly as [`Value::to_json_value`] gives it.
2479    pub fn to_json_value(&self) -> serde_json::Value {
2480        match self {
2481            ValueRef::U64(v) => serde_json::Value::from(*v),
2482            ValueRef::I64(v) => serde_json::Value::from(*v),
2483            ValueRef::F64(v) => serde_json::json!(*v),
2484            ValueRef::Bool(v) => serde_json::Value::from(*v),
2485            ValueRef::Str(s) => serde_json::Value::from(*s),
2486            ValueRef::Bytes(b) => {
2487                serde_json::Value::from(b.iter().map(|b| format!("{b:02x}")).collect::<String>())
2488            }
2489            ValueRef::Json(j) => (*j).clone(),
2490            ValueRef::None => Value::None.to_json_value(),
2491            ValueRef::Other(v) => v.to_json_value(),
2492        }
2493    }
2494}
2495
2496#[cfg(test)]
2497mod satisfies_slot_tests {
2498    use super::*;
2499
2500    /// A float node output rides its bit pattern in `Value::U64`
2501    /// (`Wire for f32` / `Wire for f16` inject it so), and a host may
2502    /// write the materialised `Value::F64` instead; a float slot
2503    /// accepts both, and a `U64` slot does not accept a float.
2504    #[test]
2505    fn float_slots_accept_the_bit_stuffed_and_materialised_forms() {
2506        let f32_bits = Value::U64(1.5f32.to_bits() as u64);
2507        let f16_bits = Value::U64(half::f16::from_f32(1.5).to_bits() as u64);
2508        assert!(f32_bits.satisfies_slot(PortType::F32));
2509        assert!(f16_bits.satisfies_slot(PortType::F16));
2510        assert!(Value::F64(1.5).satisfies_slot(PortType::F32));
2511        assert!(Value::F64(1.5).satisfies_slot(PortType::F16));
2512        assert!(!Value::F64(1.5).satisfies_slot(PortType::U64));
2513        assert!(!Value::Str("1.5".into()).satisfies_slot(PortType::F32));
2514    }
2515}