Skip to main content

vthread_stack/
scoped.rs

1//! Borrowed fibers whose executable state is revoked before their lexical scope exits.
2
3use crate::{
4    Fiber, FiberLease,
5    panic_payload::{self, CapturedPanic},
6};
7use corosensei::stack::DefaultStack;
8use std::{
9    cell::{Cell, RefCell},
10    io,
11    marker::PhantomData,
12    rc::Rc,
13};
14
15/// Lexical ownership for a bounded set of borrowed, non-Send stacks.
16pub struct FiberScope<'scope, 'env: 'scope> {
17    registry: Rc<Registry>,
18    scope: PhantomData<&'scope mut &'scope ()>,
19    env: PhantomData<&'env mut &'env ()>,
20}
21
22struct Registry {
23    fibers: RefCell<Vec<FiberLease>>,
24    capacity: usize,
25    closed: Cell<bool>,
26}
27
28struct ScopeGuard(Rc<Registry>);
29
30impl<'scope, 'env> FiberScope<'scope, 'env> {
31    /// Creates a local stack. The scope retains ownership even if its lease is forgotten.
32    pub fn spawn(
33        &'scope self,
34        stack: DefaultStack,
35        entry: impl FnOnce() + 'scope,
36    ) -> io::Result<FiberLease> {
37        let mut fibers = self.registry.fibers.borrow_mut();
38        fibers.retain(FiberLease::live);
39        if self.registry.closed.get() || fibers.len() >= self.registry.capacity {
40            return Err(io::Error::other("borrowed fiber scope closed or full"));
41        }
42        // SAFETY: entry lives for scope; the non-forgettable outer scope owns a lease
43        // and revokes every stack before returning, including on unwind or leaked leases.
44        let fiber = unsafe { Fiber::borrowed(stack, entry) };
45        let lease = FiberLease::new(fiber);
46        fibers.push(lease.clone());
47        Ok(lease)
48    }
49}
50
51impl ScopeGuard {
52    fn drain(&self) -> Option<CapturedPanic> {
53        self.0.closed.set(true);
54        let fibers = self.0.fibers.take();
55        let mut failure = None;
56        for fiber in fibers {
57            for _ in 0..2 {
58                if !fiber.live() {
59                    break;
60                }
61                if let Err(payload) =
62                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| fiber.reclaim()))
63                {
64                    panic_payload::retain(&mut failure, payload);
65                }
66            }
67            // A borrowed executable stack must never survive the lexical environment.
68            // A mount that fails twice has no safe recovery path; do not leak the fiber.
69            if fiber.live() {
70                std::process::abort();
71            }
72        }
73        failure
74    }
75}
76
77impl Drop for ScopeGuard {
78    fn drop(&mut self) {
79        self.drain();
80    }
81}
82
83/// Runs a lexical borrowed-stack owner; leaked leases are inert after this returns.
84pub fn fiber_scope<'env, R>(
85    capacity: usize,
86    body: impl for<'scope> FnOnce(&'scope FiberScope<'scope, 'env>) -> R,
87) -> R {
88    let registry = Rc::new(Registry {
89        fibers: RefCell::new(Vec::new()),
90        capacity,
91        closed: Cell::new(false),
92    });
93    let scope = FiberScope {
94        registry,
95        scope: PhantomData,
96        env: PhantomData,
97    };
98    // Declare the guard last: children may borrow the scope itself, so their
99    // reclamation must precede destruction of the scope value on every exit path.
100    let guard = ScopeGuard(Rc::clone(&scope.registry));
101    // Reclaim outside an active body unwind so a cleanup panic cannot double-unwind.
102    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(&scope)));
103    let cleanup = guard.drain();
104    match result {
105        Err(payload) => {
106            // corosensei uses a private panic payload as its forced-unwind control token.
107            // Preserve it exactly; cleanup payloads were separately captured and observed.
108            drop(cleanup);
109            std::panic::resume_unwind(payload)
110        }
111        Ok(value) => {
112            if let Some(failure) = cleanup {
113                std::panic::resume_unwind(Box::new(failure));
114            }
115            value
116        }
117    }
118}
119
120#[cfg(test)]
121#[path = "scoped_test.rs"]
122mod scoped_test;