| @@ -50,6 +50,18 @@ pub enum Val { |
| 50 | 50 | Resume(Rc<ResumeCell>), |
| 51 | 51 | Ref(Rc<RefCell<Val>>), |
| 52 | 52 | Pid(u64), |
| 53 | + /// A built-in clause of a region's `st` handler. |
| 54 | + RegionOp { |
| 55 | + refs: Rc<RefCell<Vec<Rc<RefCell<Val>>>>>, |
| 56 | + op: RefOp, |
| 57 | + }, |
| 58 | +} |
| 59 | + |
| 60 | +#[derive(Clone, Copy, Debug)] |
| 61 | +pub enum RefOp { |
| 62 | + New, |
| 63 | + Get, |
| 64 | + Set, |
| 53 | 65 | } |
| 54 | 66 | |
| 55 | 67 | impl fmt::Debug for Val { |
| @@ -66,6 +78,7 @@ impl fmt::Debug for Val { |
| 66 | 78 | Val::Resume(_) => f.write_str("<resume>"), |
| 67 | 79 | Val::Ref(r) => write!(f, "<ref {:?}>", r.borrow()), |
| 68 | 80 | Val::Pid(p) => write!(f, "<pid {p}>"), |
| 81 | + Val::RegionOp { op, .. } => write!(f, "<region {op:?}>"), |
| 69 | 82 | } |
| 70 | 83 | } |
| 71 | 84 | } |
| @@ -103,8 +116,8 @@ pub(crate) type Fiber = Coroutine<Val, OpRequest, R<Val>, DefaultStack>; |
| 103 | 116 | /// An installed handler: the suspended body fiber and the clauses. |
| 104 | 117 | pub struct HandlerFrame { |
| 105 | 118 | fiber: RefCell<Option<Fiber>>, |
| 106 | | − effect: EffectId, |
| 107 | | − clauses: Vec<Val>, |
| 119 | + /// The effects handled here, each with one clause per operation. |
| 120 | + handled: Vec<(EffectId, Vec<Val>)>, |
| 108 | 121 | ret: Option<Val>, |
| 109 | 122 | } |
| 110 | 123 | |
| @@ -205,6 +218,27 @@ impl Interp { |
| 205 | 218 | let value = args.into_iter().next().unwrap_or(Val::Unit); |
| 206 | 219 | self.drive(&cell.frame, value) |
| 207 | 220 | } |
| 221 | + Val::RegionOp { refs, op } => { |
| 222 | + let mut args = args.into_iter(); |
| 223 | + match op { |
| 224 | + RefOp::New => { |
| 225 | + let cell = Rc::new(RefCell::new(args.next().unwrap_or(Val::Unit))); |
| 226 | + refs.borrow_mut().push(cell.clone()); |
| 227 | + Ok(Val::Ref(cell)) |
| 228 | + } |
| 229 | + RefOp::Get => match args.next() { |
| 230 | + Some(Val::Ref(r)) => Ok(r.borrow().clone()), |
| 231 | + other => panic(format!("ref.get on {other:?}")), |
| 232 | + }, |
| 233 | + RefOp::Set => match (args.next(), args.next()) { |
| 234 | + (Some(Val::Ref(r)), Some(v)) => { |
| 235 | + *r.borrow_mut() = v; |
| 236 | + Ok(Val::Unit) |
| 237 | + } |
| 238 | + other => panic(format!("ref.set on {other:?}")), |
| 239 | + }, |
| 240 | + } |
| 241 | + } |
| 208 | 242 | other => panic(format!("called a non-function value {other:?}")), |
| 209 | 243 | } |
| 210 | 244 | } |
| @@ -346,6 +380,10 @@ impl Interp { |
| 346 | 380 | let clauses = self.atoms(env, clauses); |
| 347 | 381 | return self.handle(*effect, body, ret, clauses); |
| 348 | 382 | } |
| 383 | + Value::Region { effects, body } => { |
| 384 | + let body = self.atom(env, body); |
| 385 | + return self.region(effects, body); |
| 386 | + } |
| 349 | 387 | Value::Block(e) => { |
| 350 | 388 | let flow = self.eval(env, e)?; |
| 351 | 389 | return self.finish(flow); |
| @@ -377,7 +415,45 @@ impl Interp { |
| 377 | 415 | Ok(answer) |
| 378 | 416 | } |
| 379 | 417 | |
| 418 | + /// Run `body` handling `st` with fresh reference storage; afterwards |
| 419 | + /// (also after an error) clear every reference created in the region, |
| 420 | + /// which breaks any cycle through them (ADR 0002, Revision 1). |
| 421 | + fn region(&self, effects: &[EffectId], body: Val) -> R<Val> { |
| 422 | + let refs = Rc::new(RefCell::new(Vec::new())); |
| 423 | + let handled = effects |
| 424 | + .iter() |
| 425 | + .map(|e| { |
| 426 | + let clauses = self.program.effects[*e as usize] |
| 427 | + .ops |
| 428 | + .iter() |
| 429 | + .map(|(name, _)| { |
| 430 | + let op = match name.as_str() { |
| 431 | + "new" => RefOp::New, |
| 432 | + "get" => RefOp::Get, |
| 433 | + _ => RefOp::Set, |
| 434 | + }; |
| 435 | + Val::RegionOp { |
| 436 | + refs: refs.clone(), |
| 437 | + op, |
| 438 | + } |
| 439 | + }) |
| 440 | + .collect(); |
| 441 | + (*e, clauses) |
| 442 | + }) |
| 443 | + .collect(); |
| 444 | + let result = self.install(handled, body, None); |
| 445 | + for cell in refs.borrow().iter() { |
| 446 | + *cell.borrow_mut() = Val::Unit; |
| 447 | + } |
| 448 | + result |
| 449 | + } |
| 450 | + |
| 380 | 451 | fn handle(&self, effect: EffectId, body: Val, ret: Option<Val>, clauses: Vec<Val>) -> R<Val> { |
| 452 | + self.install(vec![(effect, clauses)], body, ret) |
| 453 | + } |
| 454 | + |
| 455 | + /// Run `body` on a new fiber under a frame handling `handled`. |
| 456 | + fn install(&self, handled: Vec<(EffectId, Vec<Val>)>, body: Val, ret: Option<Val>) -> R<Val> { |
| 381 | 457 | let interp = self.clone(); |
| 382 | 458 | let stack = DefaultStack::new(FIBER_STACK) |
| 383 | 459 | .map_err(|e| RtError::Panic(format!("cannot allocate a fiber: {e}")))?; |
| @@ -387,8 +463,7 @@ impl Interp { |
| 387 | 463 | }); |
| 388 | 464 | let frame = Rc::new(HandlerFrame { |
| 389 | 465 | fiber: RefCell::new(Some(fiber)), |
| 390 | | − effect, |
| 391 | | − clauses, |
| 466 | + handled, |
| 392 | 467 | ret, |
| 393 | 468 | }); |
| 394 | 469 | self.drive(&frame, Val::Unit) |
| @@ -416,13 +491,14 @@ impl Interp { |
| 416 | 491 | CoroutineResult::Yield(request) => request, |
| 417 | 492 | }; |
| 418 | 493 | *frame.fiber.borrow_mut() = Some(fiber); |
| 419 | | − if request.effect != frame.effect { |
| 494 | + let Some((_, clauses)) = frame.handled.iter().find(|(e, _)| *e == request.effect) |
| 495 | + else { |
| 420 | 496 | // Not ours: perform it in the context around this handler. |
| 421 | 497 | input = self.perform(request.effect, request.op, request.args)?; |
| 422 | 498 | continue; |
| 423 | | − } |
| 424 | | − let clause = frame.clauses[request.op as usize].clone(); |
| 425 | | − match self.program.effects[frame.effect as usize].ops[request.op as usize].1 { |
| 499 | + }; |
| 500 | + let clause = clauses[request.op as usize].clone(); |
| 501 | + match self.program.effects[request.effect as usize].ops[request.op as usize].1 { |
| 426 | 502 | OpKind::Fn => input = self.call_val(&clause, request.args)?, |
| 427 | 503 | OpKind::Ctl => { |
| 428 | 504 | let resume = Val::Resume(Rc::new(ResumeCell { |
| @@ -521,6 +597,22 @@ impl Interp { |
| 521 | 597 | Val::Str(format!("{}{}", string(&arg(a))?, string(&arg(b))?).into()) |
| 522 | 598 | } |
| 523 | 599 | "tl_string_length" => Val::Int(string(&arg(a))?.chars().count() as i64), |
| 600 | + "tl_string_debug" => Val::Str(format!("{:?}", &*string(&arg(a))?).into()), |
| 601 | + "tl_hash_int" => Val::Int(mix(int(&arg(a))? as u64)), |
| 602 | + "tl_hash_float" => Val::Int(mix(float(&arg(a))?.to_bits())), |
| 603 | + "tl_hash_string" => { |
| 604 | + // FNV-1a, then mixed. |
| 605 | + let h = string(&arg(a))? |
| 606 | + .bytes() |
| 607 | + .fold(0xcbf2_9ce4_8422_2325u64, |h, b| { |
| 608 | + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) |
| 609 | + }); |
| 610 | + Val::Int(mix(h)) |
| 611 | + } |
| 612 | + "tl_hash_combine" => { |
| 613 | + let (x, y) = (int(&arg(a))? as u64, int(&arg(b))? as u64); |
| 614 | + Val::Int(mix(x.wrapping_mul(31).wrapping_add(y) ^ (x >> 7))) |
| 615 | + } |
| 524 | 616 | "tl_pid_eq" => match (arg(a), arg(b)) { |
| 525 | 617 | (Val::Pid(x), Val::Pid(y)) => bool_val(x == y), |
| 526 | 618 | _ => return panic("tl_pid_eq: expected pids"), |
| @@ -553,18 +645,6 @@ impl Interp { |
| 553 | 645 | Val::Unit |
| 554 | 646 | } |
| 555 | 647 | "tl_panic" => return panic(string(&arg(a))?.to_string()), |
| 556 | | − "tl_ref_new" => Val::Ref(Rc::new(RefCell::new(arg(a)))), |
| 557 | | − "tl_ref_get" => match arg(a) { |
| 558 | | − Val::Ref(r) => r.borrow().clone(), |
| 559 | | − other => return panic(format!("{sym}: expected a Ref, got {other:?}")), |
| 560 | | − }, |
| 561 | | − "tl_ref_set" => match arg(a) { |
| 562 | | − Val::Ref(r) => { |
| 563 | | − *r.borrow_mut() = arg(b); |
| 564 | | − Val::Unit |
| 565 | | − } |
| 566 | | − other => return panic(format!("{sym}: expected a Ref, got {other:?}")), |
| 567 | | − }, |
| 568 | 648 | other => { |
| 569 | 649 | return panic(format!( |
| 570 | 650 | "unknown extern `{other}` (not available in the interpreter)" |
| @@ -574,6 +654,14 @@ impl Interp { |
| 574 | 654 | } |
| 575 | 655 | } |
| 576 | 656 | |
| 657 | +/// A 64-bit mixer (splitmix64's finalizer), reduced to a non-negative Int |
| 658 | +/// (62 bits), so hashes are valid 63-bit Ints. |
| 659 | +fn mix(mut z: u64) -> i64 { |
| 660 | + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); |
| 661 | + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); |
| 662 | + ((z ^ (z >> 31)) >> 2) as i64 |
| 663 | +} |
| 664 | + |
| 577 | 665 | pub(crate) fn bool_val(b: bool) -> Val { |
| 578 | 666 | Val::Data { |
| 579 | 667 | tag: u32::from(b), |