| @@ -4,40 +4,41 @@ |
| 4 | 4 | //! afterwards serves as the test oracle: every `tests/run` program must |
| 5 | 5 | //! print the same thing interpreted and compiled (M5). |
| 6 | 6 | //! |
| 7 | | −//! - Calls in tail position are trampolined, so loops written as tail |
| 8 | | −//! recursion run in constant stack. Other recursion uses the native |
| 9 | | −//! stack; programs run on a thread with a large stack. |
| 10 | | −//! - Every actor (including `main`) runs on a fiber driven by the |
| 7 | +//! **A CEK machine** ([`Machine`]): the code being evaluated, the current |
| 8 | +//! function's variables, and an explicit stack of [`Frame`]s for the rest |
| 9 | +//! of the computation (ADR 0017). Nothing recurses on the Rust stack, and |
| 10 | +//! continuations are first-class: |
| 11 | +//! - Calls in tail position replace the current activation, so loops |
| 12 | +//! written as tail recursion run in constant space. |
| 13 | +//! - `handle` pushes a [`Frame::Handler`] delimiter. A `ctl` operation |
| 14 | +//! *captures* the frames above its handler's (a continuation, given to |
| 15 | +//! the clause as `resume`); `resume` pushes them back. A one-shot |
| 16 | +//! continuation is moved back, a `multi ctl` one is copied, so it can be |
| 17 | +//! resumed again. Handlers are lexically scoped (ADR 0010): an |
| 18 | +//! operation names its handler's capability, and the frame with that |
| 19 | +//! identity handles it; operations of the runtime's [`ROOT`] capability |
| 20 | +//! go to the actor's scheduler. |
| 21 | +//! - **Unwinding** (a panic, a kill, a `final ctl` operation, a |
| 22 | +//! cancelled continuation) pops frames, running `defer` cleanups and |
| 23 | +//! ending regions on the way (ADR 0016). |
| 24 | +//! - Every actor (including `main`) is a machine driven by the |
| 11 | 25 | //! deterministic scheduler in [`crate::sched`]. |
| 12 | | −//! - Each `handle` body runs on its own fiber (corosensei). Performing an |
| 13 | | −//! operation suspends the current fiber with a request naming the |
| 14 | | −//! capability it uses (handlers are lexically scoped, ADR 0010); the |
| 15 | | −//! handler frame with that identity either answers it (`fn` clauses), |
| 16 | | −//! hands its clause a one-shot `resume` that continues the fiber |
| 17 | | −//! (`ctl`), or unwinds the fiber, then runs its clause (`final ctl`). |
| 18 | | −//! Frames forward requests for other capabilities outward; the actor's |
| 19 | | −//! root answers the runtime's [`ROOT`] capability. |
| 20 | | −//! - **Unwinding** is an `Err` returned through the Rust frames, so |
| 21 | | −//! `defer` cleanups run on the way (ADR 0016). A suspended fiber is |
| 22 | | −//! never dropped: it is resumed with an error (a cancellation, a kill) |
| 23 | | −//! and unwinds like the native backend's, innermost frames first. An |
| 24 | | −//! error answering a forwarded request is delivered into the body |
| 25 | | −//! first, for the same reason. |
| 26 | +//! |
| 27 | +//! **Matching the native backend.** Where the native runtime's fibers |
| 28 | +//! limit what can be done, the interpreter checks the same conditions and |
| 29 | +//! panics with the same messages: `resume` after its handler finished, a |
| 30 | +//! one-shot `resume` called twice, a multi-shot `resume` while its |
| 31 | +//! handler's body runs, or of a continuation holding a `ctl` handler. |
| 26 | 32 | |
| 27 | 33 | use std::cell::{Cell, RefCell}; |
| 28 | 34 | use std::fmt; |
| 29 | 35 | use std::io::Write; |
| 30 | 36 | use std::rc::Rc; |
| 31 | 37 | |
| 32 | | −use corosensei::stack::DefaultStack; |
| 33 | | −use corosensei::{Coroutine, CoroutineResult, Yielder}; |
| 34 | | − |
| 35 | 38 | use crate::ir::*; |
| 36 | 39 | |
| 37 | | −/// Virtual size of each handler fiber's stack (committed lazily). |
| 38 | | −const FIBER_STACK: usize = 64 << 20; |
| 39 | 40 | /// Stack size of the thread running the program. |
| 40 | | −pub const MAIN_STACK: usize = 1 << 30; |
| 41 | +pub const MAIN_STACK: usize = 64 << 20; |
| 41 | 42 | |
| 42 | 43 | #[derive(Clone)] |
| 43 | 44 | pub enum Val { |
| @@ -108,9 +109,8 @@ impl fmt::Debug for Val { |
| 108 | 109 | pub enum RtError { |
| 109 | 110 | Panic(String), |
| 110 | 111 | Unhandled(String), |
| 111 | | − /// A suspended handler body that will never be resumed unwinds: its |
| 112 | | − /// handler finished first (`ctl`), or a `final ctl` operation left it. |
| 113 | | − /// It stops at that handler. |
| 112 | + /// A captured continuation that will never be resumed unwinds: its |
| 113 | + /// handler finished first. It stops at that handler. |
| 114 | 114 | Cancelled, |
| 115 | 115 | /// The actor was killed: it unwinds to its root. |
| 116 | 116 | Killed, |
| @@ -133,66 +133,215 @@ pub(crate) fn panic<T>(msg: impl Into<String>) -> R<T> { |
| 133 | 133 | Err(RtError::Panic(msg.into())) |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | +/// Unwind with a panic. |
| 137 | +fn fail<T>(msg: impl Into<String>) -> Result<T, Unwind> { |
| 138 | + Err(Unwind::Error(RtError::Panic(msg.into()))) |
| 139 | +} |
| 140 | + |
| 136 | 141 | /// The capability of the runtime's own handlers (`proc`), given to `main`, |
| 137 | 142 | /// tests and every actor body. |
| 138 | 143 | pub(crate) const ROOT: u64 = 0; |
| 139 | 144 | |
| 145 | +/// An operation for the scheduler: of the [`ROOT`] capability, or the |
| 146 | +/// pseudo-effect [`crate::sched::PREEMPT`]. |
| 140 | 147 | pub(crate) struct OpRequest { |
| 141 | | − /// The handler frame the request is for. |
| 142 | 148 | pub(crate) cap: u64, |
| 143 | 149 | pub(crate) effect: EffectId, |
| 144 | 150 | pub(crate) op: u32, |
| 145 | 151 | pub(crate) args: Vec<Val>, |
| 146 | 152 | } |
| 147 | 153 | |
| 148 | | −/// A fiber is resumed with the answer to its request, or with an error |
| 149 | | −/// that makes it unwind. |
| 150 | | −pub(crate) type Fiber = Coroutine<R<Val>, OpRequest, R<Val>, DefaultStack>; |
| 151 | | −pub(crate) type FiberYielder = Yielder<R<Val>, OpRequest>; |
| 154 | +/// Code in a function body of the program. |
| 155 | +/// |
| 156 | +/// The program is shared (`Rc`) by the interpreter and never changes, and |
| 157 | +/// every machine and value lives on the interpreter's thread and is gone |
| 158 | +/// before [`run`] returns, so the pointer stays valid as long as anything |
| 159 | +/// holds it. |
| 160 | +#[derive(Clone, Copy)] |
| 161 | +struct Code(*const Expr); |
| 162 | + |
| 163 | +impl Code { |
| 164 | + fn new(e: &Expr) -> Self { |
| 165 | + Code(e) |
| 166 | + } |
| 167 | + |
| 168 | + fn get<'a>(self) -> &'a Expr { |
| 169 | + // SAFETY: see the type's documentation. |
| 170 | + unsafe { &*self.0 } |
| 171 | + } |
| 172 | +} |
| 152 | 173 | |
| 153 | | −/// An installed handler: the suspended body fiber and the clauses. |
| 154 | | −pub struct HandlerFrame { |
| 174 | +/// A handler installed by `handle` (or `region`). |
| 175 | +struct HandlerInfo { |
| 155 | 176 | /// Its capability. |
| 156 | 177 | id: u64, |
| 157 | | − fiber: RefCell<Option<Fiber>>, |
| 158 | 178 | /// The effects handled here, each with one clause per operation. |
| 159 | 179 | handled: Vec<(EffectId, Vec<Val>)>, |
| 160 | 180 | ret: Option<Val>, |
| 161 | | − /// The handler finished while its body waited for a `resume`, and the |
| 162 | | − /// body was cancelled. |
| 181 | + /// Natively the body runs on a fiber of its own: the effect has `ctl` |
| 182 | + /// or `multi ctl` operations. |
| 183 | + fiber: bool, |
| 184 | + /// The effect has `multi ctl` operations. |
| 185 | + multi: bool, |
| 186 | + /// The body runs, or waits for another handler's operation (natively, |
| 187 | + /// its fiber is in use). |
| 188 | + in_use: Cell<bool>, |
| 189 | + /// Continuations captured by its operations, in order. |
| 190 | + pending: RefCell<Vec<Rc<ResumeCell>>>, |
| 191 | + /// The handler finished and cancelled or released a continuation: a |
| 192 | + /// `resume` now panics. |
| 163 | 193 | cancelled: Cell<bool>, |
| 164 | 194 | } |
| 165 | 195 | |
| 166 | | −/// A one-shot continuation. |
| 196 | +/// A captured continuation: the frames from the handler's up to the |
| 197 | +/// operation. |
| 167 | 198 | pub struct ResumeCell { |
| 168 | | − frame: Rc<HandlerFrame>, |
| 169 | | − used: Cell<bool>, |
| 199 | + handler: Rc<HandlerInfo>, |
| 200 | + frames: RefCell<Option<Vec<Frame>>>, |
| 201 | + /// From a `multi ctl` operation: `resume` copies the frames. |
| 202 | + multi: bool, |
| 203 | + resumed: Cell<u32>, |
| 204 | + /// The frames hold another handler whose body runs on a fiber natively |
| 205 | + /// (it cannot be copied there). |
| 206 | + holds_fiber: bool, |
| 207 | +} |
| 208 | + |
| 209 | +/// Ends a region (clears its references) when the last copy of its frame |
| 210 | +/// is gone: continuations copied by `multi ctl` share it (ADR 0017). |
| 211 | +struct RegionGuard { |
| 212 | + refs: Rc<RefCell<Vec<Rc<RefCell<Val>>>>>, |
| 213 | +} |
| 214 | + |
| 215 | +impl Drop for RegionGuard { |
| 216 | + fn drop(&mut self) { |
| 217 | + for cell in self.refs.borrow().iter() { |
| 218 | + *cell.borrow_mut() = Val::Unit; |
| 219 | + } |
| 220 | + } |
| 221 | +} |
| 222 | + |
| 223 | +/// Why the stack is unwinding. |
| 224 | +#[derive(Clone)] |
| 225 | +enum Unwind { |
| 226 | + Error(RtError), |
| 227 | + /// A `final ctl` operation: unwind to the handler `target`, then run |
| 228 | + /// `clause` with `args`. |
| 229 | + Final { |
| 230 | + target: u64, |
| 231 | + clause: Val, |
| 232 | + args: Vec<Val>, |
| 233 | + }, |
| 234 | +} |
| 235 | + |
| 236 | +/// What to do with the value of the code above. |
| 237 | +#[derive(Clone)] |
| 238 | +enum Frame { |
| 239 | + /// The rest of a block of the current function: bind, continue. |
| 240 | + Bind { |
| 241 | + var: VarId, |
| 242 | + rest: Code, |
| 243 | + }, |
| 244 | + /// The rest of the calling function: restore its variables, bind, |
| 245 | + /// continue. |
| 246 | + Return { |
| 247 | + env: Vec<Val>, |
| 248 | + var: VarId, |
| 249 | + rest: Code, |
| 250 | + }, |
| 251 | + /// A handler's delimiter: the body's value goes through the return |
| 252 | + /// clause. |
| 253 | + Handler(Rc<HandlerInfo>), |
| 254 | + /// Below a handler: when the handler is done (its body or a clause |
| 255 | + /// returned, or it unwound), the continuations it left behind are |
| 256 | + /// cancelled or released. |
| 257 | + Finish(Rc<HandlerInfo>), |
| 258 | + Region(Rc<RegionGuard>), |
| 259 | + /// A `defer` cleanup, run when the frame is left. |
| 260 | + Defer(Val), |
| 261 | + /// After a cleanup: continue with this outcome. |
| 262 | + Then(Result<Val, Unwind>), |
| 263 | + /// The bottom of a continuation being cancelled. |
| 264 | + CancelStop, |
| 265 | +} |
| 266 | + |
| 267 | +enum Control { |
| 268 | + Eval(Code), |
| 269 | + Value(Val), |
| 270 | + Unwind(Unwind), |
| 271 | + /// Enter function `f` with these arguments. |
| 272 | + Enter(FnId, Vec<Val>), |
| 273 | +} |
| 274 | + |
| 275 | +/// One computation: an actor's. |
| 276 | +pub(crate) struct Machine { |
| 277 | + stack: Vec<Frame>, |
| 278 | + env: Vec<Val>, |
| 279 | + control: Control, |
| 280 | + /// Stopped at a request whose answer is the value of the code above |
| 281 | + /// (not at a preemption, nor before it started). |
| 282 | + waiting: bool, |
| 283 | +} |
| 284 | + |
| 285 | +/// Why [`Interp::run`] stopped. |
| 286 | +pub(crate) enum Step { |
| 287 | + Done(R<Val>), |
| 288 | + Request(OpRequest), |
| 289 | +} |
| 290 | + |
| 291 | +impl Machine { |
| 292 | + /// A machine calling `callee` (a closure) with `args`. |
| 293 | + pub(crate) fn call(interp: &Interp, callee: &Val, args: Vec<Val>) -> Machine { |
| 294 | + let mut m = Machine::new(); |
| 295 | + if let Err(u) = interp.apply(&mut m, callee, args) { |
| 296 | + m.control = Control::Unwind(u); |
| 297 | + } |
| 298 | + m |
| 299 | + } |
| 300 | + |
| 301 | + /// A machine calling function `f` with `args`. |
| 302 | + pub(crate) fn enter(f: FnId, args: Vec<Val>) -> Machine { |
| 303 | + let mut m = Machine::new(); |
| 304 | + m.control = Control::Enter(f, args); |
| 305 | + m |
| 306 | + } |
| 307 | + |
| 308 | + fn new() -> Machine { |
| 309 | + Machine { |
| 310 | + stack: Vec::new(), |
| 311 | + env: Vec::new(), |
| 312 | + control: Control::Value(Val::Unit), |
| 313 | + waiting: false, |
| 314 | + } |
| 315 | + } |
| 316 | + |
| 317 | + /// Continue with the answer to the request it stopped at, or with an |
| 318 | + /// error that makes it unwind. |
| 319 | + pub(crate) fn answer(&mut self, answer: R<Val>) { |
| 320 | + match answer { |
| 321 | + Err(e) => self.control = Control::Unwind(Unwind::Error(e)), |
| 322 | + Ok(v) if self.waiting => self.control = Control::Value(v), |
| 323 | + Ok(_) => {} |
| 324 | + } |
| 325 | + self.waiting = false; |
| 326 | + } |
| 170 | 327 | } |
| 171 | 328 | |
| 172 | 329 | pub(crate) struct State { |
| 173 | 330 | out: RefCell<Box<dyn Write>>, |
| 174 | | − /// The yielder of the fiber currently running, or null outside any |
| 175 | | − /// handler body. |
| 176 | | − pub(crate) current: Cell<*const FiberYielder>, |
| 177 | 331 | /// Calls since the running actor last yielded (preemption). |
| 178 | 332 | pub(crate) reductions: Cell<u32>, |
| 179 | 333 | /// The last capability handed out (0 is [`ROOT`]). |
| 180 | 334 | caps: Cell<u64>, |
| 181 | 335 | } |
| 182 | 336 | |
| 183 | | −enum Flow { |
| 184 | | − Done(Val), |
| 185 | | − Tail(FnId, Vec<Val>), |
| 186 | | −} |
| 187 | | − |
| 188 | 337 | #[derive(Clone)] |
| 189 | 338 | pub struct Interp { |
| 190 | 339 | pub(crate) program: Rc<Program>, |
| 191 | 340 | pub(crate) state: Rc<State>, |
| 192 | 341 | } |
| 193 | 342 | |
| 194 | | −/// Run `entry()` writing program output to `out`. Runs on a thread with a |
| 195 | | −/// large stack; returns the error that stopped the program, if any. |
| 343 | +/// Run `entry()` writing program output to `out`. Returns the error that |
| 344 | +/// stopped the program, if any. |
| 196 | 345 | pub fn run(program: Program, entry: FnId, out: Box<dyn Write + Send>) -> Result<(), RtError> { |
| 197 | 346 | std::thread::Builder::new() |
| 198 | 347 | .stack_size(MAIN_STACK) |
| @@ -201,7 +350,6 @@ pub fn run(program: Program, entry: FnId, out: Box<dyn Write + Send>) -> Result< |
| 201 | 350 | program: Rc::new(program), |
| 202 | 351 | state: Rc::new(State { |
| 203 | 352 | out: RefCell::new(out), |
| 204 | | − current: Cell::new(std::ptr::null()), |
| 205 | 353 | reductions: Cell::new(0), |
| 206 | 354 | caps: Cell::new(ROOT), |
| 207 | 355 | }), |
| @@ -215,83 +363,155 @@ pub fn run(program: Program, entry: FnId, out: Box<dyn Write + Send>) -> Result< |
| 215 | 363 | .unwrap_or_else(|_| Err(RtError::Panic("interpreter crashed".into()))) |
| 216 | 364 | } |
| 217 | 365 | |
| 366 | +/// Whether `e` is `return v`. |
| 367 | +fn returns(e: &Expr, v: VarId) -> bool { |
| 368 | + matches!(e, Expr::Return(Atom::Var(r)) if *r == v) |
| 369 | +} |
| 370 | + |
| 218 | 371 | impl Interp { |
| 219 | | − pub fn call_fn(&self, mut f: FnId, mut args: Vec<Val>) -> R<Val> { |
| 372 | + /// Run `m` until it finishes or stops at a request for the scheduler. |
| 373 | + pub(crate) fn run(&self, m: &mut Machine) -> Step { |
| 220 | 374 | loop { |
| 221 | | − // Preemption: after a budget of calls, let other actors run. |
| 222 | | − if !self.state.current.get().is_null() { |
| 223 | | − let n = self.state.reductions.get() + 1; |
| 224 | | − if n >= crate::sched::REDUCTIONS { |
| 225 | | − self.state.reductions.set(0); |
| 226 | | − self.perform(ROOT, crate::sched::PREEMPT, 0, Vec::new())?; |
| 227 | | − } else { |
| 228 | | − self.state.reductions.set(n); |
| 229 | | − } |
| 230 | | − } |
| 231 | | − let decl = &self.program.fns[f as usize]; |
| 232 | | − if args.len() != decl.params.len() { |
| 233 | | − return panic(format!( |
| 234 | | − "{} takes {} arguments, got {}", |
| 235 | | − decl.name, |
| 236 | | − decl.params.len(), |
| 237 | | − args.len() |
| 238 | | − )); |
| 239 | | − } |
| 240 | | − let mut env = vec![Val::Unit; decl.n_vars as usize]; |
| 241 | | − for (p, a) in decl.params.iter().zip(args) { |
| 242 | | − env[*p as usize] = a; |
| 243 | | − } |
| 244 | | − match self.eval(&mut env, &decl.body)? { |
| 245 | | − Flow::Done(v) => return Ok(v), |
| 246 | | − Flow::Tail(g, a) => { |
| 247 | | − f = g; |
| 248 | | − args = a; |
| 375 | + let control = std::mem::replace(&mut m.control, Control::Value(Val::Unit)); |
| 376 | + let next = match control { |
| 377 | + Control::Eval(code) => self.eval(m, code.get()), |
| 378 | + Control::Enter(f, args) => match self.enter(m, f, args) { |
| 379 | + Ok(true) => { |
| 380 | + return Step::Request(OpRequest { |
| 381 | + cap: ROOT, |
| 382 | + effect: crate::sched::PREEMPT, |
| 383 | + op: 0, |
| 384 | + args: Vec::new(), |
| 385 | + }); |
| 386 | + } |
| 387 | + Ok(false) => Ok(None), |
| 388 | + Err(u) => Err(u), |
| 389 | + }, |
| 390 | + Control::Value(v) => match m.stack.pop() { |
| 391 | + None => return Step::Done(Ok(v)), |
| 392 | + Some(frame) => self.give(m, frame, v), |
| 393 | + }, |
| 394 | + Control::Unwind(u) => match m.stack.pop() { |
| 395 | + None => { |
| 396 | + return Step::Done(Err(match u { |
| 397 | + Unwind::Error(e) => e, |
| 398 | + Unwind::Final { .. } => { |
| 399 | + RtError::Panic("`final ctl` reached no handler".into()) |
| 400 | + } |
| 401 | + })); |
| 402 | + } |
| 403 | + Some(frame) => self.unwind(m, frame, u), |
| 404 | + }, |
| 405 | + }; |
| 406 | + match next { |
| 407 | + Ok(None) => {} |
| 408 | + Ok(Some(request)) => { |
| 409 | + m.waiting = true; |
| 410 | + return Step::Request(request); |
| 249 | 411 | } |
| 412 | + Err(u) => m.control = Control::Unwind(u), |
| 250 | 413 | } |
| 251 | 414 | } |
| 252 | 415 | } |
| 253 | 416 | |
| 254 | | − pub(crate) fn call_val(&self, callee: &Val, args: Vec<Val>) -> R<Val> { |
| 417 | + /// Enter function `f`: count the call (preemption), bind the |
| 418 | + /// parameters. Returns whether the actor must yield first. |
| 419 | + fn enter(&self, m: &mut Machine, f: FnId, args: Vec<Val>) -> Result<bool, Unwind> { |
| 420 | + let decl = &self.program.fns[f as usize]; |
| 421 | + if args.len() != decl.params.len() { |
| 422 | + return fail(format!( |
| 423 | + "{} takes {} arguments, got {}", |
| 424 | + decl.name, |
| 425 | + decl.params.len(), |
| 426 | + args.len() |
| 427 | + )); |
| 428 | + } |
| 429 | + let mut env = vec![Val::Unit; decl.n_vars as usize]; |
| 430 | + for (p, a) in decl.params.iter().zip(args) { |
| 431 | + env[*p as usize] = a; |
| 432 | + } |
| 433 | + m.env = env; |
| 434 | + m.control = Control::Eval(Code::new(&decl.body)); |
| 435 | + // Preemption: after a budget of calls, let other actors run. |
| 436 | + let n = self.state.reductions.get() + 1; |
| 437 | + if n >= crate::sched::REDUCTIONS { |
| 438 | + self.state.reductions.set(0); |
| 439 | + return Ok(true); |
| 440 | + } |
| 441 | + self.state.reductions.set(n); |
| 442 | + Ok(false) |
| 443 | + } |
| 444 | + |
| 445 | + /// Call `callee` with `args`; its value goes to the frame on top. |
| 446 | + fn apply(&self, m: &mut Machine, callee: &Val, args: Vec<Val>) -> Result<(), Unwind> { |
| 255 | 447 | match callee { |
| 256 | 448 | Val::Closure { f, captures } => { |
| 257 | | − self.call_fn(*f, captures.iter().cloned().chain(args).collect()) |
| 449 | + let args = captures.iter().cloned().chain(args).collect(); |
| 450 | + m.control = Control::Enter(*f, args); |
| 451 | + Ok(()) |
| 258 | 452 | } |
| 259 | 453 | Val::Resume(cell) => { |
| 260 | | − // The same checks, in the same order, as the native runtime. |
| 261 | | − if cell.frame.cancelled.get() { |
| 262 | | − return panic("`resume` called after its handler finished"); |
| 263 | | − } |
| 264 | | − if cell.used.replace(true) { |
| 265 | | − return panic("`resume` called twice (continuations are one-shot)"); |
| 266 | | − } |
| 267 | 454 | let value = args.into_iter().next().unwrap_or(Val::Unit); |
| 268 | | − self.drive(&cell.frame, Ok(value)) |
| 455 | + self.resume(m, cell, value) |
| 269 | 456 | } |
| 270 | 457 | Val::RegionOp { refs, op } => { |
| 271 | 458 | let mut args = args.into_iter(); |
| 272 | | − match op { |
| 459 | + let v = match op { |
| 273 | 460 | RefOp::New => { |
| 274 | 461 | let cell = Rc::new(RefCell::new(args.next().unwrap_or(Val::Unit))); |
| 275 | 462 | refs.borrow_mut().push(cell.clone()); |
| 276 | | − Ok(Val::Ref(cell)) |
| 463 | + Val::Ref(cell) |
| 277 | 464 | } |
| 278 | 465 | RefOp::Get => match args.next() { |
| 279 | | − Some(Val::Ref(r)) => Ok(r.borrow().clone()), |
| 280 | | − other => panic(format!("ref.get on {other:?}")), |
| 466 | + Some(Val::Ref(r)) => r.borrow().clone(), |
| 467 | + other => return fail(format!("ref.get on {other:?}")), |
| 281 | 468 | }, |
| 282 | 469 | RefOp::Set => match (args.next(), args.next()) { |
| 283 | 470 | (Some(Val::Ref(r)), Some(v)) => { |
| 284 | 471 | *r.borrow_mut() = v; |
| 285 | | − Ok(Val::Unit) |
| 472 | + Val::Unit |
| 286 | 473 | } |
| 287 | | − other => panic(format!("ref.set on {other:?}")), |
| 474 | + other => return fail(format!("ref.set on {other:?}")), |
| 288 | 475 | }, |
| 289 | | − } |
| 476 | + }; |
| 477 | + m.control = Control::Value(v); |
| 478 | + Ok(()) |
| 290 | 479 | } |
| 291 | | − other => panic(format!("called a non-function value {other:?}")), |
| 480 | + other => fail(format!("called a non-function value {other:?}")), |
| 292 | 481 | } |
| 293 | 482 | } |
| 294 | 483 | |
| 484 | + /// `resume(value)`: push the captured frames back (a copy for `multi |
| 485 | + /// ctl`) and continue them with `value`. |
| 486 | + fn resume(&self, m: &mut Machine, cell: &Rc<ResumeCell>, value: Val) -> Result<(), Unwind> { |
| 487 | + let h = &cell.handler; |
| 488 | + // The checks, and their order, of the native runtime. |
| 489 | + if h.cancelled.get() { |
| 490 | + return fail("`resume` called after its handler finished"); |
| 491 | + } |
| 492 | + if h.multi && h.in_use.get() { |
| 493 | + return fail("`resume` called while its handler's body is running"); |
| 494 | + } |
| 495 | + let frames = if cell.multi { |
| 496 | + if cell.holds_fiber { |
| 497 | + return fail( |
| 498 | + "a `multi ctl` continuation holding a `ctl` handler cannot be resumed", |
| 499 | + ); |
| 500 | + } |
| 501 | + cell.frames.borrow().clone() |
| 502 | + } else { |
| 503 | + cell.frames.borrow_mut().take() |
| 504 | + }; |
| 505 | + let Some(frames) = frames else { |
| 506 | + return fail("`resume` called twice (continuations are one-shot)"); |
| 507 | + }; |
| 508 | + cell.resumed.set(cell.resumed.get() + 1); |
| 509 | + h.in_use.set(true); |
| 510 | + m.stack.extend(frames); |
| 511 | + m.control = Control::Value(value); |
| 512 | + Ok(()) |
| 513 | + } |
| 514 | + |
| 295 | 515 | fn atom(&self, env: &[Val], a: &Atom) -> Val { |
| 296 | 516 | match a { |
| 297 | 517 | Atom::Var(v) => env[*v as usize].clone(), |
| @@ -306,65 +526,51 @@ impl Interp { |
| 306 | 526 | atoms.iter().map(|a| self.atom(env, a)).collect() |
| 307 | 527 | } |
| 308 | 528 | |
| 309 | | − fn eval(&self, env: &mut Vec<Val>, mut e: &Expr) -> R<Flow> { |
| 529 | + /// Evaluate `e` in the current activation, up to its next call, value |
| 530 | + /// or request. |
| 531 | + fn eval(&self, m: &mut Machine, mut e: &Expr) -> Result<Option<OpRequest>, Unwind> { |
| 310 | 532 | loop { |
| 311 | 533 | match e { |
| 312 | 534 | Expr::Let(v, value, rest, _) => { |
| 313 | | − // `let v = call; return v` is a tail call, and in |
| 314 | | − // `let v = { e }; return v` the block `e` is in tail |
| 315 | | − // position (so calls in `if`/`match` branches are too). |
| 316 | | − if let Expr::Return(Atom::Var(r)) = &**rest |
| 317 | | − && r == v |
| 318 | | − { |
| 319 | | − match &**value { |
| 320 | | − Value::Block(inner) => { |
| 321 | | − e = inner; |
| 322 | | − continue; |
| 323 | | − } |
| 324 | | − Value::CallFn(f, args) => { |
| 325 | | − return Ok(Flow::Tail(*f, self.atoms(env, args))); |
| 326 | | − } |
| 327 | | − Value::Call(c, args) => { |
| 328 | | − if let Val::Closure { f, captures } = self.atom(env, c) { |
| 329 | | − let args = captures |
| 330 | | − .iter() |
| 331 | | − .cloned() |
| 332 | | − .chain(self.atoms(env, args)) |
| 333 | | − .collect(); |
| 334 | | − return Ok(Flow::Tail(f, args)); |
| 335 | | − } |
| 336 | | − } |
| 337 | | − _ => {} |
| 338 | | − } |
| 535 | + // In tail position: no frame for the rest. A block in |
| 536 | + // tail position is evaluated in place; a call replaces |
| 537 | + // the activation, unless it is inside a block whose |
| 538 | + // value this activation still needs. |
| 539 | + let tail = returns(rest, *v); |
| 540 | + if tail && let Value::Block(inner) = &**value { |
| 541 | + e = inner; |
| 542 | + continue; |
| 339 | 543 | } |
| 340 | | − let result = self.value(env, value)?; |
| 341 | | − env[*v as usize] = result; |
| 342 | | − e = rest; |
| 544 | + let tail = tail && !matches!(m.stack.last(), Some(Frame::Bind { .. })); |
| 545 | + return self.let_value(m, *v, value, rest, tail); |
| 546 | + } |
| 547 | + Expr::Return(a) => { |
| 548 | + m.control = Control::Value(self.atom(&m.env, a)); |
| 549 | + return Ok(None); |
| 343 | 550 | } |
| 344 | | − Expr::Return(a) => return Ok(Flow::Done(self.atom(env, a))), |
| 345 | | − Expr::Panic(msg) => return panic(msg.clone()), |
| 551 | + Expr::Panic(msg) => return fail(msg.clone()), |
| 346 | 552 | Expr::Dup(_, rest) | Expr::Drop(_, rest) => e = rest, |
| 347 | 553 | Expr::Release { token, rest, .. } => { |
| 348 | 554 | if let Some(t) = token { |
| 349 | | − env[*t as usize] = Val::Unit; |
| 555 | + m.env[*t as usize] = Val::Unit; |
| 350 | 556 | } |
| 351 | 557 | e = rest; |
| 352 | 558 | } |
| 353 | 559 | Expr::Switch { on, cases, default } => { |
| 354 | | − let tag = match self.atom(env, on) { |
| 560 | + let tag = match self.atom(&m.env, on) { |
| 355 | 561 | Val::Data { tag, .. } => tag, |
| 356 | | − other => return panic(format!("switch on a non-data value {other:?}")), |
| 562 | + other => return fail(format!("switch on a non-data value {other:?}")), |
| 357 | 563 | }; |
| 358 | 564 | e = match cases.iter().find(|(t, _)| *t == tag) { |
| 359 | 565 | Some((_, body)) => body, |
| 360 | 566 | None => match default { |
| 361 | 567 | Some(d) => d, |
| 362 | | − None => return panic(format!("no case for tag {tag}")), |
| 568 | + None => return fail(format!("no case for tag {tag}")), |
| 363 | 569 | }, |
| 364 | 570 | }; |
| 365 | 571 | } |
| 366 | 572 | Expr::SwitchLit { on, cases, default } => { |
| 367 | | − let v = self.atom(env, on); |
| 573 | + let v = self.atom(&m.env, on); |
| 368 | 574 | let hit = cases.iter().find(|(lit, _)| match (lit, &v) { |
| 369 | 575 | (Lit::Int(a), Val::Int(b)) => a == b, |
| 370 | 576 | (Lit::Float(a), Val::Float(b)) => a == b, |
| @@ -377,27 +583,52 @@ impl Interp { |
| 377 | 583 | } |
| 378 | 584 | } |
| 379 | 585 | |
| 380 | | − fn finish(&self, flow: Flow) -> R<Val> { |
| 381 | | − match flow { |
| 382 | | − Flow::Done(v) => Ok(v), |
| 383 | | − Flow::Tail(f, args) => self.call_fn(f, args), |
| 586 | + /// Push the frame receiving a call's value: the rest of this function |
| 587 | + /// (none in tail position). |
| 588 | + fn push_return(&self, m: &mut Machine, var: VarId, rest: &Expr, tail: bool) { |
| 589 | + if !tail { |
| 590 | + let env = std::mem::take(&mut m.env); |
| 591 | + m.stack.push(Frame::Return { |
| 592 | + env, |
| 593 | + var, |
| 594 | + rest: Code::new(rest), |
| 595 | + }); |
| 384 | 596 | } |
| 385 | 597 | } |
| 386 | 598 | |
| 387 | | − fn value(&self, env: &mut Vec<Val>, value: &Value) -> R<Val> { |
| 388 | | − Ok(match value { |
| 599 | + /// `let v = value; rest`. |
| 600 | + fn let_value( |
| 601 | + &self, |
| 602 | + m: &mut Machine, |
| 603 | + v: VarId, |
| 604 | + value: &Value, |
| 605 | + rest: &Expr, |
| 606 | + tail: bool, |
| 607 | + ) -> Result<Option<OpRequest>, Unwind> { |
| 608 | + let env = &m.env; |
| 609 | + let result = match value { |
| 389 | 610 | Value::Atom(a) => self.atom(env, a), |
| 390 | 611 | Value::Call(c, args) => { |
| 391 | 612 | let callee = self.atom(env, c); |
| 392 | | − return self.call_val(&callee, self.atoms(env, args)); |
| 613 | + let args = self.atoms(env, args); |
| 614 | + self.push_return(m, v, rest, tail); |
| 615 | + self.apply(m, &callee, args)?; |
| 616 | + return Ok(None); |
| 617 | + } |
| 618 | + Value::CallFn(f, args) => { |
| 619 | + let args = self.atoms(env, args); |
| 620 | + self.push_return(m, v, rest, tail); |
| 621 | + m.control = Control::Enter(*f, args); |
| 622 | + return Ok(None); |
| 393 | 623 | } |
| 394 | | − Value::CallFn(f, args) => return self.call_fn(*f, self.atoms(env, args)), |
| 395 | | − Value::CallExtern(sym, args) => return self.call_extern(sym, self.atoms(env, args)), |
| 624 | + Value::CallExtern(sym, args) => self |
| 625 | + .call_extern(sym, self.atoms(env, args)) |
| 626 | + .map_err(Unwind::Error)?, |
| 396 | 627 | Value::Prim(p, args) => { |
| 397 | 628 | let args = self.atoms(env, args); |
| 398 | 629 | let tag = |v: &Val| match v { |
| 399 | 630 | Val::Data { tag, .. } => Ok(*tag), |
| 400 | | − other => panic(format!("expected a data value, got {other:?}")), |
| 631 | + other => fail(format!("expected a data value, got {other:?}")), |
| 401 | 632 | }; |
| 402 | 633 | match p { |
| 403 | 634 | Prim::Not => bool_val(tag(&args[0])? == 0), |
| @@ -414,14 +645,15 @@ impl Interp { |
| 414 | 645 | Value::Field(a, i) => match self.atom(env, a) { |
| 415 | 646 | Val::Data { fields, .. } | Val::Tuple(fields) => match fields.get(*i as usize) { |
| 416 | 647 | Some(v) => v.clone(), |
| 417 | | − None => return panic(format!("no field {i}")), |
| 648 | + None => return fail(format!("no field {i}")), |
| 418 | 649 | }, |
| 419 | | − other => return panic(format!("field {i} of a non-data value {other:?}")), |
| 650 | + other => return fail(format!("field {i} of a non-data value {other:?}")), |
| 420 | 651 | }, |
| 421 | 652 | Value::Closure(f, caps) => Val::Closure { |
| 422 | 653 | f: *f, |
| 423 | 654 | captures: self.atoms(env, caps).into(), |
| 424 | 655 | }, |
| 656 | + Value::Reuse { value, .. } => return self.let_value(m, v, value, rest, tail), |
| 425 | 657 | Value::Perform { |
| 426 | 658 | cap, |
| 427 | 659 | effect, |
| @@ -429,9 +661,10 @@ impl Interp { |
| 429 | 661 | args, |
| 430 | 662 | } => { |
| 431 | 663 | let Val::Cap(cap) = self.atom(env, cap) else { |
| 432 | | − return panic("an operation's capability is not a capability"); |
| 664 | + return fail("an operation's capability is not a capability"); |
| 433 | 665 | }; |
| 434 | | − return self.perform(cap, *effect, *op, self.atoms(env, args)); |
| 666 | + let args = self.atoms(env, args); |
| 667 | + return self.perform(m, v, rest, cap, *effect, *op, args); |
| 435 | 668 | } |
| 436 | 669 | Value::Handle { |
| 437 | 670 | effect, |
| @@ -442,64 +675,200 @@ impl Interp { |
| 442 | 675 | let body = self.atom(env, body); |
| 443 | 676 | let ret = ret.as_ref().map(|r| self.atom(env, r)); |
| 444 | 677 | let clauses = self.atoms(env, clauses); |
| 445 | | − return self.handle(*effect, body, ret, clauses); |
| 678 | + let ops = &self.program.effects[*effect as usize].ops; |
| 679 | + let has = |k: OpKind| ops.iter().any(|(_, kind)| *kind == k); |
| 680 | + let (fiber, multi) = (has(OpKind::Ctl), false); |
| 681 | + self.push_return(m, v, rest, false); |
| 682 | + self.install(m, vec![(*effect, clauses)], body, ret, fiber, multi, None)?; |
| 683 | + return Ok(None); |
| 446 | 684 | } |
| 447 | 685 | Value::Region { effects, body } => { |
| 448 | 686 | let body = self.atom(env, body); |
| 449 | | − return self.region(effects, body); |
| 687 | + self.push_return(m, v, rest, false); |
| 688 | + self.region(m, effects, body)?; |
| 689 | + return Ok(None); |
| 450 | 690 | } |
| 451 | 691 | Value::Defer { body, cleanup } => { |
| 452 | 692 | let body = self.atom(env, body); |
| 453 | 693 | let cleanup = self.atom(env, cleanup); |
| 454 | | − let result = self.call_val(&body, Vec::new()); |
| 455 | | − // An error from the cleanup replaces the body's outcome, as |
| 456 | | − // a new unwinding replaces one in progress natively. |
| 457 | | − self.call_val(&cleanup, Vec::new())?; |
| 458 | | − return result; |
| 694 | + self.push_return(m, v, rest, false); |
| 695 | + m.stack.push(Frame::Defer(cleanup)); |
| 696 | + self.apply(m, &body, Vec::new())?; |
| 697 | + return Ok(None); |
| 459 | 698 | } |
| 460 | | − Value::Block(e) => { |
| 461 | | − let flow = self.eval(env, e)?; |
| 462 | | − return self.finish(flow); |
| 699 | + Value::Block(inner) => { |
| 700 | + // Not in tail position (see `eval`). |
| 701 | + m.stack.push(Frame::Bind { |
| 702 | + var: v, |
| 703 | + rest: Code::new(rest), |
| 704 | + }); |
| 705 | + m.control = Control::Eval(Code::new(inner)); |
| 706 | + return Ok(None); |
| 463 | 707 | } |
| 464 | | − Value::Reuse { value, .. } => return self.value(env, value), |
| 465 | | − }) |
| 708 | + }; |
| 709 | + m.env[v as usize] = result; |
| 710 | + m.control = Control::Eval(Code::new(rest)); |
| 711 | + Ok(None) |
| 466 | 712 | } |
| 467 | 713 | |
| 468 | | − // ---- effects ----------------------------------------------------------- |
| 714 | + /// The value `v` reaches `frame`. |
| 715 | + fn give(&self, m: &mut Machine, frame: Frame, v: Val) -> Result<Option<OpRequest>, Unwind> { |
| 716 | + match frame { |
| 717 | + Frame::Bind { var, rest } => { |
| 718 | + m.env[var as usize] = v; |
| 719 | + m.control = Control::Eval(rest); |
| 720 | + } |
| 721 | + Frame::Return { env, var, rest } => { |
| 722 | + m.env = env; |
| 723 | + m.env[var as usize] = v; |
| 724 | + m.control = Control::Eval(rest); |
| 725 | + } |
| 726 | + Frame::Handler(h) => { |
| 727 | + h.in_use.set(false); |
| 728 | + match &h.ret { |
| 729 | + Some(r) => self.apply(m, r, vec![v])?, |
| 730 | + None => m.control = Control::Value(v), |
| 731 | + } |
| 732 | + } |
| 733 | + Frame::Finish(h) => self.finish(m, h, Ok(v)), |
| 734 | + Frame::Region(guard) => { |
| 735 | + drop(guard); |
| 736 | + m.control = Control::Value(v); |
| 737 | + } |
| 738 | + Frame::Defer(cleanup) => { |
| 739 | + m.stack.push(Frame::Then(Ok(v))); |
| 740 | + self.apply(m, &cleanup, Vec::new())?; |
| 741 | + } |
| 742 | + Frame::Then(outcome) => { |
| 743 | + m.control = match outcome { |
| 744 | + Ok(v) => Control::Value(v), |
| 745 | + Err(u) => Control::Unwind(u), |
| 746 | + } |
| 747 | + } |
| 748 | + // The cancelled code returned instead of unwinding (it cannot): |
| 749 | + // the cancellation is over. |
| 750 | + Frame::CancelStop => m.control = Control::Value(Val::Unit), |
| 751 | + } |
| 752 | + Ok(None) |
| 753 | + } |
| 469 | 754 | |
| 470 | | − pub(crate) fn op_name(&self, effect: EffectId, op: u32) -> String { |
| 471 | | − if effect == crate::sched::PREEMPT { |
| 472 | | − return "<preempt>".into(); |
| 755 | + /// Unwinding `u` reaches `frame`. |
| 756 | + fn unwind( |
| 757 | + &self, |
| 758 | + m: &mut Machine, |
| 759 | + frame: Frame, |
| 760 | + u: Unwind, |
| 761 | + ) -> Result<Option<OpRequest>, Unwind> { |
| 762 | + match frame { |
| 763 | + Frame::Bind { .. } | Frame::Return { .. } => m.control = Control::Unwind(u), |
| 764 | + Frame::Handler(h) => { |
| 765 | + h.in_use.set(false); |
| 766 | + match u { |
| 767 | + Unwind::Final { |
| 768 | + target, |
| 769 | + clause, |
| 770 | + args, |
| 771 | + } if target == h.id => self.apply(m, &clause, args)?, |
| 772 | + u => m.control = Control::Unwind(u), |
| 773 | + } |
| 774 | + } |
| 775 | + Frame::Finish(h) => self.finish(m, h, Err(u)), |
| 776 | + Frame::Region(guard) => { |
| 777 | + drop(guard); |
| 778 | + m.control = Control::Unwind(u); |
| 779 | + } |
| 780 | + Frame::Defer(cleanup) => { |
| 781 | + m.stack.push(Frame::Then(Err(u))); |
| 782 | + self.apply(m, &cleanup, Vec::new())?; |
| 783 | + } |
| 784 | + // A new unwinding (a cleanup panicked) replaces the old outcome. |
| 785 | + Frame::Then(_) => m.control = Control::Unwind(u), |
| 786 | + Frame::CancelStop => { |
| 787 | + m.control = match u { |
| 788 | + Unwind::Error(RtError::Cancelled) => Control::Value(Val::Unit), |
| 789 | + u => Control::Unwind(u), |
| 790 | + } |
| 791 | + } |
| 473 | 792 | } |
| 474 | | − let e = &self.program.effects[effect as usize]; |
| 475 | | − format!("{}.{}", e.name, e.ops[op as usize].0) |
| 793 | + Ok(None) |
| 476 | 794 | } |
| 477 | 795 | |
| 478 | | − /// Suspend the current fiber with a request; its handler's answer is |
| 479 | | − /// the operation's result. |
| 480 | | − pub(crate) fn perform(&self, cap: u64, effect: EffectId, op: u32, args: Vec<Val>) -> R<Val> { |
| 481 | | − let yielder = self.state.current.get(); |
| 482 | | − if yielder.is_null() { |
| 483 | | − return Err(RtError::Unhandled(self.op_name(effect, op))); |
| 796 | + /// The handler `h` is done, with `outcome`: cancel the continuations it |
| 797 | + /// left that were never resumed (their cleanups run, innermost first), |
| 798 | + /// in the order they were captured, and release the others (copies of |
| 799 | + /// `multi ctl` continuations ran their cleanups already). Then go on |
| 800 | + /// with `outcome`, unless a cancellation unwound otherwise. |
| 801 | + fn finish(&self, m: &mut Machine, h: Rc<HandlerInfo>, outcome: Result<Val, Unwind>) { |
| 802 | + loop { |
| 803 | + let next = h |
| 804 | + .pending |
| 805 | + .borrow() |
| 806 | + .iter() |
| 807 | + .find(|c| c.frames.borrow().is_some()) |
| 808 | + .cloned(); |
| 809 | + let Some(cell) = next else { |
| 810 | + h.pending.borrow_mut().clear(); |
| 811 | + if h.multi { |
| 812 | + h.cancelled.set(true); |
| 813 | + } |
| 814 | + m.control = match outcome { |
| 815 | + Ok(v) => Control::Value(v), |
| 816 | + Err(u) => Control::Unwind(u), |
| 817 | + }; |
| 818 | + return; |
| 819 | + }; |
| 820 | + let frames = cell.frames.borrow_mut().take().expect("found"); |
| 821 | + if cell.resumed.get() > 0 { |
| 822 | + drop(frames); |
| 823 | + continue; |
| 824 | + } |
| 825 | + h.cancelled.set(true); |
| 826 | + h.in_use.set(true); |
| 827 | + m.stack.push(Frame::Finish(h.clone())); |
| 828 | + m.stack.push(Frame::Then(outcome)); |
| 829 | + m.stack.push(Frame::CancelStop); |
| 830 | + m.stack.extend(frames); |
| 831 | + m.control = Control::Unwind(Unwind::Error(RtError::Cancelled)); |
| 832 | + return; |
| 484 | 833 | } |
| 485 | | − // SAFETY: `current` is the yielder of the fiber executing this code; |
| 486 | | − // it lives as long as the fiber, which is running. |
| 487 | | − let answer = unsafe { |
| 488 | | − (*yielder).suspend(OpRequest { |
| 489 | | − cap, |
| 490 | | − effect, |
| 491 | | − op, |
| 492 | | − args, |
| 493 | | − }) |
| 494 | | − }; |
| 495 | | − self.state.current.set(yielder); |
| 496 | | − answer |
| 497 | 834 | } |
| 498 | 835 | |
| 499 | | − /// Run `body` handling `st` with fresh reference storage; afterwards |
| 500 | | − /// (also after an error) clear every reference created in the region, |
| 501 | | − /// which breaks any cycle through them (ADR 0002, Revision 1). |
| 502 | | − fn region(&self, effects: &[EffectId], body: Val) -> R<Val> { |
| 836 | + /// Install a handler for `handled` and call `body` with its new |
| 837 | + /// capability (above `extra`, a region's guard). |
| 838 | + #[allow(clippy::too_many_arguments)] |
| 839 | + fn install( |
| 840 | + &self, |
| 841 | + m: &mut Machine, |
| 842 | + handled: Vec<(EffectId, Vec<Val>)>, |
| 843 | + body: Val, |
| 844 | + ret: Option<Val>, |
| 845 | + fiber: bool, |
| 846 | + multi: bool, |
| 847 | + extra: Option<Frame>, |
| 848 | + ) -> Result<(), Unwind> { |
| 849 | + let id = self.state.caps.get() + 1; |
| 850 | + self.state.caps.set(id); |
| 851 | + let h = Rc::new(HandlerInfo { |
| 852 | + id, |
| 853 | + handled, |
| 854 | + ret, |
| 855 | + fiber, |
| 856 | + multi, |
| 857 | + in_use: Cell::new(true), |
| 858 | + pending: RefCell::new(Vec::new()), |
| 859 | + cancelled: Cell::new(false), |
| 860 | + }); |
| 861 | + m.stack.push(Frame::Finish(h.clone())); |
| 862 | + m.stack.extend(extra); |
| 863 | + m.stack.push(Frame::Handler(h)); |
| 864 | + self.apply(m, &body, vec![Val::Cap(id)]) |
| 865 | + } |
| 866 | + |
| 867 | + /// `region { body }`: handle `st` with fresh reference storage; when |
| 868 | + /// the region is left (also by unwinding), clear every reference |
| 869 | + /// created in it, which breaks any cycle through them (ADR 0002, |
| 870 | + /// Revision 1). |
| 871 | + fn region(&self, m: &mut Machine, effects: &[EffectId], body: Val) -> Result<(), Unwind> { |
| 503 | 872 | let refs = Rc::new(RefCell::new(Vec::new())); |
| 504 | 873 | let handled = effects |
| 505 | 874 | .iter() |
| @@ -522,113 +891,100 @@ impl Interp { |
| 522 | 891 | (*e, clauses) |
| 523 | 892 | }) |
| 524 | 893 | .collect(); |
| 525 | | − let result = self.install(handled, body, None); |
| 526 | | − for cell in refs.borrow().iter() { |
| 527 | | − *cell.borrow_mut() = Val::Unit; |
| 528 | | − } |
| 529 | | − result |
| 530 | | − } |
| 531 | | − |
| 532 | | − fn handle(&self, effect: EffectId, body: Val, ret: Option<Val>, clauses: Vec<Val>) -> R<Val> { |
| 533 | | − self.install(vec![(effect, clauses)], body, ret) |
| 894 | + let guard = Frame::Region(Rc::new(RegionGuard { refs })); |
| 895 | + self.install(m, handled, body, None, false, false, Some(guard)) |
| 534 | 896 | } |
| 535 | 897 | |
| 536 | | − /// Run `body` on a new fiber under a frame handling `handled`; the body |
| 537 | | − /// receives the frame's capability. When the handler finishes, a body |
| 538 | | − /// still waiting for a `resume` is cancelled (as natively), so its |
| 539 | | − /// cleanups run and a later `resume` panics. |
| 540 | | − fn install(&self, handled: Vec<(EffectId, Vec<Val>)>, body: Val, ret: Option<Val>) -> R<Val> { |
| 541 | | − let interp = self.clone(); |
| 542 | | − let id = self.state.caps.get() + 1; |
| 543 | | − self.state.caps.set(id); |
| 544 | | − let stack = DefaultStack::new(FIBER_STACK) |
| 545 | | − .map_err(|e| RtError::Panic(format!("cannot allocate a fiber: {e}")))?; |
| 546 | | − let fiber = Fiber::with_stack(stack, move |yielder: &FiberYielder, input: R<Val>| { |
| 547 | | − interp.state.current.set(yielder); |
| 548 | | − input?; |
| 549 | | − interp.call_val(&body, vec![Val::Cap(id)]) |
| 550 | | − }); |
| 551 | | − let frame = Rc::new(HandlerFrame { |
| 552 | | − id, |
| 553 | | − fiber: RefCell::new(Some(fiber)), |
| 554 | | − handled, |
| 555 | | − ret, |
| 556 | | − cancelled: Cell::new(false), |
| 557 | | − }); |
| 558 | | − let result = self.drive(&frame, Ok(Val::Unit)); |
| 559 | | − if frame.fiber.borrow().is_some() { |
| 560 | | − frame.cancelled.set(true); |
| 561 | | − // A panic while cancelling replaces the handler's outcome. |
| 562 | | − self.unwind_body(&frame)?; |
| 563 | | − } |
| 564 | | − result |
| 565 | | − } |
| 898 | + // ---- effects ----------------------------------------------------------- |
| 566 | 899 | |
| 567 | | − /// Unwind the frame's suspended body: resume it with `Cancelled` until |
| 568 | | − /// it finishes. Returns the error that replaced the cancellation, if |
| 569 | | − /// one did (a cleanup panicked, or the actor was killed meanwhile). |
| 570 | | − fn unwind_body(&self, frame: &Rc<HandlerFrame>) -> R<()> { |
| 571 | | − match self.drive(frame, Err(RtError::Cancelled)) { |
| 572 | | − Err(RtError::Cancelled) | Ok(_) => Ok(()), |
| 573 | | − Err(e) => Err(e), |
| 900 | + pub(crate) fn op_name(&self, effect: EffectId, op: u32) -> String { |
| 901 | + if effect == crate::sched::PREEMPT { |
| 902 | + return "<preempt>".into(); |
| 574 | 903 | } |
| 904 | + let e = &self.program.effects[effect as usize]; |
| 905 | + format!("{}.{}", e.name, e.ops[op as usize].0) |
| 575 | 906 | } |
| 576 | 907 | |
| 577 | | − /// Run the handler's body fiber with `input` until it finishes (then |
| 578 | | − /// apply the return clause) or performs an operation of this handler |
| 579 | | − /// whose clause produces the handler's result. |
| 580 | | − fn drive(&self, frame: &Rc<HandlerFrame>, mut input: R<Val>) -> R<Val> { |
| 581 | | − loop { |
| 582 | | − let Some(mut fiber) = frame.fiber.borrow_mut().take() else { |
| 583 | | − return panic("`resume` called after its handler finished"); |
| 584 | | − }; |
| 585 | | − let saved = self.state.current.get(); |
| 586 | | − let step = fiber.resume(input); |
| 587 | | − self.state.current.set(saved); |
| 588 | | − let request = match step { |
| 589 | | − CoroutineResult::Return(result) => { |
| 590 | | − let value = result?; |
| 591 | | − return match &frame.ret { |
| 592 | | − Some(r) => self.call_val(r, vec![value]), |
| 593 | | − None => Ok(value), |
| 594 | | − }; |
| 595 | | − } |
| 596 | | − CoroutineResult::Yield(request) => request, |
| 597 | | − }; |
| 598 | | − *frame.fiber.borrow_mut() = Some(fiber); |
| 599 | | − let ours = request.cap == frame.id; |
| 600 | | − let Some((_, clauses)) = frame |
| 601 | | − .handled |
| 602 | | − .iter() |
| 603 | | − .find(|(e, _)| ours && *e == request.effect) |
| 604 | | − else { |
| 605 | | − // Not ours: perform it in the context around this handler. |
| 606 | | − // An error (the code around is unwinding) is delivered to |
| 607 | | − // the body first, so that it unwinds too. |
| 608 | | − input = self.perform(request.cap, request.effect, request.op, request.args); |
| 609 | | − continue; |
| 610 | | − }; |
| 611 | | − let clause = clauses[request.op as usize].clone(); |
| 612 | | − match self.program.effects[request.effect as usize].ops[request.op as usize].1 { |
| 613 | | − // Natively the clause runs on top of the body's stack, so its |
| 614 | | − // panic unwinds the body: deliver it there. |
| 615 | | − OpKind::Fn => input = self.call_val(&clause, request.args), |
| 616 | | − OpKind::Ctl => { |
| 617 | | − let resume = Val::Resume(Rc::new(ResumeCell { |
| 618 | | − frame: frame.clone(), |
| 619 | | − used: Cell::new(false), |
| 620 | | − })); |
| 621 | | − let mut args = request.args; |
| 622 | | − args.push(resume); |
| 623 | | − return self.call_val(&clause, args); |
| 624 | | − } |
| 625 | | − OpKind::FinalCtl => { |
| 626 | | − // Unwind the body (its cleanups run), then run the clause. |
| 627 | | − self.unwind_body(frame)?; |
| 628 | | − return self.call_val(&clause, request.args); |
| 629 | | − } |
| 908 | + /// `let v = perform op(args) on cap; rest`. |
| 909 | + #[allow(clippy::too_many_arguments)] |
| 910 | + fn perform( |
| 911 | + &self, |
| 912 | + m: &mut Machine, |
| 913 | + v: VarId, |
| 914 | + rest: &Expr, |
| 915 | + cap: u64, |
| 916 | + effect: EffectId, |
| 917 | + op: u32, |
| 918 | + args: Vec<Val>, |
| 919 | + ) -> Result<Option<OpRequest>, Unwind> { |
| 920 | + let found = m |
| 921 | + .stack |
| 922 | + .iter() |
| 923 | + .rposition(|f| matches!(f, Frame::Handler(h) if h.id == cap)); |
| 924 | + let Some(index) = found else { |
| 925 | + if cap != ROOT { |
| 926 | + return fail(format!( |
| 927 | + "`{}` used a handler that has already finished", |
| 928 | + self.op_name(effect, op) |
| 929 | + )); |
| 930 | + } |
| 931 | + // The runtime's: ask the scheduler; its answer is `v`. |
| 932 | + m.stack.push(Frame::Bind { |
| 933 | + var: v, |
| 934 | + rest: Code::new(rest), |
| 935 | + }); |
| 936 | + return Ok(Some(OpRequest { |
| 937 | + cap, |
| 938 | + effect, |
| 939 | + op, |
| 940 | + args, |
| 941 | + })); |
| 942 | + }; |
| 943 | + let Frame::Handler(h) = &m.stack[index] else { |
| 944 | + unreachable!("found a handler") |
| 945 | + }; |
| 946 | + let h = h.clone(); |
| 947 | + let Some((_, clauses)) = h.handled.iter().find(|(e, _)| *e == effect) else { |
| 948 | + return fail(format!( |
| 949 | + "`{}` reached a handler of another effect", |
| 950 | + self.op_name(effect, op) |
| 951 | + )); |
| 952 | + }; |
| 953 | + let clause = clauses[op as usize].clone(); |
| 954 | + match self.program.effects[effect as usize].ops[op as usize].1 { |
| 955 | + // The clause runs on top, as natively. |
| 956 | + OpKind::Fn => { |
| 957 | + self.push_return(m, v, rest, false); |
| 958 | + self.apply(m, &clause, args)?; |
| 959 | + } |
| 960 | + OpKind::FinalCtl => { |
| 961 | + m.control = Control::Unwind(Unwind::Final { |
| 962 | + target: cap, |
| 963 | + clause, |
| 964 | + args, |
| 965 | + }); |
| 966 | + } |
| 967 | + OpKind::Ctl => { |
| 968 | + self.push_return(m, v, rest, false); |
| 969 | + let frames = m.stack.split_off(index); |
| 970 | + let holds_fiber = frames[1..] |
| 971 | + .iter() |
| 972 | + .any(|f| matches!(f, Frame::Finish(inner) if inner.fiber)); |
| 973 | + let cell = Rc::new(ResumeCell { |
| 974 | + handler: h.clone(), |
| 975 | + frames: RefCell::new(Some(frames)), |
| 976 | + multi: false, |
| 977 | + resumed: Cell::new(0), |
| 978 | + holds_fiber, |
| 979 | + }); |
| 980 | + h.in_use.set(false); |
| 981 | + h.pending.borrow_mut().push(cell.clone()); |
| 982 | + let mut args = args; |
| 983 | + args.push(Val::Resume(cell)); |
| 984 | + self.apply(m, &clause, args)?; |
| 630 | 985 | } |
| 631 | 986 | } |
| 987 | + Ok(None) |
| 632 | 988 | } |
| 633 | 989 | |
| 634 | 990 | // ---- built-ins ----------------------------------------------------------- |