Skip to main content

polydat_core/
derive_support.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Trait surface that the `#[polydat_node]` proc-macro
5//! (`polydat-derive`) calls into for boxing / unboxing wire
6//! values.
7//!
8//! ## Canonical trait surface (library_catalog.md "Shapes")
9//!
10//! - [`Wire`] — `Sized + 'static` Rust-type ↔ [`Value`] bridge.
11//!   Owned types only; the macro recognises borrow shapes
12//!   (`&str`, `&[u8]`, `&[T]`, `&serde_json::Value`)
13//!   syntactically and emits direct `match`-on-`Value`
14//!   extraction at the eval call site — no trait dispatch, no
15//!   `unsafe` lifetime transmute.
16//!
17//! Combinator [`Wire`] impls cover [`Option<T>`] (`None`-aware
18//! pass-through) and [`Ext<T>`] (downcast through
19//! [`ReflectedValue`]).
20//!
21//! A `Const<T>` position is not a `Wire`: the macro classifies it
22//! syntactically into a `ConstShape` and emits the extraction from
23//! the `ConstArg` inline, so there is no trait for it to dispatch
24//! through.
25//!
26//! ## Why the trait surface lives here
27//!
28//! `polydat-derive` is a proc-macro crate — it can't define
29//! traits that are visible at the call site, only emit token
30//! streams referencing traits defined elsewhere. The macro
31//! emits `<T as polydat::derive_support::Wire>::extract(...)`
32//! paths; this module is what those paths resolve to.
33
34use std::sync::Arc;
35
36use crate::ast::SlotShape;
37use crate::ast::{PortType, ReflectedValue, SliceArc, Value};
38
39// =====================================================================
40// Wire — Rust-type ↔ Value bridge (owned types only)
41// =====================================================================
42
43/// Rust-type ↔ `Value` bridge.
44///
45/// Every owned Rust type the macro accepts in a wire position
46/// implements this trait. `PORT` is the static [`PortType`] the
47/// DSL type-checker uses to route a wire to this slot; which slots
48/// a value rides and how wide they are follows from that port type
49/// through [`SlotShape`], the one place that mapping lives. A second
50/// `JIT: Option<JitType>` const here said the same thing about the
51/// compiled buffer and nothing ever read it.
52///
53/// Borrow shapes (`&str`, `&[u8]`, `&[T]`,
54/// `&serde_json::Value`) and polymorphic `Value`-typed wires
55/// are NOT covered here — the macro recognises them
56/// syntactically and emits direct `match`-on-`Value` extraction
57/// at the eval call site. This keeps the trait surface free of
58/// lifetime parameters.
59///
60/// `extract` panics through [`extract_mismatch`] on a value its
61/// port type does not carry. The compiler's typing routes only
62/// well-typed `Value`s to each slot before `eval` runs, so the
63/// panic marks an internal error, never a workload error.
64pub trait Wire: Sized + 'static {
65    /// Static port type for the DSL type-checker.
66    const PORT: PortType;
67
68    /// Auto-resolver (library_catalog.md "Shapes", `Resolved<R, T>`)
69    /// for `Str`-typed upstream wires feeding this slot. `None`
70    /// (the default) disables auto-promotion; the workload must
71    /// supply the wire's actual port type directly. Set via the
72    /// [`Resolved<R, T>`] marker wrapper.
73    const RESOLVER: Option<crate::dsl::registry::DefaultResolver> = None;
74
75    /// Cost class for this wire (library_catalog.md "Wire cost classes").
76    /// Defaults to [`WireCost::Data`](crate::ast::WireCost::Data) (cheap per-cycle input).
77    /// Set to [`WireCost::Config`](crate::ast::WireCost::Config) via the [`Config<T>`] marker
78    /// wrapper to signal that the wire is rarely-changing and
79    /// the compiler should warn on cycle-time binding.
80    const WIRE_COST: crate::ast::WireCost = crate::ast::WireCost::Data;
81
82    /// Pull a typed value out of a `Value` wire.
83    fn extract(v: &Value) -> Self;
84
85    /// Push a typed value back into the `Value` outputs stream.
86    fn inject(self) -> Value;
87}
88
89/// The failure of a [`Wire::extract`] handed a value of a type its port
90/// does not carry. The compiler's typing routes only values of a port's
91/// type to that port, so reaching this is an internal error rather than
92/// a workload error. The message names the wire's Rust type, the port
93/// type, and the type of the value received; the engine that catches
94/// the panic adds the failing node's name (engines.md §3.4).
95#[cold]
96#[inline(never)]
97pub fn extract_mismatch(wire: &str, expected: PortType, got: &Value) -> ! {
98    panic!(
99        "Wire<{wire}>::extract: expected {expected}, got {}; the compiler's \
100         typing admits only {expected} to this port, so this is an internal error",
101        got.type_name()
102    )
103}
104
105/// Whether a value of port type `port`, reaching a compiled node
106/// through its own [`Wire`] impl, rides whole in a scratch entry: a
107/// handle, and the dataset values (`forms`, `fragment`,
108/// `admitted_rows`), each of which is one shared value with nothing to
109/// lay out in slots. The node macro asks this of a wire type it has no
110/// structural form for, and builds no compiled form over any other
111/// port.
112pub fn rides_whole(port: PortType) -> bool {
113    matches!(
114        port,
115        PortType::Handle | PortType::Forms | PortType::Fragment | PortType::AdmittedRows
116    )
117}
118
119// ── Scalar primitives ─────────────────────────────────────────
120
121impl Wire for u64 {
122    const PORT: PortType = PortType::U64;
123    fn extract(v: &Value) -> Self {
124        v.as_u64()
125    }
126    fn inject(self) -> Value {
127        Value::U64(self)
128    }
129}
130
131impl Wire for u32 {
132    const PORT: PortType = PortType::U32;
133    fn extract(v: &Value) -> Self {
134        v.as_u64() as u32
135    }
136    fn inject(self) -> Value {
137        Value::U64(self as u64)
138    }
139}
140
141impl Wire for i32 {
142    const PORT: PortType = PortType::I32;
143    // Lenient extract: an honest `Value::I64` (sign-extended I32
144    // storage convention) and the bit-stuffed `Value::U64` form that
145    // `inject` writes — same precedent as `Wire<bool>` accepting
146    // `U64(n != 0)`.
147    fn extract(v: &Value) -> Self {
148        v.as_i64() as i32
149    }
150    fn inject(self) -> Value {
151        Value::I64(self as i64)
152    }
153}
154
155impl Wire for i64 {
156    const PORT: PortType = PortType::I64;
157    // Lenient extract: see `Wire<i32>` note above.
158    fn extract(v: &Value) -> Self {
159        v.as_i64()
160    }
161    fn inject(self) -> Value {
162        Value::I64(self)
163    }
164}
165
166impl Wire for u8 {
167    const PORT: PortType = PortType::U8;
168    fn extract(v: &Value) -> Self {
169        v.as_u64() as u8
170    }
171    fn inject(self) -> Value {
172        Value::U64(self as u64)
173    }
174}
175
176impl Wire for u16 {
177    const PORT: PortType = PortType::U16;
178    fn extract(v: &Value) -> Self {
179        v.as_u64() as u16
180    }
181    fn inject(self) -> Value {
182        Value::U64(self as u64)
183    }
184}
185
186impl Wire for i8 {
187    const PORT: PortType = PortType::I8;
188    // Lenient extract through as_i64 (honest I64 or bit-stuffed
189    // U64), narrowed by truncation — sign survives
190    // because the storage convention is sign-extension.
191    fn extract(v: &Value) -> Self {
192        v.as_i64() as i8
193    }
194    fn inject(self) -> Value {
195        Value::I64(self as i64)
196    }
197}
198
199impl Wire for i16 {
200    const PORT: PortType = PortType::I16;
201    fn extract(v: &Value) -> Self {
202        v.as_i64() as i16
203    }
204    fn inject(self) -> Value {
205        Value::I64(self as i64)
206    }
207}
208
209impl Wire for u128 {
210    const PORT: PortType = PortType::U128;
211    // No named native lowering: a 128-bit value cannot ride the
212    // one-u64 JIT slot, so it crosses the compiled tiers as a limb
213    // pair (`Imm2`) and a node over it runs its closure on the
214    // closure tier and a slot call of its kit on the native engines
215    // (type_system_alignment.md §2). The two-slot ride is about the
216    // register, not about which engines carry the type — every one
217    // of them does, which `the_128_bit_carriers_agree_on_every_engine`
218    // pins.
219    fn extract(v: &Value) -> Self {
220        v.as_u128()
221    }
222    fn inject(self) -> Value {
223        Value::U128(crate::ast::Bits128::from_u128(self))
224    }
225}
226
227impl Wire for i128 {
228    const PORT: PortType = PortType::I128;
229    fn extract(v: &Value) -> Self {
230        v.as_i128()
231    }
232    fn inject(self) -> Value {
233        Value::I128(crate::ast::Bits128::from_i128(self))
234    }
235}
236
237// ── 128-bit register words (type_system_alignment.md §8.4 L2) ──
238//
239// The raw view extracts/injects the word itself; the lane-typed
240// `[T; N]` views extract through the free-bitcast rule (any
241// register view satisfies any register slot) and inject tagged
242// with their own lane typing.
243
244impl Wire for crate::ast::Bits128 {
245    const PORT: PortType = PortType::Reg128;
246    fn extract(v: &Value) -> Self {
247        v.as_reg_bits()
248    }
249    fn inject(self) -> Value {
250        Value::Reg128(self, crate::ast::RegLanes::Raw)
251    }
252}
253
254macro_rules! impl_wire_reg {
255    ($arr:ty, $port:ident, $view:ident, $to:ident, $from:ident) => {
256        impl Wire for $arr {
257            const PORT: PortType = PortType::$port;
258            fn extract(v: &Value) -> Self {
259                v.as_reg_bits().$to()
260            }
261            fn inject(self) -> Value {
262                Value::Reg128(
263                    crate::ast::Bits128::$from(self),
264                    crate::ast::RegLanes::$view,
265                )
266            }
267        }
268    };
269}
270
271impl_wire_reg!([i8; 16], RegI8x16, I8x16, lanes_i8, from_lanes_i8);
272impl_wire_reg!([i16; 8], RegI16x8, I16x8, lanes_i16, from_lanes_i16);
273impl_wire_reg!([i32; 4], RegI32x4, I32x4, lanes_i32, from_lanes_i32);
274impl_wire_reg!([i64; 2], RegI64x2, I64x2, lanes_i64, from_lanes_i64);
275impl_wire_reg!([half::f16; 8], RegF16x8, F16x8, lanes_f16, from_lanes_f16);
276impl_wire_reg!([f32; 4], RegF32x4, F32x4, lanes_f32, from_lanes_f32);
277impl_wire_reg!([f64; 2], RegF64x2, F64x2, lanes_f64, from_lanes_f64);
278
279impl Wire for f64 {
280    const PORT: PortType = PortType::F64;
281    fn extract(v: &Value) -> Self {
282        v.as_f64()
283    }
284    fn inject(self) -> Value {
285        Value::F64(self)
286    }
287}
288
289impl Wire for f32 {
290    const PORT: PortType = PortType::F32;
291    fn extract(v: &Value) -> Self {
292        f32::from_bits(v.as_u64() as u32)
293    }
294    fn inject(self) -> Value {
295        Value::U64(self.to_bits() as u64)
296    }
297}
298
299impl Wire for half::f16 {
300    const PORT: PortType = PortType::F16;
301    // Same bit-stuffing convention as f32: the binary16 pattern
302    // rides the low 16 bits of the u64 carrier.
303    fn extract(v: &Value) -> Self {
304        half::f16::from_bits(v.as_u64() as u16)
305    }
306    fn inject(self) -> Value {
307        Value::U64(self.to_bits() as u64)
308    }
309}
310
311impl Wire for bool {
312    const PORT: PortType = PortType::Bool;
313    fn extract(v: &Value) -> Self {
314        match v {
315            Value::Bool(b) => *b,
316            Value::U64(n) => *n != 0,
317            other => extract_mismatch("bool", Self::PORT, other),
318        }
319    }
320    fn inject(self) -> Value {
321        Value::Bool(self)
322    }
323}
324
325impl Wire for String {
326    const PORT: PortType = PortType::Str;
327    fn extract(v: &Value) -> Self {
328        // A non-Str input is an internal error, not a coercion
329        // opportunity. Nodes that want a display rendering of an
330        // arbitrary `Value` take a `Value`-typed (PolyWire) arg
331        // instead.
332        match v {
333            Value::Str(s) => s.to_string(),
334            other => extract_mismatch("String", Self::PORT, other),
335        }
336    }
337    fn inject(self) -> Value {
338        Value::Str(self.into())
339    }
340}
341
342/// `Arc<str>` — zero-copy shared string handle. Reading
343/// extracts the existing `Arc<str>` from `Value::Str` (refcount
344/// bump only); injecting wraps directly. Nodes whose hot path
345/// emits the same string per cycle (lookup table outputs,
346/// fixed-value selectors) should use this instead of `String`
347/// to avoid the per-cycle `to_string()` allocation.
348impl Wire for std::sync::Arc<str> {
349    const PORT: PortType = PortType::Str;
350    fn extract(v: &Value) -> Self {
351        match v {
352            Value::Str(s) => s.clone(),
353            other => extract_mismatch("Arc<str>", Self::PORT, other),
354        }
355    }
356    fn inject(self) -> Value {
357        Value::Str(self)
358    }
359}
360
361/// `Arc<dyn Any + Send + Sync>` — opaque Handle wire. The body
362/// receives the runtime-typed handle directly; downcast is the
363/// operator's responsibility. Use [`Resolved<R, T>`] when the
364/// node wants a typed Handle with source-string auto-promotion; use this raw shape when the body
365/// needs to handle multiple inner types via runtime dispatch.
366impl Wire for std::sync::Arc<dyn std::any::Any + Send + Sync> {
367    const PORT: PortType = PortType::Handle;
368    fn extract(v: &Value) -> Self {
369        match v {
370            Value::Handle(arc) => arc.clone(),
371            other => extract_mismatch("Arc<dyn Any>", Self::PORT, other),
372        }
373    }
374    fn inject(self) -> Value {
375        Value::Handle(self)
376    }
377}
378
379/// `Box<dyn ReflectedValue>` — Ext (adapter-typed) wire with
380/// dynamic downcast left to the body. Use [`Ext<T>`] when the
381/// inner type is known at codegen; use this when a node needs
382/// to dispatch on the runtime ReflectedValue::type_name.
383impl Wire for Box<dyn ReflectedValue> {
384    const PORT: PortType = PortType::Ext;
385    fn extract(v: &Value) -> Self {
386        match v {
387            Value::Ext(b) => b.clone_reflected(),
388            other => extract_mismatch("Box<dyn ReflectedValue>", Self::PORT, other),
389        }
390    }
391    fn inject(self) -> Value {
392        Value::Ext(self)
393    }
394}
395
396// ── Bytes ──────────────────────────────────────────────────────
397
398impl Wire for Arc<[u8]> {
399    const PORT: PortType = PortType::Bytes;
400    fn extract(v: &Value) -> Self {
401        match v {
402            Value::Bytes(b) => b.clone(),
403            other => extract_mismatch("Arc<[u8]>", Self::PORT, other),
404        }
405    }
406    fn inject(self) -> Value {
407        Value::Bytes(self)
408    }
409}
410
411impl Wire for Vec<u8> {
412    const PORT: PortType = PortType::Bytes;
413    fn extract(v: &Value) -> Self {
414        match v {
415            Value::Bytes(b) => b.to_vec(),
416            other => extract_mismatch("Vec<u8>", Self::PORT, other),
417        }
418    }
419    fn inject(self) -> Value {
420        Value::Bytes(self.into())
421    }
422}
423
424// ── Json ───────────────────────────────────────────────────────
425
426impl Wire for Arc<serde_json::Value> {
427    const PORT: PortType = PortType::Json;
428    fn extract(v: &Value) -> Self {
429        match v {
430            Value::Json(j) => j.clone(),
431            other => extract_mismatch("Arc<Json>", Self::PORT, other),
432        }
433    }
434    fn inject(self) -> Value {
435        Value::Json(self)
436    }
437}
438
439// ── Typed-element vectors ──────────────────────────────────────
440
441macro_rules! impl_wire_vec {
442    ($elem:ty, $variant:ident, $port:ident) => {
443        impl Wire for SliceArc<$elem> {
444            const PORT: PortType = PortType::$port;
445            fn extract(v: &Value) -> Self {
446                match v {
447                    Value::$variant(arc) => arc.clone(),
448                    other => extract_mismatch(
449                        concat!("SliceArc<", stringify!($elem), ">"),
450                        Self::PORT,
451                        other,
452                    ),
453                }
454            }
455            fn inject(self) -> Value {
456                Value::$variant(self)
457            }
458        }
459
460        impl Wire for Vec<$elem> {
461            const PORT: PortType = PortType::$port;
462            fn extract(v: &Value) -> Self {
463                match v {
464                    Value::$variant(arc) => arc.as_slice().to_vec(),
465                    other => {
466                        extract_mismatch(concat!("Vec<", stringify!($elem), ">"), Self::PORT, other)
467                    }
468                }
469            }
470            fn inject(self) -> Value {
471                Value::$variant(SliceArc::from_vec(self))
472            }
473        }
474    };
475}
476
477impl_wire_vec!(f32, VecF32, VecF32);
478impl_wire_vec!(i32, VecI32, VecI32);
479impl_wire_vec!(f64, VecF64, VecF64);
480impl_wire_vec!(i64, VecI64, VecI64);
481impl_wire_vec!(half::f16, VecF16, VecF16);
482impl_wire_vec!(i16, VecI16, VecI16);
483impl_wire_vec!(i8, VecI8, VecI8);
484
485// ── Combinators ────────────────────────────────────────────────
486
487/// None-aware wire combinator. Macro auto-emits
488/// `accepts_none_inputs() -> true` when any arg is `Option<_>`.
489impl<T: Wire> Wire for Option<T> {
490    const PORT: PortType = T::PORT;
491    fn extract(v: &Value) -> Self {
492        match v {
493            Value::None => None,
494            _ => Some(T::extract(v)),
495        }
496    }
497    fn inject(self) -> Value {
498        match self {
499            None => Value::None,
500            Some(t) => t.inject(),
501        }
502    }
503}
504
505/// Operator-side wrapper for adapter-typed wire arguments.
506/// `Ext<T>` signals "this arg comes from `Value::Ext(Box<dyn
507/// ReflectedValue>)`; downcast it to `T`." Implements `Deref` /
508/// `DerefMut` like [`Const<T>`] so the body can use `.method()`
509/// directly.
510#[derive(Clone)]
511pub struct Ext<T>(pub T);
512
513impl<T> std::ops::Deref for Ext<T> {
514    type Target = T;
515    fn deref(&self) -> &T {
516        &self.0
517    }
518}
519
520impl<T> std::ops::DerefMut for Ext<T> {
521    fn deref_mut(&mut self) -> &mut T {
522        &mut self.0
523    }
524}
525
526impl<T: ReflectedValue + Clone + 'static> Wire for Ext<T> {
527    const PORT: PortType = PortType::Ext;
528    fn extract(v: &Value) -> Self {
529        match v {
530            Value::Ext(boxed) => {
531                let any = boxed.as_any();
532                match any.downcast_ref::<T>() {
533                    Some(t) => Ext(t.clone()),
534                    None => panic!(
535                        "Wire<Ext<{}>>::extract: ReflectedValue downcast failed; \
536                         got runtime type {:?}",
537                        std::any::type_name::<T>(),
538                        boxed.type_name()
539                    ),
540                }
541            }
542            other => extract_mismatch(std::any::type_name::<Self>(), Self::PORT, other),
543        }
544    }
545    fn inject(self) -> Value {
546        Value::Ext(Box::new(self.0))
547    }
548}
549
550// ── DynamicOutputs<T> — variable output port count ────────────
551
552/// Marker wrapper for node return types whose output port
553/// COUNT is determined at construction time from a
554/// const-list arg's length, not at codegen time.
555/// This return shape (library_catalog.md "Shapes") covers nodes like `mixed_radix`
556/// that emit one output per radix where `radix` count is a
557/// workload-supplied list.
558///
559/// Operator writes:
560///
561/// ```ignore
562/// #[polydat_node(category = Arithmetic)]
563/// fn mixed_radix(
564///     value: u64,
565///     radixes: Const<&[u64]>,
566/// ) -> DynamicOutputs<u64> {
567///     // body returns DynamicOutputs(Vec<u64>) with len == radixes.len()
568/// }
569/// ```
570///
571/// The macro emits one output port per element (named `d0`,
572/// `d1`, ...) at construction time using the const-list
573/// arg's length. `FuncSig.outputs` is `0` signalling dynamic.
574/// Requires exactly one const-list arg per function — `Const<&[C]>`
575/// or its owned spelling `Const<Vec<C>>` — and the
576/// macro errors at compile time otherwise.
577pub struct DynamicOutputs<T>(pub Vec<T>);
578
579impl<T> std::ops::Deref for DynamicOutputs<T> {
580    type Target = Vec<T>;
581    fn deref(&self) -> &Vec<T> {
582        &self.0
583    }
584}
585
586// ── Config<T> — wire arg marked as config-cost ────────────────
587
588/// Marker wrapper signalling that the wrapped wire is a
589/// configuration input — expensive to change because the node
590/// keeps internal state (LUTs, alias tables, parsed specs)
591/// derived from it. The macro emits the matching slot with
592/// `Port::config()` (library_catalog.md "Wire cost classes") so the
593/// compiler warns on cycle-time binding.
594///
595/// The operator declares the cost intent through the type system
596/// rather than an arg-level attribute. Body unwraps with `.0` or via `Deref`.
597pub struct Config<T>(pub T);
598
599impl<T> std::ops::Deref for Config<T> {
600    type Target = T;
601    fn deref(&self) -> &T {
602        &self.0
603    }
604}
605
606impl<T: Wire> Wire for Config<T> {
607    const PORT: PortType = T::PORT;
608    const RESOLVER: Option<crate::dsl::registry::DefaultResolver> = T::RESOLVER;
609    const WIRE_COST: crate::ast::WireCost = crate::ast::WireCost::Config;
610    fn extract(v: &Value) -> Self {
611        Config(T::extract(v))
612    }
613    fn inject(self) -> Value {
614        self.0.inject()
615    }
616}
617
618// ── Resolved<R, T> — Handle wire with an auto-resolver ────────
619
620/// A Handle wire that declares its default resolver through its
621/// type (library_catalog.md "Shapes"). The `R` parameter (a [`ResolverKind`] impl) carries
622/// the auto-resolver kind; the `T` parameter is the concrete
623/// `Handle`-inner type the body sees.
624///
625/// Operators write:
626///
627/// ```ignore
628/// fn matching_profiles(
629///     group: Resolved<GroupResolver, DatasetHandle>,
630///     prefix: &str,
631/// ) -> Vec<String> {
632///     let group: &TestDataGroup = group.resolve_group();
633///     // ... use group methods directly
634/// }
635/// ```
636///
637/// The macro reads `<Resolved<GroupResolver, T> as Wire>::RESOLVER`
638/// at codegen time and emits the matching `FuncSig.default_resolver`.
639/// No `#[polydat_node(default_resolver = ...)]` attribute is
640/// involved — the resolver information lives in the function
641/// signature where it belongs.
642pub struct Resolved<R: ResolverKind, T: 'static + Send + Sync> {
643    inner: std::sync::Arc<T>,
644    _r: std::marker::PhantomData<fn() -> R>,
645}
646
647impl<R: ResolverKind, T: 'static + Send + Sync> std::ops::Deref for Resolved<R, T> {
648    type Target = T;
649    fn deref(&self) -> &T {
650        &self.inner
651    }
652}
653
654impl<R: ResolverKind, T: 'static + Send + Sync> Resolved<R, T> {
655    /// Construct from a pre-resolved Arc — useful for tests
656    /// and programmatic graph assembly that bypasses the DSL
657    /// auto-resolver.
658    pub fn from_arc(inner: std::sync::Arc<T>) -> Self {
659        Self {
660            inner,
661            _r: std::marker::PhantomData,
662        }
663    }
664    /// Borrow the inner Arc.
665    pub fn as_arc(&self) -> &std::sync::Arc<T> {
666        &self.inner
667    }
668}
669
670/// Marker trait that names a kind of source-string auto-resolver
671/// for [`Resolved<R, T>`] wire args. The variants here mirror
672/// [`crate::dsl::registry::DefaultResolver`]; each impl picks
673/// one of them.
674pub trait ResolverKind: 'static {
675    /// The resolver this kind names.
676    const RESOLVER: crate::dsl::registry::DefaultResolver;
677}
678
679/// Splice `dataset_group_open(<source>)` upstream when the wire
680/// source is a `Str` (`DefaultResolver::Group`).
681pub struct GroupResolver;
682impl ResolverKind for GroupResolver {
683    const RESOLVER: crate::dsl::registry::DefaultResolver =
684        crate::dsl::registry::DefaultResolver::Group;
685}
686
687impl<R: ResolverKind, T: 'static + Send + Sync> Wire for Resolved<R, T> {
688    const PORT: PortType = PortType::Handle;
689    const RESOLVER: Option<crate::dsl::registry::DefaultResolver> =
690        Some(<R as ResolverKind>::RESOLVER);
691    fn extract(v: &Value) -> Self {
692        match v {
693            Value::Handle(arc) => {
694                let inner = arc.clone().downcast::<T>().unwrap_or_else(|_| {
695                    panic!(
696                        "Wire<Resolved<_, {}>>::extract: Handle downcast failed",
697                        std::any::type_name::<T>()
698                    )
699                });
700                Resolved {
701                    inner,
702                    _r: std::marker::PhantomData,
703                }
704            }
705            // The common fault, and the one worth naming: an
706            // upstream open did not resolve, so the handle this
707            // node reads is absent rather than wrong.
708            Value::None => panic!(
709                "a resolved handle is None — the upstream open failed to \
710                 resolve. The audit log carries the underlying error and \
711                 the name it was opening: a catalog miss, a facet missing \
712                 on disk, or a transport failure. This is the most common \
713                 fault when a workload runs on a system whose catalog is \
714                 not configured for the source it asks for."
715            ),
716            other => extract_mismatch(std::any::type_name::<Self>(), Self::PORT, other),
717        }
718    }
719    fn inject(self) -> Value {
720        Value::Handle(self.inner)
721    }
722}
723
724// The `#[polydat_node]` macro dispatches every owned type through
725// `<T as Wire>::extract` / `::inject` and emits direct
726// `match`-on-`Value` extraction for borrow shapes (`&str`, `&[u8]`,
727// `&[T]`, `&serde_json::Value`), with no lifetime transmute.
728
729/// Marker wrapper for const arguments in
730/// `#[polydat_node]` function signatures.
731///
732/// Use in arg position to signal that the value is captured at
733/// node-construction time (assembly-time) rather than read
734/// per-cycle from a wire. The macro detects `Const<T>` in arg
735/// position and:
736///
737/// - Emits `Slot::Const { ... }` (not `Slot::Wire`) in the
738///   node's NodeMeta.
739/// - Emits `SlotType::ConstU64` / `ConstF64` / `ConstStr` in
740///   the corresponding `FuncSig.params` entry (the const
741///   variant matching `T`).
742/// - Adds a struct field to hold the captured value.
743/// - Generates a `new(const_values...)` constructor.
744/// - Wires the build closure to pull from `consts: &[ConstArg]`
745///   and pass values to `new()`.
746/// - Constructs a `Const<T>(...)` wrapper around the struct
747///   field at eval time so the user's function body sees the
748///   wrapped type matching its signature.
749///
750/// Body code accesses the wrapped value via `.0` or via the
751/// `Deref` impl below:
752///
753/// ```ignore
754/// #[polydat_node(category = String)]
755/// fn combinations(input: u64, pattern: Const<&str>) -> String {
756///     apply(input, pattern.0)  // pattern.0 is &str
757/// }
758/// ```
759///
760/// Type-shape dispatch table:
761///
762/// | `Const<T>` form | `SlotType` variant | Struct field type | ConstArg accessor |
763/// |---|---|---|---|
764/// | `Const<u64>`  | `ConstU64`  | `u64`    | `as_u64()`  |
765/// | `Const<f64>`  | `ConstF64`  | `f64`    | `as_f64()`  |
766/// | `Const<bool>` | `ConstU64`  | `bool`   | `as_u64() != 0` |
767/// | `Const<&str>` | `ConstStr`  | `String` | `as_str().to_string()` |
768pub struct Const<T>(pub T);
769
770impl<T> std::ops::Deref for Const<T> {
771    type Target = T;
772    fn deref(&self) -> &T {
773        &self.0
774    }
775}
776
777impl<T> std::ops::DerefMut for Const<T> {
778    fn deref_mut(&mut self) -> &mut T {
779        &mut self.0
780    }
781}
782
783/// Construction-time setup contract for nodes
784/// that derive a pre-computed runtime state from their const
785/// args (e.g. `combinations` parsing a charset pattern into
786/// segments + modulus, `regex_match` compiling a pattern,
787/// `histribution` parsing a distribution spec).
788///
789/// **The contract**: the operator-provided setup function is
790/// called EXACTLY ONCE per node instance, at construction time
791/// (`new()`). Its result is stored in a struct field; eval-
792/// time access is a plain `&T` borrow.
793///
794/// **Type-level enforcement**: the `#[poly_const(...)]`
795/// attribute on a `&T` argument tells the macro to generate
796/// this construction pattern. The macro is the sole party
797/// emitting `setup_fn(...)` calls and it generates the call
798/// exactly once inside `new()`. The contract is inviolable
799/// because no other code path can reach the setup function —
800/// the macro hides it inside the constructor.
801///
802/// In effect, the function pointer behaves as `FnOnce` —
803/// invoked one time, by one site, never again. The FnOnce
804/// semantics aren't expressed as a trait bound because they
805/// don't need to be: the macro is the only caller, and the
806/// macro respects single-call by construction.
807///
808/// Library author idiom:
809///
810/// ```ignore
811/// pub struct ParsedPattern {
812///     pub segments: Vec<Segment>,
813///     pub modulus: u64,
814/// }
815///
816/// impl ParsedPattern {
817///     /// Single-call setup. Macro invokes once in `new()`.
818///     fn from_pattern(pattern: &str) -> Self { /* parse */ }
819/// }
820///
821/// #[polydat_node(category = String)]
822/// fn combinations(
823///     input: u64,
824///     pattern: Const<&str>,
825///     #[poly_const(ParsedPattern::from_pattern, from = pattern)]
826///     parsed: &ParsedPattern,
827/// ) -> String {
828///     // parsed is a borrow of the cached struct field —
829///     // no recomputation, no clone, no ceremony at the call site.
830///     let mut r = input % parsed.modulus;
831///     /* ... */
832/// }
833/// ```
834///
835/// Marker trait — purely a documentation handle for types
836/// intended to be polydat-setup targets. The macro doesn't
837/// dispatch on this; the attribute is the dispatch surface.
838/// Implementing the trait gives library authors a way to
839/// signal intent and improve `cargo doc` discoverability.
840pub trait PolydatSetup {}
841
842// ── The slot kit's run-time helpers ──────────────────────────────
843// Called by the closures `#[polydat_node]` emits for its `compiled_slot`
844// kit; public because generated code in other crates calls them, not
845// because hosts should.
846
847/// The value a `Ref2` pair at the head of `slots` holds by reference:
848/// the one-element slice a JSON, extension, or handle producer
849/// published (jit_boundary.md, axiom S7: one dereference).
850///
851/// The slots must hold a pair a producer published into storage that
852/// is alive: its own scratch, an extern's stored value, or a boundary
853/// value alive for the call (axioms S3, S4). A pair of length zero,
854/// an unset extern, reads as [`Value::None`].
855#[inline]
856pub fn ref_value(slots: &[u64]) -> &Value {
857    static NONE: Value = Value::None;
858    if slots.get(1).copied().unwrap_or(0) == 0 {
859        return &NONE;
860    }
861    // SAFETY: as documented; the producer's storage outlives the read.
862    unsafe { &*(slots[0] as usize as *const Value) }
863}
864
865/// An empty buffer with room for `n` elements, for a node whose buffer
866/// size comes from a *value* — a wire, a constant, or arithmetic on
867/// either.
868///
869/// `Vec::with_capacity(n as usize)` is the obvious spelling and it is
870/// wrong twice over for a value the node did not choose. A size the
871/// machine cannot hold makes the allocator **abort the process**, which
872/// no `catch_unwind` sees: not an error on the program that asked, but
873/// the host gone. And `as usize` truncates on a 32-bit target, so a
874/// large size silently becomes a small one. Here a size that does not
875/// fit `usize`, or cannot be reserved, is a failure of the node like
876/// any other — caught, attributed to the node and its inputs, and the
877/// same on every engine.
878///
879/// There is no cap. A size that *can* be allocated is allocated, however
880/// slow filling it is; how large a string a host asks for is the host's
881/// business. What this refuses is only what could never have
882/// succeeded. Arithmetic on a size belongs in `u64` with
883/// `saturating_add`, so an overflow reaches here as a size that cannot
884/// be reserved rather than wrapping to a small one first.
885pub fn buffer_for<T>(n: u64, what: &str) -> Vec<T> {
886    try_buffer_for(n, what).unwrap_or_else(|e| panic!("{e}"))
887}
888
889/// [`buffer_for`] for a caller that reports failure as a value rather
890/// than as a node's panic: a spec parser or a compile step, whose size
891/// comes from program text. The error is the same sentence.
892pub fn try_buffer_for<T>(n: u64, what: &str) -> Result<Vec<T>, String> {
893    let mut v = Vec::new();
894    match usize::try_from(n) {
895        Ok(k) if v.try_reserve_exact(k).is_ok() => Ok(v),
896        _ => Err(size_refusal(n, what)),
897    }
898}
899
900/// [`buffer_for`] for text: an empty `String` with room for `n` bytes.
901pub fn string_for(n: u64, what: &str) -> String {
902    let mut s = String::new();
903    match usize::try_from(n) {
904        Ok(n) if s.try_reserve_exact(n).is_ok() => s,
905        _ => refuse_size(n, what),
906    }
907}
908
909/// [`buffer_for`] for a buffer that is reused across evaluations:
910/// `out` is cleared and then has room for `n` elements. A native
911/// producer writing into step-owned scratch takes this shape, so its
912/// refusal reads the same as the node's.
913pub fn reserve_for<T>(out: &mut Vec<T>, n: u64, what: &str) {
914    out.clear();
915    match usize::try_from(n) {
916        Ok(n) if out.try_reserve_exact(n).is_ok() => {}
917        _ => refuse_size(n, what),
918    }
919}
920
921#[cold]
922fn refuse_size(n: u64, what: &str) -> ! {
923    panic!("{}", size_refusal(n, what))
924}
925
926fn size_refusal(n: u64, what: &str) -> String {
927    format!("{what}: a buffer of {n} elements cannot be allocated on this machine")
928}
929
930/// A polymorphic port's slots as the owned `Value` the wire type
931/// names: a scalar from its bits, a `Ref2` kind copied out of the
932/// pair its producer published.
933#[inline]
934pub fn read_poly(ty: PortType, slots: &[u64]) -> Value {
935    crate::compile::marshal::decode_slot(slots, ty)
936}
937
938/// A polymorphic return written by the node's resolved output type: a
939/// scalar as its bits into `outputs[0]`, a `Ref2` kind into
940/// `scratch[0]` with its pair republished (axiom S3). The value must
941/// be the port type's carrier: the graph colored the slot by the
942/// node's resolved output type, and a value of another type would be
943/// read by every consumer as something it is not, where the
944/// interpreter would have carried it. A `None` has no slot form on a
945/// compiled engine (engines.md §3.3).
946///
947/// The comparison is with the carrier, not the port type, because a
948/// `u32` or `f32` value *is* a `U64` in flight. Comparing with the port
949/// type refused every narrow integer and small float that reached a
950/// polymorphic node, on every compiled engine.
951#[inline]
952pub fn write_poly(
953    ty: PortType,
954    v: Value,
955    scratch: &mut [crate::ast::ScratchBuf],
956    outputs: &mut [u64],
957) {
958    // A `Dyn` port carries any value as written (input_variance.md).
959    if ty != PortType::Dyn && v.port_type() != crate::compile::marshal::carrier_port(ty) {
960        panic!(
961            "a node produced a {:?} on an output the graph typed {:?}; a compiled engine \
962             cannot carry a value of another type than the slot's (engines.md §3.4)",
963            v.port_type(),
964            ty
965        );
966    }
967    // The slot form is a property of the *type*, and the type is
968    // resolved: `ty` is what the graph coloured this output. So the
969    // write is chosen by the colour, of which there are three, rather
970    // than by the value's variant — a match over `Value` has to be
971    // extended every time the language grows a carrier, and a missing
972    // arm is not a compile error but a panic at the first pull. This
973    // one went through three rounds of that: the by-reference singles,
974    // then the numeric vectors, then the 128-bit words.
975    match ty.slot_color() {
976        // One slot of immediate data: the carrier's bits.
977        crate::ast::SlotColor::Imm1 => outputs[0] = carrier_slot_bits(&v),
978        // Two slots of immediate limb data, low word first
979        // (`Bits128`), which is what every 128-bit and register value
980        // is underneath.
981        crate::ast::SlotColor::Imm2 => {
982            // `as_reg_bits` is the register reading and refuses a
983            // 128-bit integer, so the limbs are taken from whichever
984            // two-slot carrier this is.
985            let words = match v {
986                Value::U128(b) | Value::I128(b) | Value::Reg128(b, _) => b.0,
987                other => unreachable!("a {:?} is not a two-slot carrier", other.port_type()),
988            };
989            outputs[0] = words[0];
990            outputs[1] = words[1];
991        }
992        // A (ptr, len) pair into the step's own scratch entry. Filling
993        // the entry can move its buffer, so the pair is republished
994        // every time — a slot left pointing at the old allocation is
995        // what the S9 validator catches (axiom S9(a)).
996        crate::ast::SlotColor::Ref2 => {
997            scratch[0].set_from_value(&v);
998            let (p, l) = scratch[0].ptr_len();
999            outputs[0] = p;
1000            outputs[1] = l;
1001        }
1002    }
1003}
1004
1005/// The slot bits of a one-slot carrier.
1006///
1007/// `Value::None` has no slot form on a compiled engine (engines.md
1008/// §3.3); it never reaches here, because an unset output is tracked
1009/// beside the buffer rather than written into it.
1010#[inline]
1011fn carrier_slot_bits(v: &Value) -> u64 {
1012    match v {
1013        Value::U64(x) => *x,
1014        Value::I64(x) => *x as u64,
1015        Value::F64(x) => x.to_bits(),
1016        Value::Bool(b) => *b as u64,
1017        other => panic!(
1018            "a {:?} value is not a one-slot carrier; the graph coloured its output Imm1",
1019            other.port_type()
1020        ),
1021    }
1022}
1023
1024// Macro-generated nodes register through the `NodeRegistration`
1025// inventory channel (`polydat::dsl::registry::NodeRegistration`,
1026// library_catalog.md "Registration"), the same channel
1027// `register_nodes!` uses. The proc-macro
1028// emits a `NodeRegistration` per `#[polydat_node]` site, so
1029// every consumer that already iterates the registry
1030// (`registry()`, `lookup()`, the compile pipeline's
1031// `factory::build_node`) sees macro-generated nodes
1032// automatically — no parallel collection, no separate dispatch
1033// surface. See `polydat::dsl::registry` for the load-bearing
1034// data structures.
1035
1036#[cfg(test)]
1037mod tests {
1038    use super::*;
1039
1040    fn refusal(f: impl FnOnce() + std::panic::UnwindSafe) -> String {
1041        let err = std::panic::catch_unwind(f).expect_err("the size must be refused");
1042        err.downcast_ref::<String>().cloned().unwrap_or_default()
1043    }
1044
1045    /// A size no machine can hold is a caught failure naming the node,
1046    /// not an allocator abort that takes the host down with it.
1047    #[test]
1048    fn an_impossible_size_is_refused_not_aborted() {
1049        let m = refusal(|| drop(buffer_for::<u32>(u64::MAX, "probe")));
1050        assert!(
1051            m.starts_with("probe: a buffer of 18446744073709551615"),
1052            "{m}"
1053        );
1054        let m = refusal(|| drop(string_for((1 << 53) + 1, "probe")));
1055        assert!(m.contains("cannot be allocated"), "{m}");
1056        let m = refusal(|| reserve_for(&mut vec![1.0f32; 4], u64::MAX, "probe"));
1057        assert!(m.contains("cannot be allocated"), "{m}");
1058    }
1059
1060    #[derive(Debug, Clone)]
1061    struct Probe;
1062    impl ReflectedValue for Probe {
1063        fn type_name(&self) -> &str {
1064            "probe"
1065        }
1066        fn display(&self) -> String {
1067            "probe".into()
1068        }
1069        fn as_any(&self) -> &dyn std::any::Any {
1070            self
1071        }
1072        fn clone_reflected(&self) -> Box<dyn ReflectedValue> {
1073            Box::new(self.clone())
1074        }
1075    }
1076
1077    /// A value of every port type, as its producer's `Wire` impl would
1078    /// carry it. The match has no wildcard, so a type added to the
1079    /// language does not compile here until it has an arm. `None` for
1080    /// a dataset type that has no value to make here: `forms` and
1081    /// `fragment` values exist only over a dataset's records, and no
1082    /// dataset value exists at all without the `vectordata` feature.
1083    /// Those are read back on every engine against real datasets
1084    /// (`tests/dataset_values.rs`).
1085    fn sample(ty: PortType) -> Option<Value> {
1086        Some(match ty {
1087            PortType::Forms | PortType::Fragment => return None,
1088            #[cfg(feature = "vectordata")]
1089            PortType::AdmittedRows => {
1090                use crate::derive_support::Wire;
1091                crate::dataset_value::Shared(Arc::new(
1092                    vectordata::ground_truth::OrdinalSet::from_ordinals(&[1, 4, 9]),
1093                ))
1094                .inject()
1095            }
1096            #[cfg(not(feature = "vectordata"))]
1097            PortType::AdmittedRows => return None,
1098            other => plain_sample(other),
1099        })
1100    }
1101
1102    /// A value of a port type whose values need no dataset.
1103    fn plain_sample(ty: PortType) -> Value {
1104        use crate::ast::{Bits128, RegLanes};
1105        let limbs = Bits128([0x0123_4567_89ab_cdef, 0xfedc_ba98_7654_3210]);
1106        let reg = |lanes| Value::Reg128(limbs, lanes);
1107        match ty {
1108            PortType::U64 | PortType::U32 | PortType::U16 | PortType::U8 => Value::U64(200),
1109            PortType::F32 => Value::U64(1.5f32.to_bits() as u64),
1110            PortType::F16 => Value::U64(half::f16::from_f32(1.5).to_bits() as u64),
1111            PortType::I64 | PortType::I32 | PortType::I16 | PortType::I8 => Value::I64(-7),
1112            PortType::F64 => Value::F64(-2.25),
1113            PortType::Bool => Value::Bool(true),
1114            PortType::U128 => Value::U128(limbs),
1115            PortType::I128 => Value::I128(limbs),
1116            PortType::Reg128 => reg(RegLanes::Raw),
1117            PortType::RegI8x16 => reg(RegLanes::I8x16),
1118            PortType::RegI16x8 => reg(RegLanes::I16x8),
1119            PortType::RegI32x4 => reg(RegLanes::I32x4),
1120            PortType::RegI64x2 => reg(RegLanes::I64x2),
1121            PortType::RegF16x8 => reg(RegLanes::F16x8),
1122            PortType::RegF32x4 => reg(RegLanes::F32x4),
1123            PortType::RegF64x2 => reg(RegLanes::F64x2),
1124            PortType::Str => Value::Str("héllo".into()),
1125            PortType::Bytes => Value::Bytes(vec![0u8, 1, 255].into()),
1126            PortType::Json => Value::Json(Arc::new(serde_json::json!({"k": [1, 2]}))),
1127            PortType::Ext => Value::Ext(Box::new(Probe)),
1128            PortType::Handle => Value::Handle(Arc::new(42u32)),
1129            PortType::VecF32 => Value::VecF32(SliceArc::from_vec(vec![1.0, -0.5])),
1130            PortType::VecI32 => Value::VecI32(SliceArc::from_vec(vec![-3, 4])),
1131            PortType::VecF64 => Value::VecF64(SliceArc::from_vec(vec![1e300, -0.0])),
1132            PortType::VecI64 => Value::VecI64(SliceArc::from_vec(vec![i64::MIN, 9])),
1133            PortType::VecF16 => Value::VecF16(SliceArc::from_vec(vec![half::f16::from_f32(0.5)])),
1134            PortType::VecI16 => Value::VecI16(SliceArc::from_vec(vec![-300i16, 300])),
1135            PortType::VecI8 => Value::VecI8(SliceArc::from_vec(vec![-8i8, 8])),
1136            // A `Dyn` port carries a value of any type, as written.
1137            PortType::Dyn => Value::Str("any".into()),
1138            PortType::Forms | PortType::Fragment | PortType::AdmittedRows => {
1139                unreachable!("{ty}: a dataset type, sampled by `sample`")
1140            }
1141        }
1142    }
1143
1144    /// Reading a polymorphic port inverts writing one, for every port
1145    /// type the language has: what a polymorphic node returns is what
1146    /// the next polymorphic node takes, on every compiled engine.
1147    ///
1148    /// A register reaching a polymorphic node's input arrives whole,
1149    /// with its limbs reassembled as the host's output read reassembles
1150    /// them, not as its low limb typed `U64`
1151    /// (`log_warn(reg_splat_f64(..))` is the case).
1152    #[test]
1153    fn every_port_type_reads_back_what_was_written() {
1154        for &ty in PortType::ALL {
1155            let Some(v) = sample(ty) else { continue };
1156            // A `Dyn` port carries a value of any type, as written.
1157            if ty != PortType::Dyn {
1158                assert_eq!(
1159                    v.port_type(),
1160                    crate::compile::marshal::carrier_port(ty),
1161                    "{ty:?}: the sample is not what the port carries"
1162                );
1163            }
1164            let mut scratch: Vec<crate::ast::ScratchBuf> = ty
1165                .scratch_elem()
1166                .map(crate::ast::ScratchBuf::new)
1167                .into_iter()
1168                .collect();
1169            let mut slots = [0u64; 2];
1170            // Written as the macro writes it: by the port's resolved
1171            // type, which for a narrow or float-in-carrier type is not
1172            // the port type of the carrier value its `Wire` impl injects.
1173            write_poly(ty, v.clone(), &mut scratch, &mut slots);
1174            let back = read_poly(ty, &slots[..ty.slot_width()]);
1175            assert_eq!(back, v, "{ty:?}");
1176        }
1177    }
1178
1179    /// A size that fits is reserved exactly, and a reused buffer comes
1180    /// back cleared.
1181    #[test]
1182    fn a_feasible_size_is_reserved() {
1183        let v: Vec<u8> = buffer_for(1000, "probe");
1184        assert!(v.is_empty() && v.capacity() >= 1000);
1185        let mut w = vec![7u8; 3];
1186        reserve_for(&mut w, 64, "probe");
1187        assert!(w.is_empty() && w.capacity() >= 64);
1188    }
1189}