//! Handlers with `ctl` operations: continuations by stack switching (ADR //! 0003, Revision 1; ADR 0010 for routing; ADR 0017 for `multi ctl`). //! //! - `tl_handle_ctl` runs the handler's body on a fiber of its own. The //! calling stack drives it, as the interpreter's `drive` does. //! - `tl_perform_ctl` suspends the current fiber with a request naming //! the handler, by its marker. A handler that is not the target forwards //! the request to its own parent and passes the answer back down. //! - The target calls the clause with the arguments and a `resume` //! closure. Calling `resume` continues the fiber until it finishes //! (giving the handler's result, after the return clause) or performs //! the next operation (whose clause's result it is). //! - **One-shot.** Each suspension accepts exactly one `resume`; a second //! one panics. //! - **Cancellation.** When the outermost `tl_handle_ctl` finishes while //! the fiber still waits for a `resume` that never came, the fiber is //! resumed in *cancel* mode: its perform returns with `yielding = //! CANCEL`, generated code unwinds it (running its `defer` cleanups), //! and every reference it held is dropped (exact Perceus). A `resume` //! called after that panics. If a cleanup panics (or the actor is //! killed meanwhile), that unwinding continues past the handler. //! - **Preemption** inside a fiber is forwarded up to the actor (the //! actor's own fiber yields to the scheduler), then back down. //! //! **Multi-shot** (`tl_handle_multi`, ADR 0017). Each suspension is a //! *capture*. The fiber's stack holds at most one capture at a time (its //! *occupant*); the others are saved as [`Snapshot`]s and written back at //! the same address when resumed, so pointers into the stack stay valid. //! - A `resume` whose closure is unique (its last use) runs the capture //! itself. Otherwise it runs a copy: a *copying pass* resumes the fiber //! with `yielding = CLONE`, so every frame's unwinding code takes one //! more reference to what it holds (instead of dropping it) and returns; //! then the snapshot is written back, and runs owning those references. //! Only generated code, `tl_defer` and `tl_region_exit` may sit on the //! fiber between the body and the operation: a `ctl` handler installed //! in between (a fiber of its own) makes the capture impossible to copy. //! - When the handler finishes, every capture left is released in order: //! one never resumed is cancelled (its cleanups run), one resumed before //! is discarded (`yielding = DISCARD`: references dropped, cleanups not //! run, since its copies ran them). //! //! **Lifetimes.** A handler's frame lives in a heap block (`TAG_FRAME`) //! counted like any value. `tl_handle_ctl` holds one count, and each //! `resume` closure holds one. A frame's fiber has always finished, or //! been cancelled, before the frame is freed. use crate::fiber::{Coroutine, CoroutineResult, Snapshot, Stack, Yielder}; use crate::abi::{ Block, Ctx, TAG_FRAME, UNIT, Value, YIELD_CANCEL, YIELD_CLONE, YIELD_DISCARD, YIELD_FINAL, YIELD_NONE, int, int_get, is_ptr, }; use crate::heap::{drop_value, dup_value, tl_alloc}; use crate::prims::call_closure; use crate::sched::HANDLER_STACK_SIZE; pub(crate) enum Resume { Value(Value), Cancel, /// A copying pass (ADR 0017). Clone, /// Release without running cleanups (ADR 0017). Discard, } pub(crate) enum Request { /// An operation for the handler with this marker; the payload is the /// operation's index, then its arguments. Op { marker: u64, payload: Value }, /// The actor's reduction budget is spent: yield to the scheduler. Preempt, } pub(crate) type HandlerYielder = Yielder; type HandlerFiber = Coroutine; /// A handler fiber's yielder and frame. It lives at the bottom of the /// fiber's own stack; each actor points at the one of the fiber running /// now (null on the actor's own stack). One pointer, so that saving it in /// `drive` costs one word. pub(crate) struct Running { yielder: *const HandlerYielder, frame: *mut Frame, } struct Frame { marker: u64, fiber: Option, /// Owned: the capability block (clause closures, then the marker). cap: Value, /// Owned: the return clause, or unit. ret: Value, /// Suspensions so far; a `resume` closure belongs to one. suspensions: i64, /// Whether the fiber is suspended waiting for a `resume`. waiting: bool, /// Whether the handler finished while the fiber still waited. cancelled: bool, /// `ctl` handlers installed while this frame's fiber runs, and not /// finished: a capture taken now holds their fibers. nested: u32, /// For an effect with `multi ctl` operations. multi: Option, } /// The captures of a multi-shot handler. struct Multi { /// Bit `i`: operation `i` is `multi ctl` (the others are `ctl`). ops: u64, captures: Vec, /// The capture the fiber's stack holds, suspended at its operation. occupant: Option, /// The body runs, or waits for another handler (the stack is in use). in_use: bool, } struct Capture { held: Held, /// By a `multi ctl` operation (a `ctl` one is resumed once). multi: bool, resumed: u32, /// Other `ctl` handlers' fibers were active on the stack. holds_fiber: bool, } enum Held { /// In the fiber's stack (the occupant). Live, Saved(Snapshot), /// Resumed for the last time, or released. Gone, } const WORD: usize = size_of::(); /// # Safety /// `block` must be a live frame block. unsafe fn frame<'a>(block: Value) -> &'a mut Frame { // SAFETY: caller guarantees a frame block; its raw area holds the box. unsafe { &mut *Block::fields_ptr(block as *mut Block) .cast::<*mut Frame>() .read() } } /// Called when a frame block is freed: release what the frame owns. /// /// # Safety /// `b` must be a frame block being freed. pub(crate) unsafe fn free_frame(b: *mut Block, pending: &mut Vec<*mut Block>) { // SAFETY: caller guarantees a frame block made by `tl_handle_ctl`; the // box is freed exactly once, here. unsafe { let f = Box::from_raw(Block::fields_ptr(b).cast::<*mut Frame>().read()); let Frame { fiber, cap, ret, .. } = *f; if let Some(fiber) = fiber { // Never happens (fibers finish or are cancelled first). A // suspended fiber must not be dropped (its frames never ran // their drops): leak it instead. std::mem::forget(fiber); } crate::heap::release_into(cap, pending); crate::heap::release_into(ret, pending); } } /// # Safety /// `ctx` must be the running actor's context. unsafe fn current<'a>(ctx: *mut Ctx) -> &'a mut *const Running { // SAFETY: forwarded caller guarantee. unsafe { crate::sched::current_handler(ctx) } } /// Acquire a mapping of the handler size, reusing only that separate pool's /// stacks. The existing `Stack::new` sets up the guard page on a pool miss. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn acquire_handler_stack(ctx: *mut Ctx) -> Stack { // SAFETY: forwarded caller guarantee. let (_, sched) = unsafe { crate::sched::this(ctx) }; sched.take_handler_stack().unwrap_or_else(|| { Stack::new(HANDLER_STACK_SIZE).expect("louise: cannot allocate a handler fiber") }) } /// Recycle a returned handler coroutine's mapping into the 16 MiB pool. /// /// # Safety /// `ctx` must be the running actor's context. `fiber` must have returned, /// and no snapshot may be capable of restoring its old addresses. In /// particular, this is called for multi-shot handlers only at final /// [`finish`], after all captures have become `Held::Gone`. unsafe fn recycle_handler(ctx: *mut Ctx, fiber: HandlerFiber) { let stack = fiber.into_stack(); // SAFETY: forwarded caller guarantee; `into_stack` conversion is done // before taking the scheduler lock, and `fiber` cannot be dropped again. let (_, sched) = unsafe { crate::sched::this(ctx) }; sched.pool_handler_stack(stack); } /// Run `body` (consumed) under a handler with `ctl` operations, whose /// capability `cap` (consumed) holds the clauses and the marker, and whose /// return clause is `ret` (consumed; unit if none). /// /// # Safety /// `ctx` must be the running actor's context; the values must be owned and /// follow the generated-code conventions. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_handle_ctl( ctx: *mut Ctx, body: Value, cap: Value, ret: Value, marker: u64, ) -> Value { // SAFETY: forwarded caller guarantee. unsafe { handle(ctx, body, cap, ret, marker, None) } } /// [`tl_handle_ctl`] for an effect with `multi ctl` operations: bit `i` /// of `multi_ops` is set if operation `i` is one. /// /// # Safety /// As for [`tl_handle_ctl`]. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_handle_multi( ctx: *mut Ctx, body: Value, cap: Value, ret: Value, marker: u64, multi_ops: u64, ) -> Value { // SAFETY: forwarded caller guarantee. unsafe { handle(ctx, body, cap, ret, marker, Some(multi_ops)) } } /// # Safety /// As for [`tl_handle_ctl`]. unsafe fn handle( ctx: *mut Ctx, body: Value, cap: Value, ret: Value, marker: u64, multi_ops: Option, ) -> Value { let block = tl_alloc(ctx, TAG_FRAME, 0, WORD) as Value; // SAFETY: caller guarantees a live capability. let body_cap = unsafe { dup_value(cap) }; let f = Box::into_raw(Box::new(Frame { marker, fiber: None, cap, ret, suspensions: 0, waiting: false, cancelled: false, nested: 0, multi: multi_ops.map(|ops| Multi { ops, captures: Vec::new(), occupant: None, in_use: true, }), })); let (ctx_addr, frame_addr) = (ctx as usize, f as usize); // SAFETY: `handle`'s caller guarantees the running actor's context. // Acquisition reads that actor's scheduler and cannot suspend; entering // through an outer handler changes its current handler, not its owner. let stack = unsafe { acquire_handler_stack(ctx) }; let fiber = HandlerFiber::with_stack(stack, move |yielder: &HandlerYielder, _: Resume| { let ctx = ctx_addr as *mut Ctx; // SAFETY: the fiber runs on the actor that created it. unsafe { let running = Running { yielder, frame: frame_addr as *mut Frame, }; *current(ctx) = &running; call_closure(ctx, body, &[body_cap, UNIT]) } }); // SAFETY: `f` is the fresh frame; the raw area holds its pointer. The // frame whose fiber runs this code (if any) outlives this call. unsafe { (*f).fiber = Some(fiber); Block::fields_ptr(block as *mut Block) .cast::<*mut Frame>() .write(f); let running = *current(ctx); let parent = if running.is_null() { std::ptr::null_mut() } else { (*running).frame }; if !parent.is_null() { (*parent).nested += 1; } let mut result = drive(ctx, block, Resume::Value(UNIT)); if finish(ctx, block) { drop_value(ctx, result); result = UNIT; } if !parent.is_null() { (*parent).nested -= 1; } drop_value(ctx, block); result } } /// Perform a `ctl` operation of the handler whose capability is `cap` /// (borrowed); `payload` (consumed) is the operation's index and /// arguments. Returns the value it is resumed with; when cancelled, /// returns unit with `yielding = CANCEL` (generated code unwinds). /// /// # Safety /// `ctx` must be the running actor's context; `cap` a handler capability. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_perform_ctl(ctx: *mut Ctx, cap: Value, payload: Value) -> Value { // SAFETY: caller guarantees a capability block: clauses, then marker. unsafe { let b = cap as *mut Block; let n = (*b).header.scan_fsize as usize; let marker = int_get(*Block::fields_ptr(b).add(n - 1)) as u64; suspend(ctx, Request::Op { marker, payload }) } } /// Suspend the current fiber with `request`; the answer, or unit and /// `yielding` set (cancelled, or a pass over a multi-shot capture). /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn suspend(ctx: *mut Ctx, request: Request) -> Value { // SAFETY: forwarded caller guarantee; `current` is the yielder of the // fiber executing this code. unsafe { let y = *current(ctx); if y.is_null() { if let Request::Op { payload, .. } = request { drop_value(ctx, payload); } return crate::effects::tl_panic_str( ctx, c"an operation reached the actor's root without a handler".as_ptr(), ); } let answer = (*(*y).yielder).suspend(request); *current(ctx) = y; let mode = match answer { Resume::Value(v) => return v, Resume::Cancel => YIELD_CANCEL, Resume::Clone => YIELD_CLONE, Resume::Discard => YIELD_DISCARD, }; (*ctx).yielding = mode; UNIT } } /// Preempt from inside a handler fiber: forward to the parent, up to the /// actor's own fiber. Returns false at the actor's root stack. /// /// # Safety /// `ctx` must be the running actor's context. pub(crate) unsafe fn preempt_in_fiber(ctx: *mut Ctx) -> bool { // SAFETY: forwarded caller guarantee. unsafe { if current(ctx).is_null() { return false; } let v = suspend(ctx, Request::Preempt); drop_value(ctx, v); true } } /// Run the frame's fiber with `input` until it finishes or performs an /// operation of this handler; returns the handler's result. /// /// A clause that calls `resume` and then does more work (`x + resume(())`) /// nests `resume_code`, `drive` and `call_clause` once per operation, so /// `drive`'s frame is paid once per pending `resume`: 100,000 of them in /// `tests/bench/effects.lse`. Running the fiber needs a large frame, so it /// is out of line ([`run`]), and what nests here is only the call of the /// clause. Inlined, with the runtime built as one LTO unit (ADR 0031), it /// took 352 bytes of stack per operation instead of 192: twice the page /// faults, and `effects` 17% slower. /// /// # Safety /// `ctx` must be the running actor's context; `block` a live frame. unsafe fn drive(ctx: *mut Ctx, block: Value, input: Resume) -> Value { // SAFETY: forwarded caller guarantee; the frame outlives the call. unsafe { match run(ctx, block, input) { Stop::Done(value) => value, Stop::Clause(payload, resume) => call_clause(ctx, frame(block).cap, payload, resume), } } } /// Where [`run`] left a handler. enum Stop { /// Its result. Done(Value), /// The operation in the payload is to be handled by its clause, with /// this `resume` (none for a `final ctl`). Clause(Value, Option), } /// [`drive`]'s loop: resume the fiber until the handler has a result or /// a clause to run. /// /// # Safety /// As [`drive`]. #[inline(never)] unsafe fn run(ctx: *mut Ctx, block: Value, mut input: Resume) -> Stop { // SAFETY: caller guarantees a live frame; the fiber runs on this actor. unsafe { loop { let f = frame(block); let Some(mut fiber) = f.fiber.take() else { return Stop::Done(crate::effects::tl_panic_str( ctx, c"`resume` called after its handler finished".as_ptr(), )); }; let saved = *current(ctx); let step = fiber.resume(input); *current(ctx) = saved; let f = frame(block); match step { CoroutineResult::Return(value) => { match &mut f.multi { // Kept: saved captures are written back into it. Some(m) => { m.occupant = None; m.in_use = false; f.fiber = Some(fiber); } // One-shot frames own no snapshots, so `Return` // ends both coroutine and stack-address lifetimes. None => recycle_handler(ctx, fiber), } let c = &mut *ctx; if c.yielding == YIELD_FINAL && c.yield_marker == f.marker { let payload = std::mem::replace(&mut c.yield_value, UNIT); c.yielding = YIELD_NONE; return Stop::Clause(payload, None); } if c.yielding != YIELD_NONE { return Stop::Done(UNIT); // unwinding continues in the caller } if is_ptr(f.ret) { return Stop::Done(call_closure(ctx, dup_value(f.ret), &[value])); } return Stop::Done(value); } CoroutineResult::Yield(request) => { f.fiber = Some(fiber); match request { Request::Preempt => { if !preempt_in_fiber(ctx) { crate::sched::preempt_root(ctx); } input = Resume::Value(UNIT); } Request::Op { marker, payload } if marker == f.marker => { let resume = if f.multi.is_some() { capture(ctx, block, payload) } else { f.suspensions += 1; f.waiting = true; resume_closure(ctx, block, f.suspensions, resume_code) }; return Stop::Clause(payload, Some(resume)); } Request::Op { marker, payload } => { // Not ours: ask the handlers around this one. let answer = suspend(ctx, Request::Op { marker, payload }); input = if (*ctx).yielding == YIELD_CANCEL { Resume::Cancel } else { Resume::Value(answer) }; if let Resume::Cancel = input { // The fiber around us is being cancelled: // cancel ours, then keep unwinding (or // unwind as a cleanup of ours did). (*ctx).yielding = YIELD_NONE; if !finish(ctx, block) { (*ctx).yielding = YIELD_CANCEL; } return Stop::Done(UNIT); } } } } } } } } /// A multi-shot handler's fiber suspended at one of its operations (in /// `payload`, borrowed): record the capture; returns its `resume` /// closure. Out of line, so that `drive` /// keeps the stack frame it had for one-shot handlers (nested `resume`s /// recurse through it). /// /// # Safety /// `ctx` must be the running actor's context; `block` a live multi frame. #[inline(never)] unsafe fn capture(ctx: *mut Ctx, block: Value, payload: Value) -> Value { // SAFETY: forwarded caller guarantee; the payload starts with the // operation's index. unsafe { let f = frame(block); let holds_fiber = f.nested > 0; let m = f.multi.as_mut().expect("multi"); let op = int_get(*Block::fields_ptr(payload as *mut Block)) as u32; let multi = op < 64 && m.ops & (1 << op) != 0; m.captures.push(Capture { held: Held::Live, multi, resumed: 0, holds_fiber, }); let index = m.captures.len() - 1; m.occupant = Some(index); m.in_use = false; resume_closure(ctx, block, index as i64, multi_resume_code) } } /// The handler is done: cancel the suspended body (one-shot), or release /// every capture left (multi-shot; see the module documentation). Returns /// whether the released code started an unwinding of its own, which then /// replaces the caller's. /// /// # Safety /// `ctx` must be the running actor's context; `block` a live frame. #[inline(never)] unsafe fn finish(ctx: *mut Ctx, block: Value) -> bool { // SAFETY: caller guarantees a live frame on this actor. unsafe { let f = frame(block); let Some(m) = &mut f.multi else { f.waiting = false; if f.fiber.is_some() { f.cancelled = true; } return run_out(ctx, block, Resume::Cancel); }; let mut started = false; // A computation suspended in another handler's operation (the code // around this handler is being cancelled) unwinds first. if m.in_use && f.fiber.is_some() { m.in_use = false; started |= run_out(ctx, block, Resume::Cancel); } let mut index = 0; loop { let f = frame(block); let m = f.multi.as_mut().expect("multi"); let Some(capture) = m.captures.get(index) else { break; }; if !matches!(capture.held, Held::Gone) { let mode = if capture.resumed == 0 { Resume::Cancel } else { Resume::Discard }; materialize(f, index); let m = f.multi.as_mut().expect("multi"); m.captures[index].held = Held::Gone; m.occupant = None; started |= run_out(ctx, block, mode); } index += 1; } let f = frame(block); // Late resume closures now stop before `run`. All non-`Gone` // captures were materialised and driven to `Return` above, so no // snapshot can subsequently restore this mapping's addresses. f.cancelled = true; let m = f.multi.as_ref().expect("multi"); debug_assert!(m.occupant.is_none(), "louise: live multi capture at finish"); debug_assert!( m.captures.iter().all(|c| matches!(c.held, Held::Gone)), "louise: saved multi capture at finish" ); if let Some(fiber) = f.fiber.take() { recycle_handler(ctx, fiber); } started } } /// If the frame's fiber is suspended, resume it with `mode` (cancel or /// discard) so it unwinds (dropping what it holds; when cancelled, running /// its cleanups) and finishes. The unwinding state of the caller is /// preserved, unless the code started an unwinding of its own (a cleanup /// panicked, or the actor was killed): that one replaces it, and this /// returns true. /// /// # Safety /// `ctx` must be the running actor's context; `block` a live frame. #[inline(never)] unsafe fn run_out(ctx: *mut Ctx, block: Value, mode: Resume) -> bool { // SAFETY: caller guarantees a live frame on this actor. unsafe { let f = frame(block); let Some(mut fiber) = f.fiber.take() else { return false; }; let keep = f.multi.is_some(); let flag = match mode { Resume::Discard => YIELD_DISCARD, _ => YIELD_CANCEL, }; let c = &mut *ctx; let saved = ( c.yielding, c.yield_marker, std::mem::replace(&mut c.yield_value, UNIT), ); c.yielding = YIELD_NONE; let outer = *current(ctx); let mut input = mode; loop { match fiber.resume(input) { CoroutineResult::Return(value) => { drop_value(ctx, value); break; } // Cancelled code can still preempt (or, in a clause run // while unwinding, perform): keep it going. CoroutineResult::Yield(Request::Preempt) => { *current(ctx) = outer; if !preempt_in_fiber(ctx) { crate::sched::preempt_root(ctx); } input = Resume::Value(UNIT); } CoroutineResult::Yield(Request::Op { payload, .. }) => { drop_value(ctx, payload); input = Resume::Cancel; } } } *current(ctx) = outer; if keep { frame(block).fiber = Some(fiber); } else { // A suspended one-shot body is not finished merely because its // handle ended. Reclaim only now, after this cancellation // drive reached `Return`; both ordinary and already-unwinding // exits below therefore retain the same reclamation path. recycle_handler(ctx, fiber); } let c = &mut *ctx; if c.yielding != YIELD_NONE && c.yielding != flag { drop_value(ctx, saved.2); return true; } drop_value(ctx, std::mem::replace(&mut c.yield_value, saved.2)); c.yielding = saved.0; c.yield_marker = saved.1; false } } /// Make capture `index` the one the fiber's stack holds, saving the /// occupant first. Returns a copy of what the stack now holds, if it had to /// be written back (the saved capture). #[inline(never)] fn materialize(f: &mut Frame, index: usize) -> Option { let fiber = f .fiber .as_mut() .expect("louise: a multi-shot handler keeps its fiber"); let m = f.multi.as_mut().expect("multi"); if m.occupant == Some(index) { return None; } if let Some(occupant) = m.occupant.take() { m.captures[occupant].held = Held::Saved(fiber.snapshot()); } let Held::Saved(snap) = std::mem::replace(&mut m.captures[index].held, Held::Live) else { unreachable!("louise: a capture that is neither held nor saved"); }; fiber.restore(&snap); m.occupant = Some(index); Some(snap) } /// Call the clause of `cap` for the operation in `payload` (consumed): /// its arguments, then `resume` if given. /// /// # Safety /// `ctx` must be the running actor's context; `cap` a live capability. unsafe fn call_clause(ctx: *mut Ctx, cap: Value, payload: Value, resume: Option) -> Value { // SAFETY: caller guarantees a capability and a payload block. unsafe { let p = payload as *mut Block; let n = (*p).header.scan_fsize as usize; let fields = Block::fields_ptr(p); let op = int_get(*fields) as usize; let clause = dup_value(*Block::fields_ptr(cap as *mut Block).add(op)); // The generated-code convention, without a vector: the call is the // last thing done, so it can reuse this frame (a clause calling // `resume` nests this code once per operation). let mut regs = [UNIT; 5]; let args = (1..n).map(|i| dup_value(*fields.add(i))).chain(resume); for (i, a) in args.enumerate() { if i < 5 { regs[i] = a; } else { *(*ctx).xargs.add(i - 5) = a; } } drop_value(ctx, payload); let code: ResumeCode = std::mem::transmute(crate::values::closure_code(clause)); code(ctx, clause, regs[0], regs[1], regs[2], regs[3], regs[4]) } } type ResumeCode = unsafe extern "C" fn(*mut Ctx, Value, Value, Value, Value, Value, Value) -> Value; /// A `resume` closure running `code`, for suspension `seq` of the frame in /// `block`. /// /// # Safety /// `ctx` must be the running actor's context; `block` a live frame. unsafe fn resume_closure(ctx: *mut Ctx, block: Value, seq: i64, code: ResumeCode) -> Value { // SAFETY: closure code is stored type-erased and called with the // generated-code signature, which `code` has. The borrowed entry // (ADR 0068) is the one-argument adapter: `resume(x)` takes one. let erased = unsafe { std::mem::transmute::(code) }; // SAFETY: same erasure; `tl_borrowed1` has the generated-code // signature. let erased_borrowed = unsafe { std::mem::transmute::(crate::values::tl_borrowed1) }; let c = crate::values::tl_closure_alloc(ctx, erased, erased_borrowed, 2); // SAFETY: a fresh closure with two environment fields. unsafe { let env = Block::fields_ptr(c as *mut Block); env.write(dup_value(block)); env.add(1).write(int(seq)); } c } /// `resume(x)` of a one-shot handler: continue the suspended fiber with /// `x`. unsafe extern "C" fn resume_code( ctx: *mut Ctx, this: Value, x: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: `this` is a resume closure made by `resume_closure`, owned by // this call. unsafe { let env = Block::fields_ptr(this as *mut Block); let block = *env; let seq = int_get(*env.add(1)); let f = frame(block); let message = if f.cancelled { c"`resume` called after its handler finished" } else if !f.waiting || f.suspensions != seq { c"`resume` called twice (continuations are one-shot)" } else { // The fiber waits, so the handler has not finished: its // `tl_handle_ctl` keeps the frame alive while `drive` runs, and // this closure can go first, leaving `drive` the last call. f.waiting = false; drop_value(ctx, this); return drive(ctx, block, Resume::Value(x)); }; drop_value(ctx, this); drop_value(ctx, x); crate::effects::tl_panic_str(ctx, message.as_ptr()) } } /// `resume(x)` of a multi-shot handler's capture: run it (its last use), /// or a copy of it, with `x`. unsafe extern "C" fn multi_resume_code( ctx: *mut Ctx, this: Value, x: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: `this` is a resume closure made by `resume_closure`, owned by // this call; its frame is live while it holds it. unsafe { let env = Block::fields_ptr(this as *mut Block); let block = *env; let index = int_get(*env.add(1)) as usize; let last_use = crate::heap::rc(this as *mut Block) == 1; let prepared = prepare(ctx, block, index, last_use); // As in `resume_code`: once prepared, the handler is running, and // its `tl_handle_multi` keeps the frame alive. drop_value(ctx, this); match prepared { Ok(()) => drive(ctx, block, Resume::Value(x)), Err(message) => { drop_value(ctx, x); crate::effects::tl_panic_str(ctx, message.as_ptr()) } } } } /// Check that capture `index` can be resumed (in the interpreter's order /// of checks), and leave in the fiber's stack what is to run: the capture /// itself on its last use, otherwise a copy owning references of its own. /// /// # Safety /// `ctx` must be the running actor's context; `block` a live multi frame. #[inline(never)] unsafe fn prepare( ctx: *mut Ctx, block: Value, index: usize, last_use: bool, ) -> Result<(), &'static std::ffi::CStr> { // SAFETY: forwarded caller guarantee. unsafe { let f = frame(block); if f.cancelled { return Err(c"`resume` called after its handler finished"); } let m = f.multi.as_mut().expect("multi"); if m.in_use { return Err(c"`resume` called while its handler's body is running"); } let capture = &m.captures[index]; let copy = capture.multi && !last_use; if capture.multi && capture.holds_fiber { return Err(c"a `multi ctl` continuation holding a `ctl` handler cannot be resumed"); } if matches!(capture.held, Held::Gone) { return Err(c"`resume` called twice (continuations are one-shot)"); } let kept = materialize(f, index); let m = f.multi.as_mut().expect("multi"); if copy { let fiber = f.fiber.as_mut().expect("fiber"); let snap = kept.unwrap_or_else(|| fiber.snapshot()); copying_pass(ctx, fiber); fiber.restore(&snap); m.captures[index].held = Held::Saved(snap); } else { m.captures[index].held = Held::Gone; } m.occupant = None; m.captures[index].resumed += 1; m.in_use = true; Ok(()) } } /// Resume the suspended `fiber` with `yielding = CLONE`: its frames take one /// more reference to everything they hold and return, so it finishes. The /// caller's unwinding state is preserved. /// /// # Safety /// `ctx` must be the running actor's context; `fiber` suspended at a /// multi-shot capture without other handler fibers in it. #[inline(never)] unsafe fn copying_pass(ctx: *mut Ctx, fiber: &mut HandlerFiber) { // SAFETY: forwarded caller guarantee. unsafe { let c = &mut *ctx; let saved = ( c.yielding, c.yield_marker, std::mem::replace(&mut c.yield_value, UNIT), ); c.yielding = YIELD_NONE; let outer = *current(ctx); match fiber.resume(Resume::Clone) { CoroutineResult::Return(value) => drop_value(ctx, value), CoroutineResult::Yield(_) => panic!("louise: a copying pass suspended"), } *current(ctx) = outer; let c = &mut *ctx; debug_assert_eq!(c.yielding, YIELD_CLONE, "louise: a copying pass unwound"); c.yielding = saved.0; c.yield_marker = saved.1; c.yield_value = saved.2; } }