Skip to main content

oxdock_parser/
value.rs

1//! Value-word core: every DSL value is a fixed-size word (a [`TypeDescriptor`]
2//! vtable pointer plus a 64-bit [`ValuePayload`]) interpreted through that
3//! vtable.
4//!
5//! There is exactly one representation for every type. Payloads that fit in
6//! 64 bits (integers, floats, booleans, handles, and host scalars annotated
7//! `#[oxdock_type(inline)]`) ride directly in the payload; everything else
8//! rides behind a thin pointer to either an owned `Box<T>` (exclusive heaps:
9//! `STRING`, `PATH`, `DURATION`, `PIPE`, most host types) or a shared
10//! `Arc<T>` (shared heaps: `LIST`, `MAP`, and host types annotated
11//! `#[oxdock_type(shared)]`). The vtable owns the lifecycle (`clone`, `drop`)
12//! and operations (`eq`, `fmt`), so `Clone`/`Drop`/`PartialEq`/`Display` on
13//! [`Value`] delegate instead of matching. There are no dynamic trait
14//! objects anywhere in this path: every hook is a monomorphic function
15//! pointer reached directly, with no table lookup and no lock.
16//!
17//! Descriptors are canonical singletons: each `#[oxdock_type]` struct gets
18//! one `&'static TypeDescriptor` (built at compile time, shared by every
19//! word of that type), so words carry their own vtable and no registry of
20//! any kind exists. The twelve startup types (`INT`, `FLOAT`, `STRING`, `BOOL`,
21//! `LIST`, `MAP`, `PATH`, `DURATION`, `PIPE`, `HANDLE`, `SEMAPHORE`, `PERMIT`)
22//! are ordinary Rust structs annotated with `#[oxdock_type]`, exactly as host
23//! types are. Name directories (which descriptor answers for `"TAG"`) live per execution
24//! state in `oxdock-core`, never here: this module knows types, not names.
25//!
26//! Ownership discipline (load-bearing, Miri-verified in
27//! `crates/oxdock-core/tests/miri_value_words.rs`):
28//!
29//! - Exclusive heap [`Value`]s own their box exactly once. `clone` allocates
30//!   a new box; `drop` frees it. No sharing, no aliasing. Because each box
31//!   holds a concrete sized `T`, its pointer is thin: no double-boxing, no
32//!   fat pointer casts, no metadata to lose.
33//! - Shared heap [`Value`]s (`LIST`, `MAP`) co-own an `Arc<T>` buffer.
34//!   `clone` bumps the strong count in `O(1)` with no allocation; `drop`
35//!   releases one count and frees only the final word's drop. Because the
36//!   DSL exposes no interior mutability, aliases, or reference syntax,
37//!   container graphs are strictly acyclic trees, so refcounting reclaims
38//!   deterministically with no tracing collector. Mutable access goes only
39//!   through [`Value::read_heap_mut`], which detaches (clones the buffer)
40//!   whenever the strong count exceeds 1, so a writer always exclusively
41//!   owns a private buffer and clones never observe each other's writes.
42//!   Deriving `&mut` from a payload any other way is unsound.
43//! - Pointer casts are always `Box::into_raw` / `Box::from_raw` (exclusive)
44//!   or `Arc::into_raw` / `Arc::from_raw` plus `Arc::increment_strong_count`
45//!   (shared) round trips on the same concrete payload type, which preserves
46//!   provenance. Inline words never touch the pointer domain; heap words
47//!   never touch the integer domain.
48//! - Minting a word with a descriptor built for a different Rust type
49//!   misdirects the vtable and is unsound. The `mint_*` constructors
50//!   document this contract; hosts mint through the payload type's own
51//!   `OxDockType::descriptor()`, which cannot mismatch by construction.
52
53use std::collections::BTreeMap;
54use std::fmt;
55use std::time::Duration;
56
57use oxdock_func_macro::oxdock_type;
58use oxdock_pipe::{PipeHandle, new_handle_in_task};
59
60use crate::tag::{
61    BOOL_TYPE_NAME, DURATION_TYPE_NAME, FLOAT_TYPE_NAME, HANDLE_TYPE_NAME, INT_TYPE_NAME,
62    LIST_TYPE_NAME, MAP_TYPE_NAME, PATH_TYPE_NAME, PERMIT_TYPE_NAME, PIPE_TYPE_NAME,
63    SEMAPHORE_TYPE_NAME, STRING_TYPE_NAME,
64};
65
66/// Anchor of a type's reference section, derived from its name the way the
67/// Markdown slugger derives it from the doc title.
68pub fn type_anchor(name: &str) -> String {
69    format!("value-type-{}", name.to_lowercase())
70}
71
72/// Canonical descriptors of the twelve startup types, in a fixed order, for
73/// seeding per-state name directories and static rendering (docs-gen).
74/// Each entry is the payload struct's own singleton: no table, no lock.
75pub fn startup_descriptors() -> [(&'static str, &'static TypeDescriptor); 12] {
76    [
77        (INT_TYPE_NAME, IntValue::descriptor()),
78        (FLOAT_TYPE_NAME, FloatValue::descriptor()),
79        (STRING_TYPE_NAME, StringValue::descriptor()),
80        (BOOL_TYPE_NAME, BoolValue::descriptor()),
81        (LIST_TYPE_NAME, ListValue::descriptor()),
82        (MAP_TYPE_NAME, MapValue::descriptor()),
83        (PATH_TYPE_NAME, PathValue::descriptor()),
84        (DURATION_TYPE_NAME, DurationValue::descriptor()),
85        (PIPE_TYPE_NAME, PipeValue::descriptor()),
86        (HANDLE_TYPE_NAME, HandleValue::descriptor()),
87        (SEMAPHORE_TYPE_NAME, SemaphoreValue::descriptor()),
88        (PERMIT_TYPE_NAME, SemaphorePermit::descriptor()),
89    ]
90}
91
92// ---------------------------------------------------------------------------
93// Payload structs for the startup-registered types. Each carries
94// `#[oxdock_type]` so its descriptor derives from the same macro hosts use;
95// `inline` selects the zero-allocation payload path, exactly as for host
96// scalars. Private: hosts never name these types; they observe them through
97// the word accessors below.
98// ---------------------------------------------------------------------------
99
100/// 64-bit signed integer, e.g. an exit code.
101#[oxdock_type(crate_path = "::oxdock_parser", name = "INT", inline)]
102#[derive(Debug, Clone, Copy, PartialEq)]
103struct IntValue(pub i64);
104
105/// 64-bit float, e.g. a ratio.
106#[oxdock_type(crate_path = "::oxdock_parser", name = "FLOAT", inline)]
107#[derive(Debug, Clone, Copy, PartialEq)]
108struct FloatValue(pub f64);
109
110/// Arbitrary text. Quotes keep exact bytes, lone `$var` evaluates, `{{ ... }}` interpolates.
111#[oxdock_type(
112    crate_path = "::oxdock_parser",
113    name = "STRING",
114    summary = "Arbitrary text."
115)]
116#[derive(Debug, Clone, PartialEq)]
117struct StringValue(pub String);
118
119/// Boolean `true` or `false`.
120#[oxdock_type(crate_path = "::oxdock_parser", name = "BOOL", inline)]
121#[derive(Debug, Clone, Copy, PartialEq)]
122struct BoolValue(pub bool);
123
124/// Ordered list of values. Shared heap: cloning bumps a refcount.
125#[oxdock_type(crate_path = "::oxdock_parser", name = "LIST", shared)]
126#[derive(Debug, Clone, PartialEq)]
127struct ListValue(pub Vec<Value>);
128
129/// String-keyed map of values. Shared heap: cloning bumps a refcount.
130#[oxdock_type(crate_path = "::oxdock_parser", name = "MAP", shared)]
131#[derive(Debug, Clone, PartialEq)]
132struct MapValue(pub BTreeMap<String, Value>);
133
134/// Workspace path, resolved against cwd and guarded against escape.
135#[oxdock_type(crate_path = "::oxdock_parser", name = "PATH")]
136#[derive(Debug, Clone, PartialEq)]
137#[allow(clippy::disallowed_types)]
138struct PathValue(#[allow(clippy::disallowed_types)] pub std::path::PathBuf);
139
140/// Positive time span: `500ms`, `10s`, `2m`, `1h`; bare number means seconds.
141#[oxdock_type(
142    crate_path = "::oxdock_parser",
143    name = "DURATION",
144    summary = "Positive time span."
145)]
146#[derive(Debug, Clone, PartialEq)]
147struct DurationValue(pub Duration);
148
149/// Anonymous pipe handle. The backend materializes lazily on first
150/// binding (never eagerly at declaration), so the choice always has full
151/// usage context. Cloning shares the backend (explicit-sharing fan-out);
152/// equality is handle identity, never byte comparison.
153#[oxdock_type(
154    crate_path = "::oxdock_parser",
155    name = "PIPE",
156    summary = "Anonymous pipe handle.",
157    shared
158)]
159#[derive(Debug, Clone)]
160struct PipeValue(pub PipeHandle);
161
162impl PartialEq for PipeValue {
163    /// Handle identity: two words name the same channel iff they share
164    /// the cell. Never compares bytes (backends may be unbound, and
165    /// locking two cells in `eq` risks ordering deadlocks).
166    fn eq(&self, other: &Self) -> bool {
167        self.0.ptr_eq(&other.0)
168    }
169}
170
171/// Background task handle minted by `LET $t: HANDLE<T> = ASYNC ...`.
172/// The payload names what `AWAIT` binds: `HANDLE<T>` yields `T` on
173/// capture, `HANDLE<VOID>` is join-only (bare `AWAIT`/`CANCEL` only).
174/// The handle itself is just a task id and carries no data: observe
175/// the task through `AWAIT`, `CANCEL`, or `TASK_POLL`, never through
176/// the handle. Copying it aliases the same task, and joining twice
177/// fails. Bare `HANDLE` is not a declaration type: write the payload
178/// or explicit `HANDLE<ANY>`.
179#[oxdock_type(crate_path = "::oxdock_parser", name = "HANDLE", inline)]
180#[derive(Debug, Clone, Copy, PartialEq)]
181pub struct HandleValue(pub u64);
182
183/// Shared admission-control counter backing `SEMAPHORE` words. Clones
184/// share the backend, so every word naming one semaphore observes the
185/// same count. Lock-free atomics throughout: no mutex exists to poison,
186/// so `Drop` paths stay infallible on every path including unwinding.
187/// No waiter ever sleeps on the counter, so the non-blocking acquire
188/// adds zero wedge surface.
189#[derive(Debug)]
190pub struct SemaphoreState {
191    max: usize,
192    held: std::sync::atomic::AtomicUsize,
193}
194
195impl SemaphoreState {
196    fn new(max: usize) -> Self {
197        Self {
198            max,
199            held: std::sync::atomic::AtomicUsize::new(0),
200        }
201    }
202
203    /// Non-blocking acquire: true and counted when a permit was free.
204    /// Compare-and-swap loop, so only a winning CAS claims a slot.
205    pub fn try_acquire(&self) -> bool {
206        use std::sync::atomic::Ordering;
207        let mut current = self.held.load(Ordering::Acquire);
208        loop {
209            if current >= self.max {
210                return false;
211            }
212            match self.held.compare_exchange_weak(
213                current,
214                current + 1,
215                Ordering::AcqRel,
216                Ordering::Acquire,
217            ) {
218                Ok(_) => return true,
219                Err(actual) => current = actual,
220            }
221        }
222    }
223
224    /// Release one permit. Saturating and infallible: exactly-once
225    /// last-drop release (see `PermitInner`) keeps this exact, and the
226    /// floor (never a wrap, never a panic) is the backstop.
227    pub fn release(&self) {
228        use std::sync::atomic::Ordering;
229        let _ = self
230            .held
231            .try_update(Ordering::AcqRel, Ordering::Acquire, |held| {
232                held.checked_sub(1)
233            });
234    }
235
236    /// Permits currently free. Exact at read time, stale the instant the
237    /// caller acts on it: observability only, never admission input.
238    pub fn available(&self) -> usize {
239        self.max
240            .saturating_sub(self.held.load(std::sync::atomic::Ordering::Acquire))
241    }
242}
243
244/// Counting semaphore for admission control. Cloning shares the backend
245/// (explicit-sharing fan-out); equality is handle identity, never the
246/// count.
247#[oxdock_type(
248    crate_path = "::oxdock_parser",
249    name = "SEMAPHORE",
250    summary = "Counting semaphore for admission control.",
251    shared
252)]
253#[derive(Debug, Clone)]
254struct SemaphoreValue(pub std::sync::Arc<SemaphoreState>);
255
256impl PartialEq for SemaphoreValue {
257    /// Handle identity: two words name the same semaphore iff they share
258    /// the backend. Never compares counts (a racing acquire would make
259    /// equality nondeterministic).
260    fn eq(&self, other: &Self) -> bool {
261        std::sync::Arc::ptr_eq(&self.0, &other.0)
262    }
263}
264
265/// Last-drop releaser for one acquired permit. Lives behind the permit
266/// word's `Arc`: when the final permit clone drops, this drops and hands
267/// the permit back exactly once. No manual release exists, so worker
268/// return (clean, error, panic, cooperative cancel) releases through
269/// ordinary frame teardown with no DSL cleanup code.
270#[derive(Debug)]
271pub struct PermitInner {
272    sem: std::sync::Arc<SemaphoreState>,
273}
274
275impl Drop for PermitInner {
276    fn drop(&mut self) {
277        self.sem.release();
278    }
279}
280
281/// Opaque admission permit minted by `SEMAPHORE_TRY_ACQUIRE`. Cloning
282/// shares the release obligation (first drops release nothing, the last
283/// releases once); equality is handle identity.
284#[oxdock_type(
285    crate_path = "::oxdock_parser",
286    name = "PERMIT",
287    summary = "Opaque admission permit; last drop releases it.",
288    shared
289)]
290#[derive(Debug, Clone)]
291struct SemaphorePermit(pub std::sync::Arc<PermitInner>);
292
293impl PartialEq for SemaphorePermit {
294    /// Handle identity: two words name the same permit iff they share
295    /// the releaser.
296    fn eq(&self, other: &Self) -> bool {
297        std::sync::Arc::ptr_eq(&self.0, &other.0)
298    }
299}
300
301impl fmt::Display for IntValue {
302    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
303        write!(f, "{}", self.0)
304    }
305}
306
307impl fmt::Display for FloatValue {
308    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
309        write!(f, "{}", self.0)
310    }
311}
312
313impl fmt::Display for BoolValue {
314    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
315        write!(f, "{}", self.0)
316    }
317}
318
319impl fmt::Display for HandleValue {
320    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
321        write!(f, "task#{}", self.0)
322    }
323}
324
325impl fmt::Display for StringValue {
326    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
327        write!(f, "\"{}\"", self.0)
328    }
329}
330
331impl fmt::Display for ListValue {
332    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
333        write!(f, "[")?;
334        for (i, item) in self.0.iter().enumerate() {
335            if i > 0 {
336                write!(f, ", ")?;
337            }
338            write!(f, "{}", item)?;
339        }
340        write!(f, "]")
341    }
342}
343
344impl fmt::Display for MapValue {
345    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
346        write!(f, "{{")?;
347        for (i, (k, v)) in self.0.iter().enumerate() {
348            if i > 0 {
349                write!(f, ", ")?;
350            }
351            write!(f, "{}: {}", k, v)?;
352        }
353        write!(f, "}}")
354    }
355}
356
357impl fmt::Display for DurationValue {
358    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
359        write!(f, "{}", crate::command::format_duration(&self.0))
360    }
361}
362
363impl fmt::Display for PathValue {
364    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
365        write!(f, "{}", self.0.display())
366    }
367}
368
369impl fmt::Display for PipeValue {
370    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
371        write!(f, "<pipe>")
372    }
373}
374
375impl fmt::Display for SemaphoreValue {
376    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
377        write!(f, "<semaphore>")
378    }
379}
380
381impl fmt::Display for SemaphorePermit {
382    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383        write!(f, "<permit>")
384    }
385}
386
387/// Payload half of a [`Value`] word: either the value's bytes inline or a
388/// thin pointer to an owned `Box<T>` (exclusive heaps) or a shared `Arc<T>`
389/// (shared heaps), as the type's descriptor dictates.
390/// Inline and pointer domains never mix for a given [`TypeDescriptor`].
391///
392/// Fields are private so safe code cannot forge payloads: every payload
393/// enters a word through [`store_inline`] (inline bytes) or the
394/// [`Value::mint_heap`] / [`Value::mint_heap_shared`] / [`Value::mint_inline`]
395/// choke points, where the `Send + Sync + 'static` bounds are enforced.
396/// External code observes payload bits through [`Value::inline_bits`] and
397/// [`Value::heap_ptr`].
398#[repr(C)]
399#[derive(Clone, Copy)]
400pub union ValuePayload {
401    as_u64: u64,
402    as_ptr: *mut (),
403}
404
405// Raw pointers are not `Send`/`Sync`, so both are implemented by hand.
406// Soundness: fields are private, so every exclusive heap [`Value`] owns its
407// box exactly once (mint allocates, `clone` allocates, `drop` frees),
408// shared heap [`Value`]s co-own their `Arc` buffer (mint allocates with
409// count 1, `clone` bumps, `drop` releases), payloads are never mutably
410// aliased, no vtable hook writes through a shared reference, and heap
411// contents are `Send + Sync` by construction (enforced at the `mint_*`
412// choke points, the only construction path; `Arc<T>` itself is `Send + Sync`
413// exactly when `T` is, which the same bounds guarantee).
414unsafe impl Send for ValuePayload {}
415unsafe impl Sync for ValuePayload {}
416
417/// A DSL value: a [`TypeDescriptor`] vtable pointer plus a [`ValuePayload`].
418/// Fixed size (128 bits on 64-bit targets). Lifecycle and operations call
419/// the vtable directly, with no table lookup and no lock; see the module
420/// docs for the ownership discipline.
421//
422// Fields are private so safe code cannot forge words with dangling
423// pointers: construction flows through [`Value::mint_inline`],
424// [`Value::mint_heap`], or the typed constructors below, and typed reads
425// go through [`Value::read_inline`] / [`Value::read_heap`].
426// `Send`/`Sync` follow from the payload impls above plus shared references.
427unsafe impl Send for Value {}
428unsafe impl Sync for Value {}
429#[repr(C)]
430pub struct Value {
431    vtable: &'static TypeDescriptor,
432    payload: ValuePayload,
433}
434
435impl Value {
436    /// The word's canonical descriptor singleton: the vtable backing its
437    /// lifecycle and operations.
438    pub fn descriptor(&self) -> &'static TypeDescriptor {
439        self.vtable
440    }
441
442    /// The word's registered type name (the descriptor's name).
443    pub fn type_name(&self) -> &'static str {
444        self.vtable.name
445    }
446
447    /// Raw payload bits, copied out. Meaningful for inline words (the
448    /// value's bytes); for heap words these are the box pointer's bits.
449    pub fn inline_bits(&self) -> u64 {
450        unsafe { self.payload.as_u64 }
451    }
452
453    /// Heap box (exclusive) or buffer (shared) pointer, copied out. Only
454    /// meaningful for heap words; never dereferenced here. Reading (not
455    /// dereferencing) is safe.
456    pub fn heap_ptr(&self) -> *mut () {
457        unsafe { self.payload.as_ptr }
458    }
459
460    /// Mint an inline word: memcpy the value's bytes into the payload.
461    /// Zero allocation. The descriptor must be the payload type's own
462    /// `OxDockType::descriptor()`; mismatching them misdirects the vtable
463    /// and is unsound.
464    pub fn mint_inline<T>(descriptor: &'static TypeDescriptor, value: T) -> Self
465    where
466        T: Copy + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
467    {
468        Self {
469            vtable: descriptor,
470            payload: store_inline(value),
471        }
472    }
473
474    /// Mint an exclusive heap word: move the value into an owned `Box<T>`
475    /// behind a thin pointer. One box allocation. The descriptor must be the
476    /// payload type's own `OxDockType::descriptor()`; mismatching them
477    /// misdirects the vtable and is unsound.
478    pub fn mint_heap<T>(descriptor: &'static TypeDescriptor, value: T) -> Self
479    where
480        T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
481    {
482        Self {
483            vtable: descriptor,
484            payload: ValuePayload {
485                as_ptr: Box::into_raw(Box::new(value)) as *mut (),
486            },
487        }
488    }
489
490    /// Mint a shared heap word: move the value into a reference-counted
491    /// `Arc<T>` behind a thin pointer. One allocation; later clones bump the
492    /// strong count instead of copying. The descriptor must be the payload
493    /// type's own `OxDockType::descriptor()` built for the shared path
494    /// (`#[oxdock_type(shared)]`); mismatching them misdirects the vtable
495    /// and is unsound.
496    pub fn mint_heap_shared<T>(descriptor: &'static TypeDescriptor, value: T) -> Self
497    where
498        T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
499    {
500        Self {
501            vtable: descriptor,
502            payload: ValuePayload {
503                as_ptr: std::sync::Arc::into_raw(std::sync::Arc::new(value)) as *mut (),
504            },
505        }
506    }
507
508    /// Read an inline word back out. Returns `None` when the word carries
509    /// a different descriptor; the load itself is infallible for a word
510    /// minted for `T`.
511    pub fn read_inline<T>(&self, expected: &'static TypeDescriptor) -> Option<T>
512    where
513        T: Copy + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
514    {
515        if !std::ptr::eq(self.vtable, expected) {
516            return None;
517        }
518        Some(unsafe { load_inline::<T>(self.payload) })
519    }
520
521    /// Borrow a heap word's concrete value. Returns `None` when the word
522    /// carries a different descriptor.
523    pub fn read_heap<T>(&self, expected: &'static TypeDescriptor) -> Option<&T>
524    where
525        T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
526    {
527        if !std::ptr::eq(self.vtable, expected) {
528            return None;
529        }
530        Some(unsafe { &*(self.payload.as_ptr as *const T) })
531    }
532
533    /// Borrow a heap word's concrete value mutably, detaching shared buffers
534    /// first (copy-on-write). Returns `None` when the word carries a
535    /// different descriptor. This is the only sound way to obtain `&mut`
536    /// access to a heap payload: exclusive heaps hand out their box
537    /// directly, shared heaps clone-then-hand-out when the strong count
538    /// exceeds 1 and mutate in place otherwise. Panics when called with an
539    /// inline descriptor, which has no heap buffer.
540    pub fn read_heap_mut<T>(&mut self, expected: &'static TypeDescriptor) -> Option<&mut T>
541    where
542        T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
543    {
544        if !std::ptr::eq(self.vtable, expected) {
545            return None;
546        }
547        Some(unsafe { &mut *((self.vtable.unshare)(&mut self.payload) as *mut T) })
548    }
549
550    /// Construct an integer word (inline, zero allocation).
551    pub fn int(n: i64) -> Self {
552        Self::mint_inline(IntValue::descriptor(), IntValue(n))
553    }
554
555    /// Construct a float word (inline, zero allocation).
556    pub fn float(f: f64) -> Self {
557        Self::mint_inline(FloatValue::descriptor(), FloatValue(f))
558    }
559
560    /// Construct a boolean word (inline, zero allocation).
561    pub fn bool(b: bool) -> Self {
562        Self::mint_inline(BoolValue::descriptor(), BoolValue(b))
563    }
564
565    /// Construct a task-handle word (inline, zero allocation).
566    pub fn handle(id: u64) -> Self {
567        Self::mint_inline(HandleValue::descriptor(), HandleValue(id))
568    }
569
570    /// Construct a string word.
571    pub fn string(s: String) -> Self {
572        Self::mint_heap(StringValue::descriptor(), StringValue(s))
573    }
574
575    /// Construct a list word (shared heap: clones share the buffer).
576    pub fn list(items: Vec<Value>) -> Self {
577        Self::mint_heap_shared(ListValue::descriptor(), ListValue(items))
578    }
579
580    /// Construct a map word (shared heap: clones share the buffer).
581    pub fn map(entries: BTreeMap<String, Value>) -> Self {
582        Self::mint_heap_shared(MapValue::descriptor(), MapValue(entries))
583    }
584
585    /// Construct a path word.
586    #[allow(clippy::disallowed_types)]
587    pub fn path(p: std::path::PathBuf) -> Self {
588        Self::mint_heap(PathValue::descriptor(), PathValue(p))
589    }
590
591    /// Construct a duration word.
592    pub fn duration(d: Duration) -> Self {
593        Self::mint_heap(DurationValue::descriptor(), DurationValue(d))
594    }
595
596    /// Construct a fresh unbound pipe handle (`LET $p: PIPE`, host
597    /// `new_pipe()`). Materializes lazily on first binding.
598    pub fn pipe_fresh() -> Self {
599        Self::pipe_fresh_in_task(0)
600    }
601
602    /// Construct a fresh unbound pipe handle declared by `task_id` (`0` =
603    /// root flow). The id travels with every clone so promotion checks
604    /// always see the declaration origin.
605    pub fn pipe_fresh_in_task(task_id: u64) -> Self {
606        Self::mint_heap_shared(
607            PipeValue::descriptor(),
608            PipeValue(new_handle_in_task(task_id)),
609        )
610    }
611
612    /// Wrap an existing handle as a `PIPE` word. Clones share the backend.
613    pub fn pipe_handle(handle: PipeHandle) -> Self {
614        Self::mint_heap_shared(PipeValue::descriptor(), PipeValue(handle))
615    }
616
617    /// Construct a semaphore word admitting at most `max` concurrent
618    /// holders. Every clone names the same backend.
619    pub fn semaphore(max: usize) -> Self {
620        Self::mint_heap_shared(
621            SemaphoreValue::descriptor(),
622            SemaphoreValue(std::sync::Arc::new(SemaphoreState::new(max))),
623        )
624    }
625
626    /// Mint a `PERMIT` word bound to `sem`. The permit returns to the
627    /// semaphore when the last clone of the word drops.
628    pub fn permit(sem: &std::sync::Arc<SemaphoreState>) -> Self {
629        Self::mint_heap_shared(
630            SemaphorePermit::descriptor(),
631            SemaphorePermit(std::sync::Arc::new(PermitInner {
632                sem: std::sync::Arc::clone(sem),
633            })),
634        )
635    }
636
637    /// Borrow the semaphore backend out of a `SEMAPHORE` word. Returns
638    /// `None` for non-`SEMAPHORE` words. The clone shares the backend.
639    pub fn as_semaphore(&self) -> Option<std::sync::Arc<SemaphoreState>> {
640        self.read_heap::<SemaphoreValue>(SemaphoreValue::descriptor())
641            .map(|v| std::sync::Arc::clone(&v.0))
642    }
643
644    /// Borrow the permit backend out of a `PERMIT` word. Returns `None`
645    /// for non-`PERMIT` words. The clone shares the backend.
646    pub fn as_permit(&self) -> Option<std::sync::Arc<PermitInner>> {
647        self.read_heap::<SemaphorePermit>(SemaphorePermit::descriptor())
648            .map(|v| std::sync::Arc::clone(&v.0))
649    }
650
651    /// Read an integer payload. Returns `None` for non-`INT` words.
652    pub fn as_i64(&self) -> Option<i64> {
653        self.read_inline::<IntValue>(IntValue::descriptor())
654            .map(|v| v.0)
655    }
656
657    /// Read a float payload. Returns `None` for non-`FLOAT` words.
658    pub fn as_f64(&self) -> Option<f64> {
659        self.read_inline::<FloatValue>(FloatValue::descriptor())
660            .map(|v| v.0)
661    }
662
663    /// Read a boolean payload. Returns `None` for non-`BOOL` words.
664    pub fn as_bool(&self) -> Option<bool> {
665        self.read_inline::<BoolValue>(BoolValue::descriptor())
666            .map(|v| v.0)
667    }
668
669    /// Read a task-handle payload. Returns `None` for non-`HANDLE` words.
670    pub fn as_handle(&self) -> Option<u64> {
671        self.read_inline::<HandleValue>(HandleValue::descriptor())
672            .map(|v| v.0)
673    }
674
675    /// Borrow a string payload. Returns `None` for non-`STRING` words.
676    pub fn as_str(&self) -> Option<&str> {
677        self.read_heap::<StringValue>(StringValue::descriptor())
678            .map(|v| v.0.as_str())
679    }
680
681    /// Borrow a list payload. Returns `None` for non-`LIST` words.
682    pub fn as_list(&self) -> Option<&Vec<Value>> {
683        self.read_heap::<ListValue>(ListValue::descriptor())
684            .map(|v| &v.0)
685    }
686
687    /// Borrow a list payload mutably, detaching the shared buffer first when
688    /// clones exist. Returns `None` for non-`LIST` words. This is the choke
689    /// point every future in-place container mutation must go through.
690    pub fn as_list_mut(&mut self) -> Option<&mut Vec<Value>> {
691        self.read_heap_mut::<ListValue>(ListValue::descriptor())
692            .map(|v| &mut v.0)
693    }
694
695    /// Borrow a map payload. Returns `None` for non-`MAP` words.
696    pub fn as_map(&self) -> Option<&BTreeMap<String, Value>> {
697        self.read_heap::<MapValue>(MapValue::descriptor())
698            .map(|v| &v.0)
699    }
700
701    /// Borrow a map payload mutably, detaching the shared buffer first when
702    /// clones exist. Returns `None` for non-`MAP` words. This is the choke
703    /// point every future in-place container mutation must go through.
704    pub fn as_map_mut(&mut self) -> Option<&mut BTreeMap<String, Value>> {
705        self.read_heap_mut::<MapValue>(MapValue::descriptor())
706            .map(|v| &mut v.0)
707    }
708
709    /// Clone the pipe handle out of a `PIPE` word. Returns `None` for
710    /// non-`PIPE` words. The clone shares the backend cell.
711    pub fn as_pipe_handle(&self) -> Option<PipeHandle> {
712        self.read_heap::<PipeValue>(PipeValue::descriptor())
713            .map(|v| v.0.clone())
714    }
715
716    /// Read a duration payload. Returns `None` for non-`DURATION` words.
717    pub fn as_duration(&self) -> Option<Duration> {
718        self.read_heap::<DurationValue>(DurationValue::descriptor())
719            .map(|v| v.0)
720    }
721
722    /// Borrow a path payload. Returns `None` for non-`PATH` words.
723    #[allow(clippy::disallowed_types)]
724    pub fn as_path(&self) -> Option<&std::path::Path> {
725        self.read_heap::<PathValue>(PathValue::descriptor())
726            .map(|v| v.0.as_path())
727    }
728}
729
730impl Clone for Value {
731    fn clone(&self) -> Self {
732        let payload = unsafe { (self.vtable.clone)(self.payload) };
733        Self {
734            vtable: self.vtable,
735            payload,
736        }
737    }
738}
739
740impl Drop for Value {
741    fn drop(&mut self) {
742        unsafe { (self.vtable.drop)(self.payload) };
743    }
744}
745
746impl PartialEq for Value {
747    fn eq(&self, other: &Self) -> bool {
748        if !std::ptr::eq(self.vtable, other.vtable) {
749            return false;
750        }
751        unsafe { (self.vtable.eq)(self.payload, other.payload) }
752    }
753}
754
755impl fmt::Debug for Value {
756    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
757        write!(f, "{}(", self.vtable.name)?;
758        unsafe { (self.vtable.fmt)(self.payload, f) }?;
759        write!(f, ")")
760    }
761}
762
763impl fmt::Display for Value {
764    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
765        unsafe { (self.vtable.fmt)(self.payload, f) }
766    }
767}
768
769/// Export hook for a DSL payload type, implemented by `#[oxdock_type]` on
770/// the payload struct itself. The canonical descriptor singleton backs
771/// every word of the type; user code never names a generated symbol.
772pub trait OxDockType {
773    /// The canonical descriptor deriving from the struct's name plus doc
774    /// comments. The same reference every call: pointer-compare words
775    /// against it.
776    fn descriptor() -> &'static TypeDescriptor;
777}
778
779/// Vtable for one type: lifecycle plus operations. All hooks are plain
780/// function pointers (never closures) so descriptors stay `Copy` and the
781/// global table hands them out by value. Every hook documents the payload
782/// domain it expects; calling one with a foreign payload is unsound, and
783/// every call site is a single choke point reviewed with the layout.
784///
785/// `unshare` is the copy-on-write gate: it rewrites the payload to a
786/// uniquely owned buffer when necessary and returns a mutable pointer the
787/// caller exclusively owns. Mutation must always go through
788/// [`Value::read_heap_mut`]; deriving `&mut` from a payload any other way
789/// is unsound for shared heaps.
790#[derive(Clone, Copy)]
791pub struct TypeDescriptor {
792    pub name: &'static str,
793    pub summary: &'static str,
794    pub docs: &'static str,
795    pub clone: unsafe fn(ValuePayload) -> ValuePayload,
796    pub drop: unsafe fn(ValuePayload),
797    pub eq: unsafe fn(ValuePayload, ValuePayload) -> bool,
798    pub fmt: unsafe fn(ValuePayload, &mut fmt::Formatter<'_>) -> fmt::Result,
799    pub unshare: unsafe fn(&mut ValuePayload) -> *mut (),
800}
801
802// ---------------------------------------------------------------------------
803// Payload adapters: one inline set, one exclusive-heap set, and one shared-
804// heap set drive `clone`/`drop`/`eq`/`fmt`/`unshare` for every type through
805// monomorphic function pointers. These are `pub` solely so `#[oxdock_type]`-
806// generated descriptors can name them; hosts never call them directly.
807// ---------------------------------------------------------------------------
808
809/// Copy a `Copy` value's bytes into a payload. Panics when `T` exceeds 64
810/// bits: such types must use the heap path.
811pub fn store_inline<T>(value: T) -> ValuePayload
812where
813    T: Copy + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
814{
815    assert!(
816        std::mem::size_of::<T>() <= 8,
817        "inline payloads hold at most 64 bits"
818    );
819    let mut bits: u64 = 0;
820    unsafe {
821        std::ptr::copy_nonoverlapping(
822            &value as *const T as *const u8,
823            &mut bits as *mut u64 as *mut u8,
824            std::mem::size_of::<T>(),
825        );
826    }
827    // No `mem::forget`: `T: Copy` has no finalizer, so the source needs no
828    // suppression after its bytes are copied out.
829    ValuePayload { as_u64: bits }
830}
831
832/// Reconstruct a `Copy` value from an inline payload.
833///
834/// # Safety
835/// The payload must hold bytes stored by [`store_inline`] for `T`.
836pub unsafe fn load_inline<T>(payload: ValuePayload) -> T
837where
838    T: Copy + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
839{
840    // (Spelled as an explicit gate because `debug_assert!` expands to the
841    // banned `cfg!` macro.)
842    #[cfg(debug_assertions)]
843    if std::mem::size_of::<T>() > 8 {
844        panic!("inline payloads hold at most 64 bits");
845    }
846    let mut value = std::mem::MaybeUninit::<T>::uninit();
847    unsafe {
848        std::ptr::copy_nonoverlapping(
849            &payload.as_u64 as *const u64 as *const u8,
850            value.as_mut_ptr() as *mut u8,
851            std::mem::size_of::<T>(),
852        );
853        value.assume_init()
854    }
855}
856
857/// Inline `clone`: payloads are plain bytes.
858///
859/// # Safety
860/// The payload must hold inline bytes (never a live pointer).
861pub unsafe fn clone_copy(payload: ValuePayload) -> ValuePayload {
862    payload
863}
864
865/// Inline `drop`: nothing owns anything.
866///
867/// # Safety
868/// The payload must hold inline bytes (never a live pointer).
869pub unsafe fn drop_noop(_payload: ValuePayload) {}
870
871/// Inline `eq`: reconstruct both sides and compare.
872///
873/// # Safety
874/// Both payloads must hold bytes stored by [`store_inline`] for `T`.
875pub unsafe fn eq_inline<T>(a: ValuePayload, b: ValuePayload) -> bool
876where
877    T: Copy + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
878{
879    unsafe { load_inline::<T>(a) == load_inline::<T>(b) }
880}
881
882/// Inline `fmt`: reconstruct and render.
883///
884/// # Safety
885/// The payload must hold bytes stored by [`store_inline`] for `T`.
886pub unsafe fn fmt_inline<T>(payload: ValuePayload, f: &mut fmt::Formatter) -> fmt::Result
887where
888    T: Copy + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
889{
890    write!(f, "{}", unsafe { load_inline::<T>(payload) })
891}
892
893/// Heap `clone`: deep-copy the box.
894///
895/// # Safety
896/// The payload must own a `Box<T>` exactly once.
897pub unsafe fn clone_boxed<T>(payload: ValuePayload) -> ValuePayload
898where
899    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
900{
901    let source = unsafe { &*(payload.as_ptr as *const T) };
902    ValuePayload {
903        as_ptr: Box::into_raw(Box::new(source.clone())) as *mut (),
904    }
905}
906/// Heap `drop`: free the box.
907///
908/// # Safety
909/// The payload must own a `Box<T>` exactly once; it must never be used
910/// again afterwards.
911pub unsafe fn drop_boxed<T>(payload: ValuePayload)
912where
913    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
914{
915    drop(unsafe { Box::from_raw(payload.as_ptr as *mut T) });
916}
917
918/// Heap `eq`: compare the boxed values.
919///
920/// # Safety
921/// Both payloads must own a `Box<T>` exactly once.
922pub unsafe fn eq_boxed<T>(a: ValuePayload, b: ValuePayload) -> bool
923where
924    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
925{
926    let left = unsafe { &*(a.as_ptr as *const T) };
927    let right = unsafe { &*(b.as_ptr as *const T) };
928    left == right
929}
930
931/// Heap `fmt`: render the boxed value.
932///
933/// # Safety
934/// The payload must own a `Box<T>` exactly once.
935pub unsafe fn fmt_boxed<T>(payload: ValuePayload, f: &mut fmt::Formatter) -> fmt::Result
936where
937    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
938{
939    let value = unsafe { &*(payload.as_ptr as *const T) };
940    write!(f, "{value}")
941}
942
943/// Shared-heap `clone`: bump the `Arc` strong count, sharing the buffer.
944/// `O(1)` with no allocation.
945///
946/// # Safety
947/// The payload must co-own an `Arc<T>` buffer minted by
948/// [`Value::mint_heap_shared`] and cloned only through this hook, so one
949/// outstanding strong count exists per live word.
950pub unsafe fn clone_shared<T>(payload: ValuePayload) -> ValuePayload
951where
952    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
953{
954    unsafe { std::sync::Arc::increment_strong_count(payload.as_ptr as *const T) };
955    payload
956}
957
958/// Shared-heap `drop`: release one `Arc` strong count, freeing the buffer
959/// only when the final word drops.
960///
961/// # Safety
962/// The payload must co-own an `Arc<T>` buffer; it must never be used again
963/// afterwards.
964pub unsafe fn drop_shared<T>(payload: ValuePayload)
965where
966    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
967{
968    drop(unsafe { std::sync::Arc::from_raw(payload.as_ptr as *const T) });
969}
970
971/// Shared-heap `eq`: compare the shared values.
972///
973/// # Safety
974/// Both payloads must co-own an `Arc<T>` buffer.
975pub unsafe fn eq_shared<T>(a: ValuePayload, b: ValuePayload) -> bool
976where
977    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
978{
979    let left = unsafe { &*(a.as_ptr as *const T) };
980    let right = unsafe { &*(b.as_ptr as *const T) };
981    left == right
982}
983
984/// Shared-heap `fmt`: render the shared value.
985///
986/// # Safety
987/// The payload must co-own an `Arc<T>` buffer.
988pub unsafe fn fmt_shared<T>(payload: ValuePayload, f: &mut fmt::Formatter) -> fmt::Result
989where
990    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
991{
992    let value = unsafe { &*(payload.as_ptr as *const T) };
993    write!(f, "{value}")
994}
995
996/// Inline `unshare`: inline words hold bytes, not a heap buffer, so there
997/// is nothing to hand out mutably. Panics: reaching this hook means
998/// [`Value::read_heap_mut`] was called with an inline descriptor, a caller
999/// bug (mirrors [`store_inline`]'s size assert).
1000///
1001/// # Safety
1002/// The payload must hold inline bytes (never a live pointer).
1003pub unsafe fn unshare_inline(payload: &mut ValuePayload) -> *mut () {
1004    let _ = payload;
1005    panic!("inline words have no heap buffer to unshare");
1006}
1007
1008/// Exclusive-heap `unshare`: the box is already uniquely owned, so the
1009/// payload is returned unchanged with no allocation.
1010///
1011/// # Safety
1012/// The payload must own a `Box<T>` exactly once. The returned pointer must
1013/// only be written through while this word stays the sole owner.
1014pub unsafe fn unshare_boxed<T>(payload: &mut ValuePayload) -> *mut ()
1015where
1016    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
1017{
1018    unsafe { payload.as_ptr }
1019}
1020
1021/// Shared-heap `unshare`: detach on write. When the strong count is 1 the
1022/// payload is returned unchanged (in-place, no allocation); otherwise the
1023/// buffer is cloned, the word is rewritten to the private buffer, and the
1024/// other clones keep the original. Either way the returned pointer addresses
1025/// a buffer this word uniquely owns.
1026///
1027/// # Safety
1028/// The payload must co-own an `Arc<T>` buffer minted by
1029/// [`Value::mint_heap_shared`] with one outstanding strong count per live
1030/// word. The returned pointer must only be written through while this word
1031/// stays the sole owner of its (possibly fresh) buffer.
1032pub unsafe fn unshare_shared<T>(payload: &mut ValuePayload) -> *mut ()
1033where
1034    T: Clone + PartialEq + fmt::Display + fmt::Debug + Send + Sync + 'static,
1035{
1036    let raw = unsafe { payload.as_ptr } as *const T;
1037    let mut shared = unsafe { std::sync::Arc::from_raw(raw) };
1038    let unique = std::sync::Arc::make_mut(&mut shared);
1039    let out = unique as *mut T;
1040    payload.as_ptr = std::sync::Arc::into_raw(shared) as *mut ();
1041    out as *mut ()
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046    use super::*;
1047
1048    #[test]
1049    fn semaphore_counts_exactly_to_cap() {
1050        let sem = Value::semaphore(2);
1051        let inner = sem.as_semaphore().expect("SEMAPHORE word");
1052        assert_eq!(inner.available(), 2);
1053        assert!(inner.try_acquire());
1054        assert_eq!(inner.available(), 1);
1055        assert!(inner.try_acquire());
1056        assert_eq!(inner.available(), 0);
1057        assert!(!inner.try_acquire());
1058        inner.release();
1059        assert_eq!(inner.available(), 1);
1060    }
1061
1062    #[test]
1063    fn semaphore_words_share_one_backend_by_identity() {
1064        let first = Value::semaphore(1);
1065        let alias = first.clone();
1066        assert_eq!(&alias, &first);
1067        assert_eq!(format!("{first}"), "<semaphore>");
1068        // One acquire through either word exhausts the shared count.
1069        assert!(first.as_semaphore().expect("backend").try_acquire());
1070        assert!(!alias.as_semaphore().expect("backend").try_acquire());
1071        // Distinct declarations never alias; non-words read as absent.
1072        assert_ne!(Value::semaphore(1), first);
1073        assert!(Value::int(1).as_semaphore().is_none());
1074    }
1075
1076    #[test]
1077    fn permit_last_drop_releases_exactly_once() {
1078        let sem = Value::semaphore(1);
1079        let inner = sem.as_semaphore().expect("backend");
1080        assert!(inner.try_acquire());
1081        let first = Value::permit(&inner);
1082        assert_eq!(format!("{first}"), "<permit>");
1083        let second = first.clone();
1084        assert_eq!(&first, &second);
1085        drop(first);
1086        assert_eq!(inner.available(), 0);
1087        drop(second);
1088        assert_eq!(inner.available(), 1);
1089    }
1090
1091    #[test]
1092    fn permit_releases_when_holder_panics() {
1093        let sem = Value::semaphore(1);
1094        let inner = sem.as_semaphore().expect("backend");
1095        let worker = {
1096            let inner = std::sync::Arc::clone(&inner);
1097            std::thread::spawn(move || {
1098                assert!(inner.try_acquire());
1099                let _permit = Value::permit(&inner);
1100                panic!("worker fails holding the permit");
1101            })
1102        };
1103        assert!(worker.join().is_err());
1104        assert_eq!(inner.available(), 1);
1105    }
1106
1107    #[test]
1108    fn semaphore_holds_cap_under_contention() {
1109        use std::sync::atomic::Ordering;
1110        let sem = Value::semaphore(4);
1111        let inner = sem.as_semaphore().expect("backend");
1112        let holders = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1113        let peak = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1114        let mut threads = Vec::new();
1115        for _ in 0..8 {
1116            let inner = std::sync::Arc::clone(&inner);
1117            let holders = std::sync::Arc::clone(&holders);
1118            let peak = std::sync::Arc::clone(&peak);
1119            threads.push(std::thread::spawn(move || {
1120                let mut acquired = 0;
1121                while acquired < 25 {
1122                    if inner.try_acquire() {
1123                        {
1124                            // Release rides the permit word's drop: the
1125                            // scope exit below hands the permit back.
1126                            let _permit = Value::permit(&inner);
1127                            let current = holders.fetch_add(1, Ordering::SeqCst) + 1;
1128                            peak.fetch_max(current, Ordering::SeqCst);
1129                            std::thread::yield_now();
1130                            holders.fetch_sub(1, Ordering::SeqCst);
1131                        }
1132                        acquired += 1;
1133                    } else {
1134                        std::thread::yield_now();
1135                    }
1136                }
1137            }));
1138        }
1139        for thread in threads {
1140            thread.join().expect("worker joins");
1141        }
1142        // 200 acquisitions, never more than 4 inside at once, every
1143        // permit handed back: exact accounting under contention.
1144        assert!(peak.load(Ordering::SeqCst) <= 4);
1145        assert_eq!(holders.load(Ordering::SeqCst), 0);
1146        assert_eq!(inner.available(), 4);
1147    }
1148}