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