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