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