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