From d3d3303db1c8b32795577eb0a1b72a7c072a1723 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:19:29 +1000 Subject: [PATCH 1/6] feat(rust): add hardened persistent Session and zero-copy HostCtx API --- rust/crates/psychoscript/src/collector.rs | 200 +- rust/crates/psychoscript/src/host.rs | 134 +- rust/crates/psychoscript/src/host_function.rs | 23 + rust/crates/psychoscript/src/lib.rs | 2 + rust/crates/psychoscript/src/promise.rs | 8 + rust/crates/psychoscript/src/reach.rs | 12 + rust/crates/psychoscript/src/runtime.rs | 15 + rust/crates/psychoscript/src/session.rs | 1770 +++++++++++++++++ rust/crates/psychoscript/src/snapshot.rs | 61 +- rust/crates/psychoscript/src/strings.rs | 28 + rust/crates/psychoscript/src/vm.rs | 375 +++- rust/crates/psychoscript/tests/session.rs | 1509 ++++++++++++++ 12 files changed, 4080 insertions(+), 57 deletions(-) create mode 100644 rust/crates/psychoscript/src/session.rs create mode 100644 rust/crates/psychoscript/tests/session.rs diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index ca606c66..2e106c2b 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -480,6 +480,12 @@ impl Gc { std::mem::replace(&mut self.made, outer).unwrap_or_default() } + /// Whether the collector alone set `suspend_wanted` so a top-level call may take a GC step at a back-edge. + #[inline(always)] + pub(crate) fn owns_suspend(&self) -> bool { + self.owns_suspend + } + /// Someone other than the collector asks the run to stop. pub(crate) fn disown_suspend(&mut self) { self.owns_suspend = false; @@ -545,6 +551,18 @@ impl StrGc { grow_free: Vec::new(), } } + + /// Whether string slot `idx` is live and not scheduled to be swept in an active post-mark phase. + #[inline(always)] + pub(crate) fn is_live(&self, idx: usize) -> bool { + match self.color.get(idx) { + Some(&FREE) => false, + Some(&WHITE) if matches!(self.phase, Phase::Idle | Phase::Mark) => true, + Some(&WHITE) if self.phase == Phase::Sweep => idx < self.sweep.0 || idx >= self.sweep.1, + Some(&WHITE) => false, + _ => true, + } + } } impl Strings { @@ -1122,11 +1140,171 @@ impl Vm { } } + /// Whether heap object `id` is live and not scheduled to be swept in an active post-mark phase. + #[inline(always)] + pub(crate) fn is_live_obj(&self, id: Id) -> bool { + let i = id as usize; + if i >= self.heap.len() { + return false; + } + match self.heap.marks.color.get(i) { + Some(&FREE) => false, + Some(&WHITE) if matches!(self.gc.phase, Phase::Idle | Phase::Mark) => true, + Some(&WHITE) if self.gc.phase == Phase::Sweep => { + i < self.gc.obj_sweep.0 || i >= self.gc.obj_sweep.1 + } + Some(&WHITE) => false, + _ => true, + } + } + + /// Bounds- and liveness-checked read of heap object `id`. + #[inline(always)] + pub(crate) fn live_obj(&self, id: Id) -> Option<&Obj> { + self.is_live_obj(id).then(|| &self.heap[id as usize]) + } + + /// Bounds- and liveness-checked mutable read of heap object `id`, running the SATB barrier. + #[inline(always)] + pub(crate) fn live_obj_mut(&mut self, id: Id) -> Option<&mut Obj> { + if !self.is_live_obj(id) { + return None; + } + Some(&mut self.heap[id as usize]) + } + + /// Whether the incremental collector is currently in `Phase::Mark`. + #[inline(always)] + pub(crate) fn gc_is_marking(&self) -> bool { + self.gc.phase == Phase::Mark + } + + /// Write barrier for rooting a value outside the heap (e.g. `Vm::pinned`, `Vm::global_map`, + /// `Vm::globals`) or writing into an already-black host-mutated object while incremental GC is + /// in `Phase::Mark`. Because incremental marking has no atomic remark pass, a white object + /// newly stored into an already-scanned root or black object would otherwise be swept. + #[inline] + pub(crate) fn gc_shade(&mut self, val: Value) { + if self.gc.phase != Phase::Mark { + return; + } + self.gc_shade_slow(val); + } + + #[cold] + #[inline(never)] + fn gc_shade_slow(&mut self, val: Value) { + match val { + Value::Big(id) if !crate::builtins::bigint::on_heap(id) => {} + Value::Obj(id) | Value::Big(id) => { + if self.heap.marks.color.get(id as usize) == Some(&WHITE) { + self.heap.marks.color[id as usize] = GREY; + self.heap.marks.grey.push(id); + } + } + Value::Str(s) => { + let idx = s as usize; + if let Some(c) = self.atoms.gc.color.get_mut(idx) + && *c == WHITE + { + *c = BLACK; + let g = self.atoms.bufs[idx].grow as usize; + if self.atoms.gc.retired.get(g) != Some(&true) + && let Some(l) = self.atoms.gc.grow_live.get_mut(g) + { + *l = true; + } + } + } + _ => {} + } + } + + /// Shades an atom key written into a live object during an active GC cycle. + #[inline] + pub(crate) fn gc_shade_atom(&mut self, a: Atom) { + if self.gc.phase != Phase::Idle + && let Some(&sid) = self.atoms.atom_str.get(a as usize) + && sid != crate::strings::NO_ATOM + { + self.atoms.shade_atom(a); + } + } + + /// Runs a full GC cycle (finishing any in-progress cycle first, then executing one complete + /// `Idle -> Mark -> Sweep -> Idle` pass) and releases empty trailing heap chunks back to the OS. + pub(crate) fn gc_collect_full(&mut self) { + let busy = self.replay_meter.is_some() + || !self.replay.is_empty() + || self.convert_req.is_some() + || self.json_walk != 0; + if busy { + return; + } + // If a cycle was already underway, finish it first so a fresh Idle -> Mark -> Sweep -> Idle + // pass collects anything unpinned or dropped during the prior mark phase. + if self.gc.phase != Phase::Idle { + while self.gc.phase != Phase::Idle { + self.gc.debt = MAX_WORK; + self.gc_step(); + } + } + loop { + self.gc.debt = MAX_WORK; + self.gc_step(); + if self.gc.phase == Phase::Idle { + break; + } + } + self.gc.requested = false; + if self.gc.owns_suspend { + self.gc.owns_suspend = false; + self.suspend_wanted = false; + } + let old_len = self.heap.len(); + let floor = self.snapshot_base.heap.max(self.heap.base.get().len()); + let mut top = old_len; + while top > floor && self.heap.marks.color.get(top - 1) == Some(&FREE) { + top -= 1; + } + if top < old_len { + while self.heap.drop_free_tail(top) > 0 {} + let new_len = self.heap.len(); + self.heap.chunks.shrink_to_fit(); + self.heap.marks.color.shrink_to_fit(); + self.gc.free.retain(|&id| (id as usize) < new_len); + self.gc.free.shrink_to_fit(); + if let Some(m) = self.heap_meter.as_deref_mut() { + m.on_heap_truncate(old_len, new_len); + } + } + self.gc_poll(); + } + /// Whether a step is due, for the host stop. pub(crate) fn gc_pending(&self) -> bool { self.gc.requested } + /// Runs one bounded incremental GC step when the VM is not inside a non-reentrant conversion. + pub(crate) fn gc_step_once(&mut self) { + let busy = self.replay_meter.is_some() + || !self.replay.is_empty() + || self.convert_req.is_some() + || self.json_walk != 0; + if busy { + return; + } + if self.gc.phase != Phase::Idle || self.gc.requested || self.gc_used() >= self.gc.trigger { + self.gc.requested = false; + self.gc_step(); + if self.gc.owns_suspend && !self.gc.requested { + self.gc.owns_suspend = false; + self.suspend_wanted = false; + } + } + } + fn gc_step(&mut self) { #[cfg(feature = "gc-stats")] let started = crate::time::Instant::now(); @@ -1233,8 +1411,26 @@ impl Vm { match self.heap.marks.color[at] { WHITE => { self.heap.marks.color[at] = FREE; - if let Kind::BigInt(n) = &self.heap[at].kind { - self.bigints.forget(at as Id, n); + let reclaim_fn = match &self.heap[at].kind { + Kind::BigInt(n) => { + self.bigints.forget(at as Id, n); + None + } + Kind::Native { + f, + data: Value::Num(index), + .. + } if std::ptr::fn_addr_eq( + *f, + crate::host::host_native as crate::vm::NativeFn, + ) => + { + Some(*index as usize) + } + _ => None, + }; + if let Some(idx) = reclaim_fn { + self.host.reclaim_function(idx); } *self.heap.slot_mut(at) = Obj::new(None, Kind::Ordinary); self.gc.free.push(at as Id); diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index b493c90a..3f3f177c 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -190,6 +190,10 @@ pub struct FnEntry { /// Whether it is among the globals, even where no path leads (inside an array): such a function never crosses /// back to the host as itself. pub(crate) installed: bool, + /// Whether GC may reclaim this slot when its JS wrapper object is swept (true for direct/local host fns). + pub(crate) reclaimable: bool, + /// Owning `(session_id, local_idx, generation)` in `SESSION_STORES` when created by `HostCtx::new_local_fn`. + pub(crate) local_slot: Option<(u64, usize, u32)>, } /// A host call in flight, as a suspend sees it. @@ -302,7 +306,9 @@ pub struct RunHost { pub(crate) run: Run, pub(crate) next_call: u64, pub tasks: Tasks<'static, Settlement>, - pub(crate) functions: Vec, + pub(crate) functions: Vec>, + /// Free indices in `functions` reclaimed when direct/local host functions are swept by GC. + pub(crate) free_functions: Vec, /// Host calls in flight. pub calls: Vec, /// Results whose functions survive a suspend through their owner's hooks. @@ -404,6 +410,7 @@ impl RunHost { next_call: 0, tasks: Tasks::default(), functions: Vec::new(), + free_functions: Vec::new(), calls: Vec::new(), results: Vec::new(), restarts: Vec::new(), @@ -889,6 +896,31 @@ struct Target { /// A synchronous one is called now: its value crosses back at once, and work it left pending is a promise. When the /// runtime awaits promises in arguments and one hasn't fulfilled, the call waits for them first. fn call_host(vm: &mut Vm, f: &Callee, args: &[Value], target: Target, callee: Value) -> Res { + if let Callee::Fn(hf) = f + && let Body::Direct(d) = &hf.body + { + if vm.native_depth >= crate::vm::MAX_NATIVE_DEPTH || vm.stack_spent() { + return Err(vm.range_error("Maximum call stack size exceeded")); + } + let d = d.clone(); + let prev_gc_safe = vm.session_gc_safe; + vm.session_gc_safe = false; + vm.native_depth += 1; + let mut ctx = crate::session::HostCtx::new(vm); + let res = d( + &mut ctx, + crate::session::DirectArgs::with_this(Value::Undef, args), + ); + vm.native_depth -= 1; + vm.session_gc_safe = prev_gc_safe; + if vm.fatal.is_some() { + return Err(Value::Undef); + } + return match res { + Ok(v) => Ok(vm.sanitize_val(v.0)), + Err(e) => Err(vm.sanitize_val(e.0)), + }; + } let takes = matches!(f, Callee::Fn(f) if f.takes_functions); let raw = template_raw(vm, args); vm.lends.clear(); @@ -1508,9 +1540,9 @@ fn hosted(vm: &Vm, id: Id) -> Option { if !std::ptr::fn_addr_eq(*f, host_native as crate::vm::NativeFn) { return None; } - let entry = vm.host.functions.get(*index as usize)?; + let entry = vm.host.functions.get(*index as usize)?.as_ref()?; match &entry.f { - Callee::Fn(f) if !entry.installed => Some(f.clone()), + Callee::Fn(f) if !entry.installed && entry.local_slot.is_none() => Some(f.clone()), _ => None, } } @@ -2402,13 +2434,58 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option Value { + wrap_direct_with_local(vm, f, None) +} + +/// Like [`wrap_direct`], tagging the entry with a session-local closure slot to release on GC sweep. +pub(crate) fn wrap_direct_with_local( + vm: &mut Vm, + f: HostFunction, + local_slot: Option<(u64, usize, u32)>, +) -> Value { + let constructible = f.constructible; + let label = f.name.to_string(); + let name = f.name().to_owned(); + let length = f.length; + let entry = FnEntry { + f: Callee::Fn(f), + label, + path: None, + owner: None, + installed: false, + reclaimable: true, + local_slot, + }; + let index = if let Some(slot) = vm.host.free_functions.pop() { + vm.host.functions[slot as usize] = Some(entry); + slot as usize + } else { + let idx = vm.host.functions.len(); + vm.host.functions.push(Some(entry)); + idx + }; let made = native(vm, &name, length, host_native, Value::Num(index as f64)); if constructible && let Value::Obj(id) = made @@ -2419,11 +2496,54 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option Res { +impl RunHost { + /// Reclaims a direct/local host function slot when its JS `Kind::Native` wrapper is swept by GC. + pub(crate) fn reclaim_function(&mut self, index: usize) { + if let Some(slot) = self.functions.get_mut(index) + && slot.as_ref().is_some_and(|e| e.reclaimable) + { + if let Some(entry) = slot.take() + && let Some((session_id, local_idx, generation)) = entry.local_slot + { + crate::session::release_local_fn(session_id, local_idx, generation); + } + self.free_functions.push(index as u32); + } + } +} + +pub(crate) fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res { let Value::Num(index) = vm.native_data(callee) else { return Ok(Value::Undef); }; - let entry = &vm.host.functions[index as usize]; + let Some(entry) = vm + .host + .functions + .get(index as usize) + .and_then(|e| e.as_ref()) + else { + return Err(vm.type_error("host function is no longer alive")); + }; + if let Callee::Fn(f) = &entry.f + && let Body::Direct(d) = &f.body + { + if vm.native_depth > crate::vm::MAX_NATIVE_DEPTH || vm.stack_spent() { + return Err(vm.range_error("Maximum call stack size exceeded")); + } + let d = d.clone(); + let prev_gc_safe = vm.session_gc_safe; + vm.session_gc_safe = false; + let mut ctx = crate::session::HostCtx::new(vm); + let res = d(&mut ctx, crate::session::DirectArgs::with_this(this, args)); + vm.session_gc_safe = prev_gc_safe; + if vm.fatal.is_some() { + return Err(Value::Undef); + } + return match res { + Ok(v) => Ok(vm.sanitize_val(v.0)), + Err(e) => Err(vm.sanitize_val(e.0)), + }; + } if let Callee::Fn(f) = &entry.f && let Body::Lost(message) = &f.body { diff --git a/rust/crates/psychoscript/src/host_function.rs b/rust/crates/psychoscript/src/host_function.rs index 23fc912b..f2c4d88f 100644 --- a/rust/crates/psychoscript/src/host_function.rs +++ b/rust/crates/psychoscript/src/host_function.rs @@ -743,11 +743,19 @@ impl std::ops::Deref for DurableCall { type SyncFn = dyn Fn(Vec, &Call) -> Returned + Send + Sync; type AsyncFn = dyn Fn(Vec, Call) -> BoxFuture<'static, HostResult> + Send + Sync; +type DirectFn = dyn Fn( + &mut crate::session::HostCtx<'_>, + crate::session::DirectArgs<'_>, + ) -> Result + + Send + + Sync; #[derive(Clone)] pub(crate) enum Body { Sync(Arc), Async(Arc), + /// A zero-copy synchronous host function operating directly on VM values via [`HostCtx`](crate::HostCtx). + Direct(Arc), /// A function a resumed run lost: calling it throws this message at the call. Lost(Arc), /// A live response's state, read with no call of the host (the reference's `hostGetter`). @@ -808,6 +816,21 @@ impl HostFunction { Self::with_body(Body::Sync(Arc::new(move |args, call| f(args, call).into()))) } + /// A zero-copy synchronous host function that reads and constructs VM values directly through + /// [`HostCtx`](crate::HostCtx) without deep-copying through [`HostValue`]. + pub fn direct(f: F) -> Self + where + F: Fn( + &mut crate::session::HostCtx<'_>, + crate::session::DirectArgs<'_>, + ) -> Result + + Send + + Sync + + 'static, + { + Self::with_body(Body::Direct(Arc::new(f))) + } + /// An asynchronous function: the program gets a promise at once. pub fn new_async(f: impl Fn(Vec, Call) -> F + Send + Sync + 'static) -> Self where diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index e8d4e0c3..29fc5c07 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -40,6 +40,7 @@ mod promise; mod reach; mod run; mod runtime; +mod session; mod snapshot; mod stack; mod streaming; @@ -70,6 +71,7 @@ pub use runtime::{ Outcome, ProgramOptions, Run, Runtime, Translate, TranslateFunctions, TranslatePromises, }; pub use serde_json::Value as Json; +pub use session::{DirectArgs, FnHandle, HostCtx, Key, Session, Val, ValHandle}; pub use snapshot::{Snapshot, SnapshotError, from_bytes, to_bytes}; pub use streaming::{HttpBody, StreamingResponse}; diff --git a/rust/crates/psychoscript/src/promise.rs b/rust/crates/psychoscript/src/promise.rs index 187c0979..37cb1749 100644 --- a/rust/crates/psychoscript/src/promise.rs +++ b/rust/crates/psychoscript/src/promise.rs @@ -329,6 +329,14 @@ impl Vm { } pub fn run_job(&mut self, job: Job) -> Result<(), Value> { + let prev_gc_safe = self.session_gc_safe; + self.session_gc_safe = false; + let r = self.run_job_inner(job); + self.session_gc_safe = prev_gc_safe; + r + } + + fn run_job_inner(&mut self, job: Job) -> Result<(), Value> { match job { Job::Thenable { promise, diff --git a/rust/crates/psychoscript/src/reach.rs b/rust/crates/psychoscript/src/reach.rs index 0f86fd9b..51a37596 100644 --- a/rust/crates/psychoscript/src/reach.rs +++ b/rust/crates/psychoscript/src/reach.rs @@ -32,6 +32,17 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { t.frame(f); } t.vals(vm.globals.iter()); + if let Some(roots) = vm.host_roots.as_deref() { + t.val(&roots.session_exports); + for slot in &roots.pinned { + if let Some(v) = &slot.value { + t.val(v); + } + } + for &a in &roots.host_atoms { + t.atom(a); + } + } for (k, v) in &vm.global_map { t.atom(*k); t.val(v); @@ -66,6 +77,7 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { std.headers, std.array_buffer, std.data_view, + std.bigint, ] .into_iter() .chain(std.typed) diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 2eedb378..5d5b65a6 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -319,6 +319,21 @@ impl Runtime { Program::new(self, code.into(), options) } + /// Compiles and runs `code`'s top-level setup, returning a persistent [`Session`](crate::Session) for repeated + /// low-latency calls into guest functions. + pub fn session<'c>(&self, code: impl Into>) -> Result> { + crate::Session::start(self, code.into(), &ProgramOptions::default()) + } + + /// [`Runtime::session`] with [`ProgramOptions`]. + pub fn session_with<'c>( + &self, + code: impl Into>, + options: &ProgramOptions, + ) -> Result> { + crate::Session::start(self, code.into(), options) + } + /// Parses and compiles a program once, for [`Runtime::program`] and the `execute` methods to run many times /// without doing it again; or the diagnostic a run of it would fail with first (an empty program, a syntax /// error). Unsupported syntax still fails where it runs, as from source. A compiled program runs in any runtime. diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs new file mode 100644 index 00000000..d731faee --- /dev/null +++ b/rust/crates/psychoscript/src/session.rs @@ -0,0 +1,1770 @@ +//! Persistent VM sessions and zero-copy synchronous host callbacks for low-latency embedders. +//! +//! A [`Session`] keeps a live VM across repeated calls into guest functions ([`Session::call_fn`]), +//! and [`HostFunction::direct`](crate::HostFunction::direct) lets synchronous host functions read +//! and build VM values directly through [`HostCtx`] without deep-copying through [`HostValue`](crate::HostValue). + +use std::any::{Any, TypeId}; +use std::borrow::Cow; +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use rustc_hash::FxHashMap; + +use crate::object::{ + ACCESSOR, DEFAULT_FLAGS, ENUMERABLE, FIXED, FROZEN, Kind, NON_EXTENSIBLE, PENDING_STACK, + SPARSE, WRITABLE, +}; +use crate::ops::MAX_ARRAY_LEN; +use crate::run; +use crate::runtime::ProgramOptions; +use crate::strings::{Atom, SYM_LAST}; +use crate::value::Value; +use crate::vm::Vm; +use crate::{Code, Diagnostic, DiagnosticKind, HostFunction, Limits, Outcome, Runtime}; + +/// Largest integer exactly representable in IEEE 754 f64 (2^53 - 1). +const MAX_SAFE_INT: f64 = 9_007_199_254_740_991.0; + +/// Default per-call microtask budget for [`Session::drain_jobs`]. +const DEFAULT_DRAIN_JOBS_BUDGET: usize = 4096; + +static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1); + +type LocalDirectFn = dyn Fn(&mut HostCtx<'_>, DirectArgs<'_>) -> Result; + +struct LocalFnSlot { + func: Option>, + generation: u32, +} + +#[derive(Default)] +struct SessionStore { + local_fns: Vec, + local_fns_free: Vec, + user_data: FxHashMap>>>, +} + +thread_local! { + static SESSION_STORES: RefCell> = RefCell::new(FxHashMap::default()); +} + +#[inline(always)] +fn next_generation(generation: u32) -> u32 { + let next = generation.wrapping_add(1); + if next == 0 { 1 } else { next } +} + +/// Allocates a unique non-zero id for every `Vm` instance so typed `ValHandle`/`FnHandle` values +/// can never collide across standalone `Runtime::execute` runs or `Session` instances. +pub(crate) fn next_session_id() -> u64 { + let id = NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed); + if id == 0 { + NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed) + } else { + id + } +} + +fn alloc_session_store(id: u64) { + let _ = SESSION_STORES.try_with(|m| { + m.borrow_mut().insert(id, SessionStore::default()); + }); +} + +fn drop_session_store(id: u64) { + if id != 0 { + let removed = SESSION_STORES + .try_with(|m| m.borrow_mut().remove(&id)) + .ok() + .flatten(); + // Drop outside the RefCell borrow guard so nested Session drops cannot panic. + drop(removed); + } +} + +/// RAII guard ensuring a newly allocated session store is released if `Session::start` unwinds +/// or returns an error before constructing `Session`. +struct SessionInitGuard { + session_id: u64, + active: bool, +} + +impl SessionInitGuard { + fn new(session_id: u64) -> Self { + Self { + session_id, + active: true, + } + } + + fn disarm(&mut self) { + self.active = false; + } +} + +impl Drop for SessionInitGuard { + fn drop(&mut self) { + if self.active { + drop_session_store(self.session_id); + } + } +} + +fn store_local_fn(session_id: u64, f: Rc) -> Option<(usize, u32)> { + if session_id == 0 { + return None; + } + SESSION_STORES + .try_with(|m| { + let mut map = m.borrow_mut(); + let store = map.get_mut(&session_id)?; + if let Some(idx) = store.local_fns_free.pop() { + let slot = &mut store.local_fns[idx]; + slot.func = Some(f); + Some((idx, slot.generation)) + } else { + let idx = store.local_fns.len(); + store.local_fns.push(LocalFnSlot { + func: Some(f), + generation: 1, + }); + Some((idx, 1)) + } + }) + .ok() + .flatten() +} + +fn get_local_fn(session_id: u64, idx: usize, generation: u32) -> Option> { + if session_id == 0 || generation == 0 { + return None; + } + SESSION_STORES + .try_with(|m| { + m.borrow() + .get(&session_id) + .and_then(|s| s.local_fns.get(idx)) + .filter(|slot| slot.generation == generation) + .and_then(|slot| slot.func.as_ref()) + .cloned() + }) + .ok() + .flatten() +} + +/// Releases a session-local closure slot when its JS wrapper object is swept by GC. +pub(crate) fn release_local_fn(session_id: u64, idx: usize, generation: u32) { + if session_id == 0 || generation == 0 { + return; + } + let dropped = SESSION_STORES + .try_with(|m| { + let mut map = m.borrow_mut(); + let store = map.get_mut(&session_id)?; + let slot = store.local_fns.get_mut(idx)?; + if slot.generation != generation { + return None; + } + let old = slot.func.take()?; + slot.generation = next_generation(slot.generation); + store.local_fns_free.push(idx); + Some(old) + }) + .ok() + .flatten(); + // Drop outside the RefCell borrow guard in case captured state drops a Session. + drop(dropped); +} + +fn store_set_user_data(session_id: u64, val: T) { + if session_id == 0 { + return; + } + let previous = SESSION_STORES + .try_with(|m| { + m.borrow_mut().get_mut(&session_id).and_then(|store| { + store + .user_data + .insert(TypeId::of::(), Rc::new(RefCell::new(Box::new(val)))) + }) + }) + .ok() + .flatten(); + // Drop replaced user data outside the RefCell borrow guard. + drop(previous); +} + +fn store_get_cell(session_id: u64) -> Option>>> { + if session_id == 0 { + return None; + } + SESSION_STORES + .try_with(|m| { + m.borrow() + .get(&session_id) + .and_then(|s| s.user_data.get(&TypeId::of::())) + .cloned() + }) + .ok() + .flatten() +} + +#[inline(always)] +fn normalize_hole(v: Value) -> Val { + if matches!(v, Value::Uninit) { + Val::UNDEFINED + } else { + Val(v) + } +} + +#[inline] +fn lookup_atom(vm: &Vm, name: &str) -> Option { + if !crate::strings::has_mark(name) { + vm.atoms.lookup(name) + } else { + let carrier = crate::strings::external_text(name.to_owned()); + vm.atoms.lookup(&carrier) + } +} + +#[inline] +fn lookup_global_by_key(vm: &Vm, key: Key) -> Option { + if let Some(v) = vm.global_map.get(&key.0).copied() { + return (!matches!(v, Value::Uninit)).then_some(Val(v)); + } + vm.global_names + .iter() + .position(|&a| a == key.0) + .and_then(|i| vm.globals.get(i).copied()) + .filter(|v| !matches!(v, Value::Uninit)) + .map(Val) +} + +#[inline] +fn lookup_global(vm: &Vm, name: &str) -> Option { + let atom = lookup_atom(vm, name)?; + lookup_global_by_key(vm, Key(atom)) +} + +/// A lightweight, `Copy` handle to a JS value inside a live VM. +/// +/// **GC lifetime:** An unpinned `Val` is only valid until the next JS call or GC step +/// ([`Session::call_fn`], [`Session::call_val`], [`HostCtx::call_fn_val`], [`Session::drain_jobs`], +/// [`Session::gc_step`], or [`Session::collect_garbage`]). To keep a value alive across calls or +/// collection cycles, pin it with [`Session::pin_val`] / [`HostCtx::pin_val`] ([`ValHandle`]) or +/// [`Session::pin_fn`] / [`HostCtx::pin_fn`] ([`FnHandle`]). +#[derive(Clone, Copy, Debug)] +pub struct Val(pub(crate) Value); + +impl Val { + pub const UNDEFINED: Val = Val(Value::Undef); + pub const NULL: Val = Val(Value::Null); + + #[inline(always)] + pub const fn bool(b: bool) -> Self { + Val(Value::Bool(b)) + } + + #[inline(always)] + pub const fn num(n: f64) -> Self { + Val(Value::Num(n)) + } + + #[inline(always)] + pub const fn is_undefined(self) -> bool { + matches!(self.0, Value::Undef | Value::Uninit) + } + + #[inline(always)] + pub const fn is_null(self) -> bool { + matches!(self.0, Value::Null) + } + + #[inline(always)] + pub const fn is_nullish(self) -> bool { + matches!(self.0, Value::Undef | Value::Uninit | Value::Null) + } + + #[inline(always)] + pub const fn is_bool(self) -> bool { + matches!(self.0, Value::Bool(_)) + } + + #[inline(always)] + pub const fn is_num(self) -> bool { + matches!(self.0, Value::Num(_)) + } + + #[inline(always)] + pub const fn is_str(self) -> bool { + matches!(self.0, Value::Str(_)) + } + + #[inline(always)] + pub const fn is_obj_ref(self) -> bool { + matches!(self.0, Value::Obj(_)) + } + + #[inline(always)] + pub const fn as_bool(self) -> Option { + match self.0 { + Value::Bool(b) => Some(b), + _ => None, + } + } + + #[inline(always)] + pub const fn as_f64(self) -> Option { + match self.0 { + Value::Num(n) => Some(n), + _ => None, + } + } + + /// Returns the integer value when this is a finite whole number within `0..=u32::MAX`. + #[inline(always)] + pub fn as_u32(self) -> Option { + match self.0 { + Value::Num(n) + if n.is_finite() && n.fract() == 0.0 && (0.0..=u32::MAX as f64).contains(&n) => + { + Some(n as u32) + } + _ => None, + } + } + + /// Returns the integer value when this is a finite whole number within `i32::MIN..=i32::MAX`. + #[inline(always)] + pub fn as_i32(self) -> Option { + match self.0 { + Value::Num(n) + if n.is_finite() + && n.fract() == 0.0 + && (i32::MIN as f64..=i32::MAX as f64).contains(&n) => + { + Some(n as i32) + } + _ => None, + } + } + + /// Returns the integer value when this is a finite whole number within IEEE 754 safe integer range. + #[inline(always)] + pub fn as_i64(self) -> Option { + match self.0 { + Value::Num(n) if n.is_finite() && n.fract() == 0.0 && n.abs() <= MAX_SAFE_INT => { + Some(n as i64) + } + _ => None, + } + } +} + +impl From for Val { + #[inline(always)] + fn from(b: bool) -> Self { + Val::bool(b) + } +} + +impl From for Val { + #[inline(always)] + fn from(n: f64) -> Self { + Val::num(n) + } +} + +impl From for Val { + #[inline(always)] + fn from(n: u32) -> Self { + Val::num(n as f64) + } +} + +impl From for Val { + #[inline(always)] + fn from(n: i32) -> Self { + Val::num(n as f64) + } +} + +impl From for Val { + #[inline(always)] + fn from(n: i64) -> Self { + Val::num(n as f64) + } +} + +impl From for Val { + #[inline(always)] + fn from(n: usize) -> Self { + Val::num(n as f64) + } +} + +/// A pre-interned, permanently GC-rooted property key for zero-allocation object reads and writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Key(pub(crate) Atom); + +impl Key { + #[inline(always)] + pub const fn raw(self) -> u32 { + self.0 + } +} + +/// A GC-rooted, session-scoped, generation-tagged handle to a callable guest function inside a [`Session`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FnHandle { + session_id: u64, + idx: u32, + generation: u32, +} + +impl FnHandle { + #[inline(always)] + pub const fn raw(self) -> u64 { + ((self.generation as u64) << 32) | (self.idx as u64) + } +} + +/// A GC-rooted, session-scoped, generation-tagged handle to an arbitrary JS value inside a [`Session`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ValHandle { + session_id: u64, + idx: u32, + generation: u32, +} + +impl ValHandle { + #[inline(always)] + pub const fn raw(self) -> u64 { + ((self.generation as u64) << 32) | (self.idx as u64) + } +} + +/// Borrowed arguments passed to a [`HostFunction::direct`](crate::HostFunction::direct) callback. +#[derive(Clone, Copy)] +pub struct DirectArgs<'a> { + this: Value, + args: &'a [Value], +} + +impl<'a> DirectArgs<'a> { + #[inline(always)] + pub(crate) fn with_this(this: Value, args: &'a [Value]) -> Self { + Self { this, args } + } + + /// The `this` receiver of the call (with `Value::Uninit` normalized to [`Val::UNDEFINED`]). + #[inline(always)] + pub fn this(&self) -> Val { + normalize_hole(self.this) + } + + #[inline(always)] + pub fn len(&self) -> usize { + self.args.len() + } + + #[inline(always)] + pub fn is_empty(&self) -> bool { + self.args.is_empty() + } + + /// The argument at `index`, or [`Val::UNDEFINED`] if out of range. + #[inline(always)] + pub fn get(&self, index: usize) -> Val { + normalize_hole(self.args.get(index).copied().unwrap_or(Value::Undef)) + } +} + +/// Borrowed view into a live VM for zero-copy value inspection and construction. +pub struct HostCtx<'a> { + vm: &'a mut Vm, +} + +impl<'a> HostCtx<'a> { + #[inline(always)] + pub(crate) fn new(vm: &'a mut Vm) -> Self { + Self { vm } + } + + /// Interns a property name WITHOUT permanently rooting it in `Vm::host_atoms`. + #[inline] + pub(crate) fn intern_key(&mut self, name: &str) -> Key { + let atom = if !crate::strings::has_mark(name) { + self.vm.atoms.intern(name) + } else { + let carrier = crate::strings::external_text(name.to_owned()); + self.vm.atoms.intern(&carrier) + }; + Key(atom) + } + + /// Interns a property name once and permanently roots it for the lifetime of the VM so GC never + /// reclaims it. Ideal for fixed property/event keys cached by the embedder. + #[inline] + pub fn key(&mut self, name: &str) -> Key { + let key = self.intern_key(name); + let roots = self.vm.host_roots_mut(); + if roots.host_atom_set.insert(key.0) { + roots.host_atoms.push(key.0); + } + key + } + + /// Returns the decoded UTF-8 text of an interned [`Key`], or `""` if the key is invalid. + #[inline] + pub fn key_name(&self, key: Key) -> Cow<'_, str> { + self.vm + .atoms + .text_opt(key.0) + .map(crate::strings::host_text) + .unwrap_or(Cow::Borrowed("")) + } + + /// Whether `v` is a live JS Array. + #[inline(always)] + pub fn is_array(&self, v: Val) -> bool { + let Value::Obj(id) = v.0 else { + return false; + }; + self.vm + .live_obj(id) + .is_some_and(|o| matches!(o.kind, Kind::Array(_))) + } + + /// Whether `v` is a live non-null, non-array, non-callable, non-bytes JS object. + #[inline(always)] + pub fn is_object(&self, v: Val) -> bool { + let Value::Obj(id) = v.0 else { + return false; + }; + let Some(obj) = self.vm.live_obj(id) else { + return false; + }; + !obj.is_callable() && !matches!(obj.kind, Kind::Array(_) | Kind::Bytes(_)) + } + + /// Whether `v` is a live plain ordinary JS object (`{}`). + #[inline(always)] + pub fn is_plain_object(&self, v: Val) -> bool { + let Value::Obj(id) = v.0 else { + return false; + }; + self.vm + .live_obj(id) + .is_some_and(|o| matches!(o.kind, Kind::Ordinary)) + } + + /// Whether `v` is a live callable JS function. + #[inline(always)] + pub fn is_fn(&self, v: Val) -> bool { + let Value::Obj(id) = v.0 else { + return false; + }; + self.vm.live_obj(id).is_some_and(|o| o.is_callable()) + } + + /// Whether `v` is a live `Uint8Array`, `Buffer`, `ArrayBuffer`, or other typed array. + #[inline(always)] + pub fn is_bytes(&self, v: Val) -> bool { + let Value::Obj(id) = v.0 else { + return false; + }; + self.vm + .live_obj(id) + .is_some_and(|o| matches!(o.kind, Kind::Bytes(_))) + } + + /// Human-readable JS type name of `v` for diagnostics. + pub fn type_name(&self, v: Val) -> &'static str { + match v.0 { + Value::Undef | Value::Uninit => "undefined", + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Num(_) => "number", + Value::Str(_) => "string", + Value::Sym(_) => "symbol", + Value::Big(_) => "bigint", + Value::Obj(id) => { + let Some(obj) = self.vm.live_obj(id) else { + return "undefined"; + }; + if obj.is_callable() { + "function" + } else { + match &obj.kind { + Kind::Array(_) => "array", + Kind::Bytes(b) => b.elem.name(), + _ => "object", + } + } + } + } + } + + /// Returns the heap object id of `v`, if it is a live heap object. + #[inline(always)] + pub fn obj_id(&self, v: Val) -> Option { + let Value::Obj(id) = v.0 else { + return None; + }; + self.vm.live_obj(id).map(|_| id) + } + + /// Whether `v` is a live frozen JS object (`Object.freeze(...)`). + #[inline(always)] + pub fn obj_is_frozen(&self, v: Val) -> bool { + let Value::Obj(id) = v.0 else { + return false; + }; + self.vm.live_obj(id).is_some_and(|o| o.flags & FROZEN != 0) + } + + /// Borrows a JS string value directly as `&str` when it is live, well-formed UTF-8 without carrier marks. + #[inline(always)] + pub fn as_str(&self, v: Val) -> Option<&str> { + let Value::Str(s) = v.0 else { + return None; + }; + let text = self.vm.atoms.get_opt(s)?; + if crate::strings::has_mark(text) { + None + } else { + Some(text) + } + } + + /// Converts a JS string value to an owned UTF-8 `String` (decoding any carrier marks lossily). + pub fn to_string_lossy(&self, v: Val) -> Option { + let Value::Str(s) = v.0 else { + return None; + }; + let text = self.vm.atoms.get_opt(s)?; + Some(crate::strings::host_text(text).into_owned()) + } + + /// Formats a JS value purely from heap inspection without ever invoking user JS + /// (`toString`, `valueOf`, `[Symbol.toPrimitive]`, or property getters). + fn format_val_safe(&self, v: Value) -> String { + match v { + Value::Undef | Value::Uninit => "undefined".to_owned(), + Value::Null => "null".to_owned(), + Value::Bool(b) => if b { "true" } else { "false" }.to_owned(), + Value::Num(n) => crate::value::num_to_string(n), + Value::Str(s) => self + .vm + .atoms + .get_opt(s) + .map(|t| crate::strings::host_text(t).into_owned()) + .unwrap_or_default(), + Value::Sym(s) => crate::ops::symbol_text(s).to_owned(), + Value::Big(id) => format!("{}n", self.vm.big_text(id)), + Value::Obj(id) => { + let Some(obj) = self.vm.live_obj(id) else { + return "undefined".to_owned(); + }; + let name = self.read_data_str_prop(id, self.vm.names.name); + let message = self.read_data_str_prop(id, self.vm.names.message); + let is_err = matches!(obj.kind, Kind::Error(_)); + if is_err || message.is_some() { + let name = name.unwrap_or_else(|| "Error".to_owned()); + let msg = message.unwrap_or_default(); + return match (name.is_empty(), msg.is_empty()) { + (false, false) => format!("{name}: {msg}"), + (false, true) => name, + (true, false) => msg, + (true, true) => "Error".to_owned(), + }; + } + format!("[{}]", self.type_name(Val(v))) + } + } + } + + /// Reads a primitive data property along the prototype chain (bounded depth) without invoking getters. + fn read_data_str_prop(&self, mut id: u32, key: Atom) -> Option { + for _ in 0..16 { + let obj = self.vm.live_obj(id)?; + if let Some(p) = obj.props.prop(key) { + if p.flags & ACCESSOR != 0 { + return None; + } + return match p.value() { + Value::Str(s) => self + .vm + .atoms + .get_opt(s) + .map(|t| crate::strings::host_text(t).into_owned()), + Value::Num(n) => Some(crate::value::num_to_string(n)), + Value::Bool(b) => Some(if b { "true" } else { "false" }.to_owned()), + _ => None, + }; + } + let Some(proto) = obj.proto else { + break; + }; + id = proto; + } + None + } + + /// Allocates a JS string directly in the VM's string arena. + #[inline] + pub fn new_str(&mut self, s: &str) -> Val { + if !crate::strings::has_mark(s) { + Val(self.vm.string_of_str(s)) + } else { + Val(self + .vm + .string_val(crate::strings::external_text(s.to_owned()))) + } + } + + /// Builds an object with its initial fields in one allocation, deduplicating repeated keys + /// (last value wins) so `Object.keys` never observes duplicate entries. + #[inline] + pub fn new_object_with(&mut self, fields: &[(Key, Val)]) -> Val { + let proto = self.vm.realm.object_proto; + let mut props = crate::object::Props::default(); + if !fields.is_empty() { + props.reserve_exact(fields.len()); + } + for &(k, v) in fields { + if self.vm.atoms.text_opt(k.0).is_none() { + continue; + } + let v = self.vm.sanitize_val(v.0); + self.vm.gc_shade_atom(k.0); + self.vm.gc_shade(v); + props.insert(k.0, v, DEFAULT_FLAGS); + } + let prop_count = props.items.len() as u64; + if prop_count > 0 { + self.vm + .charge_heap(crate::heap::PROPERTY_BYTES * prop_count); + } + let mut obj = crate::object::Obj::new(Some(proto), Kind::Ordinary); + obj.props = props; + let id = self.vm.alloc(obj); + Val(Value::Obj(id)) + } + + /// Creates a plain JS object with property storage pre-reserved for `capacity` fields. + #[inline] + pub fn new_object(&mut self, capacity: usize) -> Val { + let id = self.vm.new_object(); + if capacity > 0 + && let Some(obj) = self.vm.live_obj_mut(id) + { + obj.props.reserve_exact(capacity); + } + Val(Value::Obj(id)) + } + + /// Appends or updates a property on a JS object while preserving object invariants (no duplicate + /// keys, respects frozen/non-writable/non-extensible flags, and charges the heap meter). + #[inline] + pub fn obj_push_new(&mut self, obj: Val, key: Key, val: Val) { + self.obj_set(obj, key, val); + } + + /// Sets a property on an object by pre-interned [`Key`], respecting JS object invariants + /// (frozen/non-extensible/non-writable guards, resetting stale `ACCESSOR`/`PENDING_STACK` flags, + /// and array index synchronization). + #[inline] + pub fn obj_set(&mut self, obj: Val, key: Key, val: Val) { + let Value::Obj(id) = obj.0 else { + return; + }; + if self.vm.atoms.text_opt(key.0).is_none() { + return; + } + let Some(target) = self.vm.live_obj(id) else { + return; + }; + let obj_flags = target.flags; + if obj_flags & FROZEN != 0 { + return; + } + let is_array = matches!(target.kind, Kind::Array(_)); + let val = self.vm.sanitize_val(val.0); + self.vm.gc_shade_atom(key.0); + self.vm.gc_shade(val); + + if is_array { + if key.0 == self.vm.names.length { + return; + } + if let Some(index) = self.vm.atoms.index(key.0) { + let i = index as usize; + let lk = self.vm.names.length; + if obj_flags & SPARSE == 0 { + let cur_len = match &self.vm.heap[id as usize].kind { + Kind::Array(items) => items.len(), + _ => 0, + }; + if i < cur_len { + if let Some(o) = self.vm.live_obj_mut(id) + && let Kind::Array(items) = &mut o.kind + { + items[i] = val; + } + return; + } + if obj_flags & NON_EXTENSIBLE != 0 { + return; + } + if i < MAX_ARRAY_LEN { + let grown = i + 1 - cur_len; + if let Some(o) = self.vm.live_obj_mut(id) + && let Kind::Array(items) = &mut o.kind + { + items.resize(i, Value::Uninit); + items.push(val); + } + self.vm + .charge_heap(crate::heap::ELEMENT_BYTES * grown as u64); + return; + } + let len = cur_len.max(i + 1); + if let Some(o) = self.vm.live_obj_mut(id) { + o.flags |= SPARSE; + o.props.insert(key.0, val, DEFAULT_FLAGS); + o.props.insert(lk, Value::Num(len as f64), 0); + } + self.vm.charge_heap(crate::heap::PROPERTY_BYTES); + return; + } + let cur_len = self.vm.array_len(id); + if let Some(o) = self.vm.live_obj_mut(id) { + if let Kind::Array(items) = &mut o.kind + && i < items.len() + { + items[i] = val; + return; + } + if let Some(pos) = o.props.find(key.0) { + let pf = o.props.items[pos].flags; + if pf & ACCESSOR != 0 { + if pf & FIXED != 0 { + return; + } + o.props.items[pos].set_value(val); + o.props.items[pos].flags = DEFAULT_FLAGS; + } else { + if pf & WRITABLE == 0 { + return; + } + o.props.items[pos].set_value(val); + o.props.items[pos].flags = pf & !PENDING_STACK; + } + return; + } + if obj_flags & NON_EXTENSIBLE != 0 { + return; + } + o.props.push_new(key.0, val, DEFAULT_FLAGS); + if i >= cur_len { + o.props.insert(lk, Value::Num((i + 1) as f64), 0); + } + } + self.vm.charge_heap(crate::heap::PROPERTY_BYTES); + return; + } + } + + let mut added = false; + if let Some(o) = self.vm.live_obj_mut(id) { + if let Some(pos) = o.props.find(key.0) { + let pf = o.props.items[pos].flags; + if pf & ACCESSOR != 0 { + if pf & FIXED != 0 { + return; + } + o.props.items[pos].set_value(val); + o.props.items[pos].flags = DEFAULT_FLAGS; + } else { + if pf & WRITABLE == 0 { + return; + } + o.props.items[pos].set_value(val); + o.props.items[pos].flags = pf & !PENDING_STACK; + } + } else { + if o.flags & NON_EXTENSIBLE != 0 { + return; + } + o.props.push_new(key.0, val, DEFAULT_FLAGS); + added = true; + } + } + if added { + self.vm.charge_heap(crate::heap::PROPERTY_BYTES); + } + } + + /// Sets a property on an object by string name without permanently rooting the key atom in + /// `Vm::host_atoms`. + #[inline] + pub fn obj_set_str(&mut self, obj: Val, name: &str, val: Val) { + let key = self.intern_key(name); + self.obj_set(obj, key, val); + } + + /// Reads an own data property on an object by pre-interned [`Key`]. + #[inline(always)] + pub fn obj_get(&self, obj: Val, key: Key) -> Option { + let Value::Obj(id) = obj.0 else { + return None; + }; + let o = self.vm.live_obj(id)?; + let prop = o.props.prop(key.0)?; + if prop.flags & ACCESSOR != 0 { + return None; + } + Some(Val(prop.value())) + } + + /// Reads an own numeric property on an object by pre-interned [`Key`]. + #[inline(always)] + pub fn obj_get_f64(&self, obj: Val, key: Key) -> Option { + self.obj_get(obj, key).and_then(Val::as_f64) + } + + /// Reads an own string property on an object by pre-interned [`Key`]. + #[inline(always)] + pub fn obj_get_str(&self, obj: Val, key: Key) -> Option<&str> { + let v = self.obj_get(obj, key)?; + self.as_str(v) + } + + /// Visits every own enumerable string-keyed data property of `obj` in insertion order + /// (skipping symbol keys and accessor properties). + #[inline] + pub fn obj_for_each(&self, obj: Val, mut f: impl FnMut(&str, Val)) -> bool { + let Value::Obj(id) = obj.0 else { + return false; + }; + let Some(o) = self.vm.live_obj(id) else { + return false; + }; + for prop in o.props.items.iter() { + if prop.key <= SYM_LAST || prop.flags & ENUMERABLE == 0 || prop.flags & ACCESSOR != 0 { + continue; + } + let Some(raw) = self.vm.atoms.text_opt(prop.key) else { + continue; + }; + if !crate::strings::has_mark(raw) { + f(raw, Val(prop.value())); + } else { + let decoded = crate::strings::host_text(raw); + f(&decoded, Val(prop.value())); + } + } + true + } + + /// Visits every own enumerable string-keyed data property of `obj` in insertion order, + /// passing `Some(Key)` when the property key is permanently rooted via [`HostCtx::key`] and + /// `None` for unrooted dynamic keys (so an unrooted `Key` can never escape). + #[inline] + pub fn obj_for_each_key(&self, obj: Val, mut f: impl FnMut(Option, &str, Val)) -> bool { + let Value::Obj(id) = obj.0 else { + return false; + }; + let Some(o) = self.vm.live_obj(id) else { + return false; + }; + for prop in o.props.items.iter() { + if prop.key <= SYM_LAST || prop.flags & ENUMERABLE == 0 || prop.flags & ACCESSOR != 0 { + continue; + } + let Some(raw) = self.vm.atoms.text_opt(prop.key) else { + continue; + }; + let rooted_key = self + .vm + .host_roots + .as_deref() + .is_some_and(|r| r.host_atom_set.contains(&prop.key)) + .then_some(Key(prop.key)); + if !crate::strings::has_mark(raw) { + f(rooted_key, raw, Val(prop.value())); + } else { + let decoded = crate::strings::host_text(raw); + f(rooted_key, &decoded, Val(prop.value())); + } + } + true + } + + /// Creates a dense JS array pre-allocated for `capacity` elements. + #[inline] + pub fn new_array(&mut self, capacity: usize) -> Val { + Val(self.vm.new_array(Vec::with_capacity(capacity))) + } + + /// Appends an element to a JS array (handles both dense and sparse arrays, guards frozen / + /// non-extensible / max JS array length, and charges the heap meter). + #[inline] + pub fn array_push(&mut self, arr: Val, val: Val) { + let Value::Obj(id) = arr.0 else { + return; + }; + let Some(obj) = self.vm.live_obj(id) else { + return; + }; + if !matches!(obj.kind, Kind::Array(_)) || obj.flags & (FROZEN | NON_EXTENSIBLE) != 0 { + return; + } + let len = self.vm.array_len(id); + if len >= u32::MAX as usize { + return; + } + let is_sparse = obj.flags & SPARSE != 0; + let val = self.vm.sanitize_val(val.0); + self.vm.gc_shade(val); + if !is_sparse { + if len < MAX_ARRAY_LEN { + if let Some(o) = self.vm.live_obj_mut(id) + && let Kind::Array(items) = &mut o.kind + { + items.push(val); + } + self.vm.charge_heap(crate::heap::ELEMENT_BYTES); + return; + } + let key = self.intern_key(&len.to_string()).0; + let lk = self.vm.names.length; + if let Some(o) = self.vm.live_obj_mut(id) { + o.flags |= SPARSE; + o.props.insert(key, val, DEFAULT_FLAGS); + o.props.insert(lk, Value::Num((len + 1) as f64), 0); + } + self.vm.charge_heap(crate::heap::PROPERTY_BYTES); + return; + } + let key = self.intern_key(&len.to_string()).0; + let lk = self.vm.names.length; + if let Some(o) = self.vm.live_obj_mut(id) { + o.props.insert(key, val, DEFAULT_FLAGS); + o.props.insert(lk, Value::Num((len + 1) as f64), 0); + } + self.vm.charge_heap(crate::heap::PROPERTY_BYTES); + } + + /// Returns the logical length of a JS array (handles both dense and sparse arrays). + #[inline(always)] + pub fn array_len(&self, arr: Val) -> Option { + let Value::Obj(id) = arr.0 else { + return None; + }; + let obj = self.vm.live_obj(id)?; + if !matches!(obj.kind, Kind::Array(_)) { + return None; + } + Some(self.vm.array_len(id)) + } + + /// Reads an element from a JS array without copying the array (handles both dense and sparse arrays). + /// Holes within `0..len` read as [`Val::UNDEFINED`]; out-of-range indices return `None`. + #[inline] + pub fn array_get(&self, arr: Val, index: usize) -> Option { + let Value::Obj(id) = arr.0 else { + return None; + }; + let obj = self.vm.live_obj(id)?; + let Kind::Array(items) = &obj.kind else { + return None; + }; + if obj.flags & SPARSE == 0 { + return items.get(index).copied().map(normalize_hole); + } + let len = self.vm.array_len(id); + if index >= len { + return None; + } + if let Some(&v) = items.get(index) + && !matches!(v, Value::Uninit) + { + return Some(Val(v)); + } + let key_str = index.to_string(); + if let Some(atom) = self.vm.atoms.lookup(&key_str) + && let Some(prop) = obj.props.prop(atom) + && prop.flags & ACCESSOR == 0 + { + return Some(normalize_hole(prop.value())); + } + Some(Val::UNDEFINED) + } + + /// Calls `f` with each element of a JS array. + /// + /// For dense arrays, visits every slot `0..len` without allocating (holes yield + /// [`Val::UNDEFINED`]). For sparse arrays, visits every populated data element in ascending + /// index order (dense prefix + sparse tail, skipping accessor properties) in O(populated) time. + #[inline] + pub fn array_for_each(&self, arr: Val, mut f: impl FnMut(Val)) -> bool { + let Value::Obj(id) = arr.0 else { + return false; + }; + let Some(obj) = self.vm.live_obj(id) else { + return false; + }; + let Kind::Array(items) = &obj.kind else { + return false; + }; + if obj.flags & SPARSE == 0 { + for &item in items { + f(normalize_hole(item)); + } + return true; + } + for &item in items { + if !matches!(item, Value::Uninit) { + f(Val(item)); + } + } + let mut tail: Vec<(usize, Value)> = obj + .props + .items + .iter() + .filter(|p| p.flags & ACCESSOR == 0) + .filter_map(|p| Some((self.vm.atoms.index(p.key)? as usize, p.value()))) + .collect(); + tail.sort_unstable_by_key(|(i, _)| *i); + for (_, item) in tail { + if !matches!(item, Value::Uninit) { + f(Val(item)); + } + } + true + } + + /// Borrows the raw bytes of a `Uint8Array`, `Buffer`, `ArrayBuffer`, or other typed array. + #[inline] + pub fn as_bytes(&self, v: Val) -> Option<&[u8]> { + let Value::Obj(id) = v.0 else { + return None; + }; + let obj = self.vm.live_obj(id)?; + match &obj.kind { + Kind::Bytes(b) => Some(b.data(self.vm)), + _ => None, + } + } + + /// Creates a new `Uint8Array` holding a copy of `bytes`. + #[inline] + pub fn new_bytes(&mut self, bytes: &[u8]) -> Val { + Val(crate::builtins::bytes::new_bytes( + self.vm, + bytes.to_vec(), + false, + )) + } + + /// Wraps a synchronous direct [`HostFunction`] into a callable JS function value inside this VM. + #[inline] + pub fn new_direct_fn(&mut self, f: HostFunction) -> Val { + Val(crate::host::wrap_direct(self.vm, f)) + } + + /// Wraps a thread-local (`!Send`) direct callback into a callable JS function owned by this [`Session`]. + /// Reclaimed automatically when the returned JS function becomes unreachable and is swept by GC. + pub fn new_local_fn(&mut self, name: &str, f: F) -> Val + where + F: Fn(&mut HostCtx<'_>, DirectArgs<'_>) -> Result + 'static, + { + let session_id = self.vm.session_id; + let slot_info = store_local_fn(session_id, Rc::new(f)); + let local_slot = slot_info.map(|(i, g)| (session_id, i, g)); + let hf = HostFunction::direct(move |ctx, args| { + let Some((i, generation)) = slot_info else { + return Err(ctx.error("local host function requires an active Session")); + }; + if ctx.vm.session_id != session_id { + return Err(ctx.error("session local host function called from wrong Session")); + } + let Some(func) = get_local_fn(session_id, i, generation) else { + return Err(ctx.error("session local host function is no longer alive")); + }; + func(ctx, args) + }) + .named(name); + Val(crate::host::wrap_direct_with_local(self.vm, hf, local_slot)) + } + + /// Calls a JS function value synchronously from inside a direct host function (re-entrant). + #[inline] + pub fn call_fn_val(&mut self, f: Val, this: Val, args: &[Val]) -> Result { + let mut cached = self.vm.native_proto.clone(); + self.vm + .call_direct(&f.0, this.0, args, &mut cached) + .map(|s| Val(s.get())) + .map_err(|e| Val(e.get())) + } + + fn alloc_pin(&mut self, v: Value) -> (u32, u32) { + let v = self.vm.sanitize_val(v); + // Write barrier: incremental GC has no atomic remark pass, so a white value newly stored + // into `HostRoots::pinned` while marking is in progress must be shaded immediately. + self.vm.gc_shade(v); + let roots = self.vm.host_roots_mut(); + if let Some(idx) = roots.pinned_free.pop() { + let slot = &mut roots.pinned[idx as usize]; + slot.value = Some(v); + (idx, slot.generation) + } else { + let idx = roots.pinned.len() as u32; + roots.pinned.push(crate::vm::PinSlot { + value: Some(v), + generation: 1, + }); + (idx, 1) + } + } + + fn free_pin(&mut self, idx: u32, generation: u32) { + if generation == 0 { + return; + } + let Some(roots) = self.vm.host_roots.as_deref_mut() else { + return; + }; + if let Some(slot) = roots.pinned.get_mut(idx as usize) + && slot.value.is_some() + && slot.generation == generation + { + slot.value = None; + slot.generation = next_generation(slot.generation); + roots.pinned_free.push(idx); + } + } + + /// Pins a callable guest value so it stays rooted across GC cycles and can be invoked via [`Session::call_fn`]. + pub fn pin_fn(&mut self, v: Val) -> Option { + let Value::Obj(id) = v.0 else { + return None; + }; + if !self.vm.live_obj(id).is_some_and(|o| o.is_callable()) { + return None; + } + let (idx, generation) = self.alloc_pin(v.0); + Some(FnHandle { + session_id: self.vm.session_id, + idx, + generation, + }) + } + + /// Reads the value of a pinned function handle, or `Val::UNDEFINED` if freed, stale, or from another session. + #[inline(always)] + pub fn get_fn(&self, handle: FnHandle) -> Val { + if handle.session_id != self.vm.session_id { + return Val::UNDEFINED; + } + Val(self.vm.get_pinned(handle.idx, handle.generation)) + } + + /// Releases a previously pinned function handle so the GC can reclaim it. + pub fn unpin_fn(&mut self, handle: FnHandle) { + if handle.session_id != self.vm.session_id { + return; + } + self.free_pin(handle.idx, handle.generation); + } + + /// Pins an arbitrary JS value so it stays rooted across GC cycles. + pub fn pin_val(&mut self, v: Val) -> ValHandle { + let (idx, generation) = self.alloc_pin(v.0); + ValHandle { + session_id: self.vm.session_id, + idx, + generation, + } + } + + /// Reads a previously pinned JS value, or `Val::UNDEFINED` if freed, stale, or from another session. + #[inline(always)] + pub fn get_val(&self, handle: ValHandle) -> Val { + if handle.session_id != self.vm.session_id { + return Val::UNDEFINED; + } + Val(self.vm.get_pinned(handle.idx, handle.generation)) + } + + /// Releases a previously pinned value handle so the GC can reclaim it. + pub fn unpin_val(&mut self, handle: ValHandle) { + if handle.session_id != self.vm.session_id { + return; + } + self.free_pin(handle.idx, handle.generation); + } + + /// Sets or updates a global variable in this live VM. + pub fn set_global(&mut self, name: &str, v: Val) { + let v = self.vm.sanitize_val(v.0); + // Write barrier: shade `v` if GC is mid-mark since globals were already scanned at cycle start. + self.vm.gc_shade(v); + let atom = self.intern_key(name).0; + self.vm.global_map.insert(atom, v); + for (i, &a) in self.vm.global_names.iter().enumerate() { + if a == atom { + self.vm.globals[i] = v; + } + } + } + + /// Looks up a global variable by name without interning or permanently rooting the key. + pub fn get_global(&self, name: &str) -> Option { + lookup_global(self.vm, name) + } + + /// Looks up a global variable by pre-interned [`Key`]. + #[inline] + pub fn get_global_by_key(&self, key: Key) -> Option { + lookup_global_by_key(self.vm, key) + } + + /// Creates a JS `TypeError` value suitable for returning as `Err(ctx.type_error(...))`. + #[cold] + pub fn type_error(&mut self, msg: &str) -> Val { + Val(self.vm.type_error(msg)) + } + + /// Creates a JS `Error` value suitable for returning as `Err(ctx.error(...))`. + #[cold] + pub fn error(&mut self, msg: &str) -> Val { + let proto = self.vm.realm.error_proto; + Val(self.vm.make_error(proto, msg)) + } + + /// Attaches typed per-session user data (accessible from both [`Session`] and [`HostCtx`]). + pub fn set_user_data(&mut self, val: T) { + store_set_user_data(self.vm.session_id, val); + } + + /// Reads typed per-session user data. + pub fn with_user_data(&self, f: impl FnOnce(&T) -> R) -> Option { + let cell = store_get_cell::(self.vm.session_id)?; + let borrow = cell.borrow(); + borrow.downcast_ref::().map(f) + } + + /// Mutates typed per-session user data. + pub fn with_user_data_mut(&self, f: impl FnOnce(&mut T) -> R) -> Option { + let cell = store_get_cell::(self.vm.session_id)?; + let mut borrow = cell.borrow_mut(); + borrow.downcast_mut::().map(f) + } + + /// Clones typed per-session user data (ideal for `Rc` state handles). + pub fn get_user_data(&self) -> Option { + self.with_user_data(Clone::clone) + } +} + +/// A persistent live VM instance initialized from a program, ready for repeated low-latency calls. +/// Thread-affine (`!Send + !Sync`) so per-session local host callbacks and user data are cleanly owned. +pub struct Session { + vm: Vm, + code: Arc, + cached_func: Arc, + _local: PhantomData<*const ()>, +} + +impl Drop for Session { + fn drop(&mut self) { + drop_session_store(self.vm.session_id); + } +} + +impl Session { + pub(crate) fn start( + rt: &Runtime, + code: Code<'_>, + options: &ProgramOptions, + ) -> Result> { + let mut running = run::start(rt, code, options)?; + let session_id = running.vm.session_id; + alloc_session_store(session_id); + let mut guard = SessionInitGuard::new(session_id); + let probe = 0u8; + running.vm.stack_base = &probe as *const u8 as usize; + running.vm.stack_budget = run::RUN_STACK_BUDGET; + running.vm.start = crate::time::Instant::now(); + if let Some(c) = running.vm.cpu.as_deref_mut() { + c.enter(); + } + running.vm.slice_restart(); + run::call_main(&mut running.vm); + let _ = running.vm.drive(); + if let Some(c) = running.vm.cpu.as_deref_mut() { + c.leave(false); + } + // Clear any init-time slice stretch so a Runtime `slice_ms` does not immediately trip on + // the first post-init `call_fn` outside `arm_slice`. + running.vm.slice = None; + if running.vm.fatal.is_some() + || matches!(running.vm.outcome, Some(Err(_))) + || running.vm.outcome.is_none() + { + return Err(Box::new(run::finish(*running))); + } + let exports = match running.vm.outcome.take() { + Some(Ok(v)) => v, + _ => unreachable!("checked above"), + }; + // Root exports on the VM outside `HostRoots::pinned` so user unpin calls can never unroot it. + running.vm.gc_shade(exports); + running.vm.host_roots_mut().session_exports = exports; + let cached_func = running.vm.native_proto.clone(); + guard.disarm(); + Ok(Session { + vm: running.vm, + code: running.code, + cached_func, + _local: PhantomData, + }) + } + + /// The value returned by the top-level program (e.g. an object of exported functions). + #[inline(always)] + pub fn exports(&self) -> Val { + Val(self + .vm + .host_roots + .as_deref() + .map_or(Value::Undef, |r| r.session_exports)) + } + + /// Looks up a named function on [`Session::exports`] (or global scope) and pins it for [`Session::call_fn`]. + pub fn export_fn(&mut self, name: &str) -> Option { + let exports = self.exports(); + if let Some(atom) = lookup_atom(&self.vm, name) + && let Some(v) = self.ctx().obj_get(exports, Key(atom)) + && let Some(h) = self.ctx().pin_fn(v) + { + return Some(h); + } + self.global_fn(name) + } + + /// Borrows the VM context for building/reading values and interning keys. + #[inline(always)] + pub fn ctx(&mut self) -> HostCtx<'_> { + HostCtx { vm: &mut self.vm } + } + + /// Pre-interns and permanently roots a property name for zero-allocation reads and writes. + #[inline] + pub fn key(&mut self, name: &str) -> Key { + self.ctx().key(name) + } + + /// Looks up a global variable by name without interning or permanently rooting the key. + pub fn global(&self, name: &str) -> Option { + lookup_global(&self.vm, name) + } + + /// Looks up a global variable by pre-interned [`Key`]. + #[inline] + pub fn global_by_key(&self, key: Key) -> Option { + lookup_global_by_key(&self.vm, key) + } + + /// Sets or updates a global variable in this live VM. + pub fn set_global(&mut self, name: &str, v: Val) { + self.ctx().set_global(name, v); + } + + /// Looks up a global function by name and pins it for repeated invocation via [`Session::call_fn`]. + pub fn global_fn(&mut self, name: &str) -> Option { + let v = self.global(name)?; + self.ctx().pin_fn(v) + } + + /// Arms a recoverable per-entry slice budget of `ms` milliseconds (on `Limits::clock`, e.g. `ThreadCpu`). + /// Call [`Session::disarm_slice`] when the entry finishes so idle time is not charged. + /// + /// Clears a prior recoverable [`DiagnosticKind::SliceExceeded`] fatal state, while preserving + /// non-recoverable fatals such as memory limits. + pub fn arm_slice(&mut self, ms: u64) { + if matches!(self.vm.fatal, Some((DiagnosticKind::SliceExceeded, _))) { + self.vm.fatal = None; + } + self.vm.limits.slice_ms = Some(ms); + if self.vm.cpu.is_none() && self.vm.limits.clock == crate::Clock::ThreadCpu { + self.vm.start_cpu_meter(); + } + if let Some(c) = self.vm.cpu.as_deref_mut() { + c.enter(); + } + self.vm.slice_restart(); + self.vm.rebudget(); + } + + /// Ends the current entry's CPU-time stretch and clears the active slice limit so calls outside + /// a timed entry do not measure against a stale slice. + pub fn disarm_slice(&mut self) { + self.vm.limits.slice_ms = None; + self.vm.slice = None; + if let Some(c) = self.vm.cpu.as_deref_mut() { + c.leave(false); + } + self.vm.rebudget(); + } + + /// Invokes a pinned guest function synchronously with zero heap allocations on the hot path. + #[inline] + pub fn call_fn(&mut self, f: FnHandle, args: &[Val]) -> Result { + self.call_fn_with_this(f, Val::UNDEFINED, args) + } + + /// Invokes a pinned guest function synchronously with an explicit `this` receiver. + #[inline] + pub fn call_fn_with_this( + &mut self, + f: FnHandle, + this: Val, + args: &[Val], + ) -> Result { + if f.session_id != self.vm.session_id { + return self.call_val(Val::UNDEFINED, this, args); + } + let func = self.vm.get_pinned(f.idx, f.generation); + self.call_val(Val(func), this, args) + } + + /// Invokes a callable JS value directly with an explicit `this` receiver. + #[inline] + pub fn call_val(&mut self, f: Val, this: Val, args: &[Val]) -> Result { + match self + .vm + .call_direct(&f.0, this.0, args, &mut self.cached_func) + { + Ok(slot) => { + if self.vm.fatal.is_some() { + Err(self.format_error(Value::Undef)) + } else { + Ok(Val(slot.get())) + } + } + Err(err) => Err(self.format_error(err.get())), + } + } + + /// Runs up to `max_jobs` queued Promise / microtask jobs without clearing remaining jobs when + /// the budget is reached. Returns `Ok(true)` if more jobs remain, or `Ok(false)` when drained. + /// Remaining jobs are cleared only on a fatal VM limit (such as slice timeout or OOM). + pub fn drain_jobs_budget(&mut self, max_jobs: usize) -> Result { + if self.vm.fatal.is_some() { + self.vm.jobs.clear(); + return Err(self.format_error(Value::Undef)); + } + let probe = 0u8; + if self.vm.native_depth == 0 { + self.vm.stack_base = &probe as *const u8 as usize; + self.vm.stack_budget = run::RUN_STACK_BUDGET; + } + let mut ran = 0usize; + while ran < max_jobs { + let Some(job) = self.vm.jobs.pop_front() else { + break; + }; + ran += 1; + if let Err(err) = self.vm.tick() { + if self.vm.fatal.is_some() { + self.vm.jobs.clear(); + } + return Err(self.format_error(err)); + } + if let Err(err) = self.vm.run_job(job) { + if self.vm.fatal.is_some() { + self.vm.jobs.clear(); + } + return Err(self.format_error(err)); + } + if self.vm.fatal.is_some() { + self.vm.jobs.clear(); + return Err(self.format_error(Value::Undef)); + } + if self.vm.suspended { + break; + } + } + Ok(!self.vm.jobs.is_empty()) + } + + /// Runs queued Promise / microtask jobs in this session without failing on externally pending Promises. + /// Runs up to 4096 jobs per call (returning `SliceExceeded` if jobs still remain without + /// destructively clearing the queue; only fatal errors clear remaining jobs). + pub fn drain_jobs(&mut self) -> Result<(), Diagnostic> { + let more = self.drain_jobs_budget(DEFAULT_DRAIN_JOBS_BUDGET)?; + if more && !self.vm.suspended { + return Err(Diagnostic { + kind: DiagnosticKind::SliceExceeded, + message: format!( + "Microtask queue exceeded {DEFAULT_DRAIN_JOBS_BUDGET} jobs in a single drain." + ) + .into(), + location: None, + suggestions: Vec::new(), + }); + } + Ok(()) + } + + /// Drains any unhandled Promise rejections recorded in this session, formatting each rejection + /// reason directly from heap state (never invoking arbitrary user JS `toString()` or + /// `[Symbol.toPrimitive]`) and clearing the VM's root list so rejected Promises do not accumulate. + pub fn take_unhandled_rejections(&mut self) -> Vec { + let drained = std::mem::take(&mut self.vm.host.unhandled); + if drained.is_empty() { + return Vec::new(); + } + let mut out = Vec::with_capacity(drained.len()); + let ctx = self.ctx(); + for (_, reason) in drained { + out.push(ctx.format_val_safe(reason)); + } + out + } + + /// Whether any Promise / microtask jobs are waiting to run. + #[inline(always)] + pub fn has_pending_jobs(&self) -> bool { + !self.vm.jobs.is_empty() + } + + /// Reachable heap bytes held by this session's VM. + pub fn memory_bytes(&self) -> usize { + crate::heap::measure(&self.vm) as usize + } + + /// Runs one bounded incremental GC step between UI frames. + pub fn gc_step(&mut self) { + self.vm.gc_step_once(); + } + + /// Runs a full garbage collection cycle and releases empty trailing heap chunks back to the OS. + pub fn collect_garbage(&mut self) { + self.vm.gc_collect_full(); + } + + /// The limits configured on this session. + pub fn limits(&self) -> &Limits { + &self.vm.limits + } + + /// Pins a callable value. + pub fn pin_fn(&mut self, v: Val) -> Option { + self.ctx().pin_fn(v) + } + + /// Reads a pinned function value, or `Val::UNDEFINED` if freed, stale, or from another session. + #[inline(always)] + pub fn get_fn(&self, handle: FnHandle) -> Val { + if handle.session_id != self.vm.session_id { + return Val::UNDEFINED; + } + Val(self.vm.get_pinned(handle.idx, handle.generation)) + } + + /// Releases a pinned function handle. + pub fn unpin_fn(&mut self, handle: FnHandle) { + self.ctx().unpin_fn(handle); + } + + /// Pins an arbitrary JS value. + pub fn pin_val(&mut self, v: Val) -> ValHandle { + self.ctx().pin_val(v) + } + + /// Reads a pinned JS value, or `Val::UNDEFINED` if freed, stale, or from another session. + #[inline(always)] + pub fn get_val(&self, handle: ValHandle) -> Val { + if handle.session_id != self.vm.session_id { + return Val::UNDEFINED; + } + Val(self.vm.get_pinned(handle.idx, handle.generation)) + } + + /// Releases a pinned value handle. + pub fn unpin_val(&mut self, handle: ValHandle) { + self.ctx().unpin_val(handle); + } + + /// Attaches typed per-session user data. + pub fn set_user_data(&mut self, val: T) { + store_set_user_data(self.vm.session_id, val); + } + + /// Reads typed per-session user data. + pub fn with_user_data(&self, f: impl FnOnce(&T) -> R) -> Option { + let cell = store_get_cell::(self.vm.session_id)?; + let borrow = cell.borrow(); + borrow.downcast_ref::().map(f) + } + + /// Mutates typed per-session user data. + pub fn with_user_data_mut(&self, f: impl FnOnce(&mut T) -> R) -> Option { + let cell = store_get_cell::(self.vm.session_id)?; + let mut borrow = cell.borrow_mut(); + borrow.downcast_mut::().map(f) + } + + /// Clones typed per-session user data. + pub fn get_user_data(&self) -> Option { + self.with_user_data(Clone::clone) + } + + #[cold] + #[inline(never)] + fn format_error(&mut self, err: Value) -> Diagnostic { + if let Some((kind, msg)) = self.vm.fatal.take() { + return Diagnostic { + kind, + message: msg.into(), + location: None, + suggestions: Vec::new(), + }; + } + let message = self.ctx().format_val_safe(err); + let (kind, location, suggestions) = if let Value::Obj(id) = err + && let Some(obj) = self.vm.live_obj(id) + && let Kind::Error(Some(f)) = &obj.kind + { + ( + f.kind.clone(), + f.offset.map(|o| run::line_col(&self.code, o)), + self.vm + .host + .suggestions + .get(&id) + .cloned() + .unwrap_or_default(), + ) + } else { + (DiagnosticKind::ExecutionFailure, None, Vec::new()) + }; + Diagnostic { + kind, + message: message.into(), + location, + suggestions, + } + } +} diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index 1b572db5..8812edf3 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -555,20 +555,23 @@ impl Enc<'_> { } let functions: Vec = h.functions[base.functions.min(h.functions.len())..] .iter() - .map(|f| { - let (name, length, own) = match &f.f { - Callee::Fn(hf) => (hf.name(), hf.length, hf.own_name), - Callee::Durable(_) => ("", 0, false), - }; - json!([ - f.label, - f.path.as_deref().map(texts), - f.owner, - f.installed, - name, - length, - own - ]) + .map(|slot| match slot { + Some(f) => { + let (name, length, own) = match &f.f { + Callee::Fn(hf) => (hf.name(), hf.length, hf.own_name), + Callee::Durable(_) => ("", 0, false), + }; + json!([ + f.label, + f.path.as_deref().map(texts), + f.owner, + f.installed, + name, + length, + own + ]) + } + None => J::Null, }) .collect(); let mut suggestions: Vec<(&Id, &Vec)> = h.suggestions.iter().collect(); @@ -2657,8 +2660,16 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { }); } vm.host.functions.truncate(base.functions); + vm.host + .free_functions + .retain(|&idx| (idx as usize) < base.functions); for (i, f) in field_list(j, "functions")?.iter().enumerate() { let index = base.functions + i; + if f.is_null() { + vm.host.functions.push(None); + vm.host.free_functions.push(index as u32); + continue; + } let label = string(at(f, 0)?)?; let path = opt_path(at(f, 1)?)?; let owner = opt_string(at(f, 2)?)?; @@ -2672,13 +2683,31 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { Some(path) => vm.host.resolve(path), None => from_root.map(Callee::Fn), }; - vm.host.functions.push(FnEntry { + vm.host.functions.push(Some(FnEntry { f: found.unwrap_or_else(|| Callee::Fn(host::lost_function(&name))), label, path, owner, installed, - }); + reclaimable: false, + local_slot: None, + })); + } + for o in vm.heap.iter() { + if let Kind::Native { f, data, .. } = &o.kind + && std::ptr::fn_addr_eq(*f, crate::host::host_native as crate::vm::NativeFn) + { + let valid = matches!( + data, + Value::Num(n) + if *n >= 0.0 + && n.fract() == 0.0 + && vm.host.functions.get(*n as usize).is_some_and(Option::is_some) + ); + if !valid { + return Err(invalid("a host function slot is missing.")); + } + } } vm.host.suggestions.clear(); for s in field_list(j, "suggestions")? { diff --git a/rust/crates/psychoscript/src/strings.rs b/rust/crates/psychoscript/src/strings.rs index 518e32e3..795f1837 100644 --- a/rust/crates/psychoscript/src/strings.rs +++ b/rust/crates/psychoscript/src/strings.rs @@ -701,6 +701,34 @@ impl Strings { self.get(self.atom_str[a as usize]) } + /// Bounds- and liveness-checked string lookup returning `None` for out-of-range, freed, or + /// unswept dead (`WHITE` during `Phase::Sweep`) string ids. + #[inline] + pub(crate) fn get_opt(&self, id: StrId) -> Option<&str> { + let idx = id as usize; + let b = self.bufs.get(idx)?; + if !self.gc.is_live(idx) { + return None; + } + if b.grow == NO_GROW { + return Some(&b.s); + } + let off = b.aux as usize; + self.grow + .get(b.grow as usize)? + .get(off..off + b.len as usize) + } + + /// Bounds-checked atom lookup returning `None` for invalid or freed (`NO_ATOM`) atoms. + #[inline] + pub(crate) fn text_opt(&self, a: Atom) -> Option<&str> { + let &sid = self.atom_str.get(a as usize)?; + if sid == NO_ATOM { + return None; + } + self.get_opt(sid) + } + /// The array index an atom names, if it is canonical. #[inline] pub fn index(&self, a: Atom) -> Option { diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 8781cc9a..80e07c52 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -5,14 +5,14 @@ use std::collections::VecDeque; use std::sync::Arc; use std::time::Duration; -use rustc_hash::FxHashMap; +use rustc_hash::{FxHashMap, FxHashSet}; use crate::accessors::Read; use crate::bytecode::{Arith, Capture, FuncProto, Op, Program, TemplateSite}; use crate::compiler::{DELEGATE_ASYNC, DELEGATE_NO_ARG}; use crate::conversion::code; use crate::object::*; -use crate::strings::{StrId, Strings}; +use crate::strings::{Atom, StrId, Strings}; use crate::value::{Id, Slot, Value}; use crate::{DiagnosticKind, Limits}; @@ -25,7 +25,7 @@ pub type NativeFn = fn(&mut Vm, Value, &[Value], Id) -> Res; pub const MAX_DEPTH: usize = 10_000; pub(crate) const MAX_OBJECTS: usize = 2_000_000; pub(crate) const MAX_STRINGS: usize = 4_000_000; -const MAX_NATIVE_DEPTH: usize = 400; +pub(crate) const MAX_NATIVE_DEPTH: usize = 400; pub(crate) const FUEL: i32 = 20_000; /// The reference's fuel: it starts the host calls a program queued whenever this runs out, so streaming responses /// count it the same way. A loop back-edge, a function call or a job costs one, a call of a native function fifty. @@ -282,7 +282,7 @@ pub struct Vm { /// A host call waiting for promises in its arguments parks its frames (see `park_frames`) with this coroutine. pub(crate) park: bool, pub(crate) park_coroutine: u32, - native_depth: usize, + pub(crate) native_depth: usize, /// Address near the bottom of the native stack this run started on, and how much of it calls may use. pub stack_base: usize, pub stack_budget: usize, @@ -366,6 +366,36 @@ pub struct Vm { pub(crate) slice: Option>, /// What `console.count`, `group` and `time` remember, once one is called. Saved with the run. pub(crate) console: Option>, + /// Lazily boxed host/session GC roots (pinned handles, rooted host atoms, session exports), + /// keeping `Vm` compact and `Vm::stack` near the top of the struct. + pub(crate) host_roots: Option>, + /// Unique non-zero VM instance id used to scope pinned handles and per-`Session` TLS state. + pub(crate) session_id: u64, + /// Explicitly `true` ONLY while executing a top-level `Session::call_val` JS frame with no + /// unrooted Rust locals on the call stack, permitting back-edge `gc_point()` steps. + pub(crate) session_gc_safe: bool, +} + +/// Host- and session-owned GC roots boxed out of `Vm` so standalone runs pay zero overhead. +#[derive(Default)] +pub(crate) struct HostRoots { + /// Guest values pinned by an embedder (`Session` / `HostCtx::pin_fn` / `HostCtx::pin_val`). + pub(crate) pinned: Vec, + /// Free slot indices in `pinned` available for reuse. + pub(crate) pinned_free: Vec, + /// Property key atoms interned by the host (`HostCtx::key` / `Session::key`), traced as permanent GC roots. + pub(crate) host_atoms: Vec, + /// Deduplication set for `host_atoms`. + pub(crate) host_atom_set: FxHashSet, + /// Top-level export value kept rooted for a persistent `Session` (separate from user `pinned` slots). + pub(crate) session_exports: Value, +} + +/// One generation-tagged slot in `HostRoots::pinned`, preventing ABA reuse bugs and `undefined` pin leaks. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PinSlot { + pub(crate) value: Option, + pub(crate) generation: u32, } impl Vm { @@ -513,6 +543,9 @@ impl Vm { cpu: None, slice: None, console: None, + host_roots: None, + session_id: crate::session::next_session_id(), + session_gc_safe: false, } } @@ -823,7 +856,7 @@ impl Vm { /// A back-edge, a function call or a job. #[inline] - fn tick(&mut self) -> Result<(), Value> { + pub(crate) fn tick(&mut self) -> Result<(), Value> { self.budget -= 1; if self.budget <= 0 { return self.budget_out(true); @@ -891,7 +924,7 @@ impl Vm { self.host.meter.start = self.budget; } - fn rebudget(&mut self) { + pub(crate) fn rebudget(&mut self) { let b = self.host.meter.handover.min(self.host.meter.fuel).max(1); self.budget = b; self.host.meter.start = b; @@ -968,6 +1001,8 @@ impl Vm { if self.native_depth >= MAX_NATIVE_DEPTH { return Err(self.range_error("Maximum call stack size exceeded")); } + let prev_gc_safe = self.session_gc_safe; + self.session_gc_safe = false; self.native_depth += 1; self.host.meter.counted = true; self.reads.fault = None; @@ -976,9 +1011,11 @@ impl Vm { if self.entered { let r = self.drive_entered(true); self.native_depth -= 1; + self.session_gc_safe = prev_gc_safe; return r; } self.native_depth -= 1; + self.session_gc_safe = prev_gc_safe; let r = r?; self.native_spent(); return Ok(r); @@ -1326,6 +1363,165 @@ impl Vm { } } + /// Lazily allocates and returns mutable access to the VM's boxed host/session GC roots. + #[inline] + pub(crate) fn host_roots_mut(&mut self) -> &mut HostRoots { + self.host_roots.get_or_insert_with(Box::default) + } + + /// Reads a generation-checked pinned value, or `Value::Undef` if freed or stale. + #[inline(always)] + pub(crate) fn get_pinned(&self, idx: u32, generation: u32) -> Value { + self.host_roots + .as_deref() + .and_then(|r| r.pinned.get(idx as usize)) + .filter(|slot| slot.generation == generation) + .and_then(|slot| slot.value) + .unwrap_or(Value::Undef) + } + + /// Validates that a host-supplied `Value` still points to a live heap object, string, or BigInt, + /// returning `Value::Undef` for stale or `Uninit` values so post-GC writes cannot poison the VM. + #[inline] + pub(crate) fn sanitize_val(&self, v: Value) -> Value { + match v { + Value::Obj(id) => { + if self.is_live_obj(id) { + v + } else { + Value::Undef + } + } + Value::Str(id) => { + if self.atoms.get_opt(id).is_some() { + v + } else { + Value::Undef + } + } + Value::Big(id) if crate::builtins::bigint::on_heap(id) => { + if self.is_live_obj(id) { + v + } else { + Value::Undef + } + } + Value::Uninit => Value::Undef, + _ => v, + } + } + + /// Calls a guest function synchronously from a [`Session`](crate::Session) without copying `args` or cloning `func`. + #[inline] + pub(crate) fn call_direct( + &mut self, + f: &Value, + this: Value, + args: &[crate::session::Val], + cached: &mut Arc, + ) -> Result { + if self.fatal.is_some() { + return Err(Slot::UNDEF); + } + let f = self.sanitize_val(*f); + let this = self.sanitize_val(this); + // Write barrier: if incremental GC is mid-mark, shade the callee, receiver, and arguments + // before pushing them onto the VM stack so an unrooted WHITE Val cannot be stored into an + // already-BLACK container and swept. + if self.gc_is_marking() { + self.gc_shade(f); + self.gc_shade(this); + for arg in args { + let v = self.sanitize_val(arg.0); + self.gc_shade(v); + } + } + let probe = 0u8; + if self.native_depth == 0 { + self.stack_base = &probe as *const u8 as usize; + self.stack_budget = crate::run::RUN_STACK_BUDGET; + } + if let Value::Obj(id) = f + && let Some(obj) = self.live_obj(id) + && matches!(obj.kind, Kind::Closure(_)) + && self.native_depth < MAX_NATIVE_DEPTH + && self.stack_base.abs_diff(&probe as *const u8 as usize) <= self.stack_budget + { + let fpos = self.stack.len(); + self.push(f); + self.push(this); + for arg in args { + let v = self.sanitize_val(arg.0); + self.stack.push(Slot::pack(v)); + } + self.push_simple_or_full(id, fpos, args.len(), true) + .map_err(Slot::pack)?; + let prev_gc_safe = self.session_gc_safe; + self.session_gc_safe = self.run_depth == 0 && self.native_depth == 0; + self.native_depth += 1; + let r = self.run_callback_with(cached); + self.native_depth -= 1; + self.session_gc_safe = prev_gc_safe; + return match r { + Ok(Exit::Return(v)) | Ok(Exit::Yield(v)) => Ok(v), + Ok(Exit::Suspend) => Ok(Slot::UNDEF), + Err(e) => Err(Slot::pack(e)), + }; + } + let raw: Vec = args.iter().map(|v| self.sanitize_val(v.0)).collect(); + self.call_slow(&f, this, &raw) + .map(Slot::pack) + .map_err(Slot::pack) + } + + /// Fast inline closure frame push for plain sync non-class closures with a spare frame and budget left. + #[inline(always)] + fn push_simple_or_full( + &mut self, + id: Id, + fpos: usize, + argc: usize, + is_base: bool, + ) -> Result<(), Value> { + if self.budget > 1 + && self.frames.len() <= MAX_DEPTH + && let Kind::Closure(c) = &self.heap[id as usize].kind + && c.proto.class == 0 + && !c.proto.is_async + && !c.proto.is_generator + && !c.proto.needs_extra + && argc <= c.proto.nparams as usize + && let Some(mut spare) = self.spare_frames.pop() + { + self.budget -= 1; + if c.proto.is_arrow { + self.stack[fpos + 1] = Slot::pack(c.this); + } + let base = fpos + 2; + let nlocals = c.proto.nlocals as usize; + if nlocals > argc { + self.stack.resize(base + nlocals, Slot::UNDEF); + } + if !Arc::ptr_eq(&spare.func, &c.proto) { + spare.func = c.proto.clone(); + } + if !Arc::ptr_eq(&spare.upvals, &c.upvals) { + spare.upvals = c.upvals.clone(); + } + spare.pc = 0; + spare.base = base; + spare.hbase = self.handlers.len() as u32; + spare.extra = Box::default(); + spare.argc = argc as u32; + spare.kind = FrameKind::Normal; + spare.is_base = is_base; + spare.yield_pc = NO_YIELD; + self.push_frame(spare); + return Ok(()); + } + self.push_closure_frame(id, fpos, argc, is_base) + } + /// `call` with each outcome packed in one word, so it comes back in registers: a two-word `Value` returned /// through memory stalls the caller's reload on store forwarding, measurably on short callbacks. #[inline(never)] @@ -1364,6 +1560,14 @@ impl Vm { } fn call_slow(&mut self, f: &Value, this: Value, args: &[Value]) -> Res { + let prev_gc_safe = self.session_gc_safe; + self.session_gc_safe = false; + let r = self.call_slow_inner(f, this, args); + self.session_gc_safe = prev_gc_safe; + r + } + + fn call_slow_inner(&mut self, f: &Value, this: Value, args: &[Value]) -> Res { if self.stack_spent() { return Err(self.range_error("Maximum call stack size exceeded")); } @@ -1371,7 +1575,10 @@ impl Vm { return Err(self.type_error("The called value is not a function.")); }; let id = *id; - match &self.heap[id as usize].kind { + let Some(obj) = self.live_obj(id) else { + return Err(self.type_error("The called value is not a function.")); + }; + match &obj.kind { Kind::Closure(_) => { if self.native_depth >= MAX_NATIVE_DEPTH { return Err(self.range_error("Maximum call stack size exceeded")); @@ -1626,7 +1833,10 @@ impl Vm { self.stack.truncate(fpos); return Err(self.range_error("Maximum call stack size exceeded")); } - self.tick()?; + if let Err(err) = self.tick() { + self.stack.truncate(fpos); + return Err(err); + } let Kind::Closure(c) = &self.heap[id as usize].kind else { return Ok(()); }; @@ -1711,8 +1921,62 @@ impl Vm { self.push_closure_frame(id, fpos, argc, false)?; Ok(true) } - Kind::Native { f, .. } => { + Kind::Native { f, data, .. } => { let f = *f; + if std::ptr::fn_addr_eq(f, crate::host::host_native as NativeFn) + && let Value::Num(index) = *data + && let Some(Some(entry)) = self.host.functions.get(index as usize) + && let crate::host::Callee::Fn(hf) = &entry.f + && let crate::host_function::Body::Direct(d) = &hf.body + { + if self.native_depth >= MAX_NATIVE_DEPTH || self.stack_spent() { + self.stack.truncate(fpos); + return Err(self.range_error("Maximum call stack size exceeded")); + } + let d = d.clone(); + let this = self.stack[fpos + 1].get(); + let prev_gc_safe = self.session_gc_safe; + self.session_gc_safe = false; + let r = if argc <= 8 { + let mut stack_args = [Value::Undef; 8]; + for (dst, slot) in stack_args.iter_mut().zip(&self.stack[fpos + 2..]) { + *dst = slot.get(); + } + self.stack.truncate(fpos); + self.native_depth += 1; + let mut ctx = crate::session::HostCtx::new(self); + let r = d( + &mut ctx, + crate::session::DirectArgs::with_this(this, &stack_args[..argc]), + ); + self.native_depth -= 1; + r + } else { + let mut args = self.arg_pool.pop().unwrap_or_default(); + args.extend(self.stack.drain(fpos + 2..).map(Slot::get)); + self.stack.truncate(fpos); + self.native_depth += 1; + let mut ctx = crate::session::HostCtx::new(self); + let r = d(&mut ctx, crate::session::DirectArgs::with_this(this, &args)); + self.native_depth -= 1; + args.clear(); + self.arg_pool.push(args); + r + }; + self.session_gc_safe = prev_gc_safe; + if self.fatal.is_some() { + return Err(Value::Undef); + } + match r { + Ok(v) => { + let v = self.sanitize_val(v.0); + self.push(v); + self.native_spent(); + return Ok(false); + } + Err(e) => return Err(self.sanitize_val(e.0)), + } + } if id == self.realm.generator_next && let Some(g) = self.suspended_generator(self.stack[fpos + 1]) { @@ -2314,23 +2578,30 @@ impl Vm { self.handlers.truncate(frame.hbase as usize); self.stack.truncate(frame.base - 2); match frame.kind { - FrameKind::Async(c) if !fatal => { - let result = match self.coroutines[c as usize].promise { - Some(p) => { - self.free_coroutine(c); - self.reject(p, e); - Value::Obj(p) + FrameKind::Async(c) => { + if fatal { + self.free_coroutine(c); + if frame.is_base { + return Err(Err(e)); } - None => { - self.outcome = Some(Err(e)); - Value::Undef + } else { + let result = match self.coroutines[c as usize].promise { + Some(p) => { + self.free_coroutine(c); + self.reject(p, e); + Value::Obj(p) + } + None => { + self.outcome = Some(Err(e)); + Value::Undef + } + }; + if frame.is_base { + return Err(Ok(Exit::Return(Slot::pack(result)))); } - }; - if frame.is_base { - return Err(Ok(Exit::Return(Slot::pack(result)))); + self.push(result); + return Ok(()); } - self.push(result); - return Ok(()); } FrameKind::Generator(g, _) => { self.leave_generator(g, None); @@ -3136,6 +3407,17 @@ impl Vm { r } + #[inline(always)] + fn run_callback_with(&mut self, cached: &mut Arc) -> Result { + if self.resumable_run { + return self.run(); + } + self.run_depth += 1; + let r = self.run_frames_with(false, cached); + self.run_depth -= 1; + r + } + /// Continues frames a suspend left on the job stack, as the entry point that started them would have. pub fn continue_frames(&mut self) -> Result<(), Value> { if self.frames.is_empty() { @@ -3149,6 +3431,15 @@ impl Vm { /// The dispatch loop. `resumable` lets a suspend stop it at a back-edge, leaving its frames for later. fn run_frames(&mut self, resumable: bool) -> Result { + let mut cached = self.frames.last().expect("frame").func.clone(); + self.run_frames_with(resumable, &mut cached) + } + + fn run_frames_with( + &mut self, + resumable: bool, + func: &mut Arc, + ) -> Result { 'outer: loop { let fi = self.frames.len() - 1; if let FrameKind::Native(op, sub) = self.frames[fi].kind { @@ -3166,7 +3457,9 @@ impl Vm { } } } - let func = self.frames[fi].func.clone(); + if !Arc::ptr_eq(func, &self.frames[fi].func) { + *func = self.frames[fi].func.clone(); + } let code: &[Op] = &func.code; let base = self.frames[fi].base; let mut pc = self.frames[fi].pc; @@ -4177,10 +4470,19 @@ impl Vm { Op::Jump(t) => { if (t as usize) < pc { tri!(self.tick()); - if self.suspend_wanted && resumable && !self.gc_point() { - self.frames[fi].pc = t as usize; - self.suspended = true; - return Ok(Exit::Suspend); + if self.suspend_wanted { + if resumable { + if !self.gc_point() { + self.frames[fi].pc = t as usize; + self.suspended = true; + return Ok(Exit::Suspend); + } + } else if self.session_gc_safe + && self.run_depth == 1 + && self.gc.owns_suspend() + { + self.gc_point(); + } } } pc = t as usize; @@ -4228,10 +4530,19 @@ impl Vm { if self.truthy(&v) { if (t as usize) < pc { tri!(self.tick()); - if self.suspend_wanted && resumable && !self.gc_point() { - self.frames[fi].pc = t as usize; - self.suspended = true; - return Ok(Exit::Suspend); + if self.suspend_wanted { + if resumable { + if !self.gc_point() { + self.frames[fi].pc = t as usize; + self.suspended = true; + return Ok(Exit::Suspend); + } + } else if self.session_gc_safe + && self.run_depth == 1 + && self.gc.owns_suspend() + { + self.gc_point(); + } } } pc = t as usize; diff --git a/rust/crates/psychoscript/tests/session.rs b/rust/crates/psychoscript/tests/session.rs new file mode 100644 index 00000000..e9f177d6 --- /dev/null +++ b/rust/crates/psychoscript/tests/session.rs @@ -0,0 +1,1509 @@ +use std::cell::Cell; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use psychoscript::{ + Clock, DiagnosticKind, HostFunction, HostValue, Limits, Namespace, ProgramOptions, Resolved, + Runtime, Session, Val, +}; + +#[test] +fn session_calls_stateful_exports_and_direct_host_functions_with_this() { + let log = Arc::new(Mutex::new(Vec::::new())); + let rt = Runtime::make().globals({ + let log = log.clone(); + move |_| { + let log = log.clone(); + vec![ + ( + "record", + HostValue::Function(HostFunction::direct(move |ctx, args| { + let msg = ctx.as_str(args.get(0)).unwrap_or(""); + let n = args.get(1).as_f64().unwrap_or(0.0); + log.lock().unwrap().push(format!("{msg}:{n}")); + Ok(Val::num(n * 2.0)) + })), + ), + ( + "sumArray", + HostValue::Function(HostFunction::direct(|ctx, args| { + let mut sum = 0.0; + ctx.array_for_each(args.get(0), |v| { + if let Some(x) = v.as_f64() { + sum += x; + } + }); + Ok(Val::num(sum)) + })), + ), + ( + "readThisAndMany", + HostValue::Function(HostFunction::direct(|ctx, args| { + let k_tag = ctx.key("tag"); + let tag = ctx.obj_get_str(args.this(), k_tag).unwrap_or("none"); + let mut sum = 0.0; + for i in 0..args.len() { + sum += args.get(i).as_f64().unwrap_or(0.0); + } + Ok(ctx.new_str(&format!("{tag}:{sum}"))) + })), + ), + ] + } + }); + + let mut sess = rt + .session_with( + r#" + let count = 0; + function click(delta) { + count += delta; + return count; + } + function render(label) { + const doubled = record(label, count); + return sumArray([doubled, 10, 20]); + } + function callMethod() { + const host = { tag: "btn", fn: readThisAndMany }; + // 10 args exercises >8 args direct dispatch path too. + return host.fn(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + function readReceiver() { + return this.value; + } + function triple(x) { + return x * 3; + } + return { click, render, callMethod, readReceiver, triple }; + "#, + &ProgramOptions::default(), + ) + .expect("session init"); + + let exports = sess.exports(); + assert!(sess.ctx().is_plain_object(exports)); + let click = sess.export_fn("click").expect("click export"); + let render = sess.export_fn("render").expect("render export"); + let call_method = sess.export_fn("callMethod").expect("callMethod export"); + let read_receiver = sess.export_fn("readReceiver").expect("readReceiver export"); + let k_triple = sess.key("triple"); + let triple_val = sess.ctx().obj_get(exports, k_triple).expect("triple val"); + sess.set_global("globalMultiplier", triple_val); + let global_mul = sess.global_fn("globalMultiplier").expect("global fn"); + + assert_eq!( + sess.call_fn(click, &[Val::num(3.0)]).unwrap().as_f64(), + Some(3.0) + ); + assert_eq!( + sess.call_fn(click, &[Val::num(4.0)]).unwrap().as_f64(), + Some(7.0) + ); + + let label = sess.ctx().new_str("panel"); + let out = sess.call_fn(render, &[label]).unwrap(); + assert_eq!(out.as_f64(), Some(44.0)); + assert_eq!(*log.lock().unwrap(), vec!["panel:7".to_owned()]); + + let method_out = sess.call_fn(call_method, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(method_out), Some("btn:55")); + + let receiver = { + let mut ctx = sess.ctx(); + let k_val = ctx.key("value"); + ctx.new_object_with(&[(k_val, Val::num(99.0))]) + }; + assert_eq!( + sess.call_fn_with_this(read_receiver, receiver, &[]) + .unwrap() + .as_f64(), + Some(99.0) + ); + assert_eq!( + sess.call_fn(global_mul, &[Val::num(6.0)]).unwrap().as_f64(), + Some(18.0) + ); + let global_fn_val = sess.global("globalMultiplier").expect("global val"); + assert_eq!( + sess.call_val(global_fn_val, Val::UNDEFINED, &[Val::num(5.0)]) + .unwrap() + .as_f64(), + Some(15.0) + ); +} + +#[test] +fn direct_host_function_inside_namespace_works_without_panicking() { + let rt = Runtime::make().globals(|_| { + vec![( + "api", + HostValue::Namespace(Namespace::new( + |_| Ok(Vec::new()), + |path| { + let name = path.last().and_then(|s| s.as_str()).unwrap_or(""); + match name { + "add" => Resolved::Function(HostFunction::direct(|_ctx, args| { + let a = args.get(0).as_f64().unwrap_or(0.0); + let b = args.get(1).as_f64().unwrap_or(0.0); + Ok(Val::num(a + b)) + })), + "fail" => Resolved::Function(HostFunction::direct(|ctx, _| { + Err(ctx.type_error("ns boom")) + })), + _ => Resolved::Function(HostFunction::direct(|_ctx, _| Ok(Val::UNDEFINED))), + } + }, + )), + )] + }); + + let mut sess = rt + .session( + r#" + function run() { + const sum = api.math.add(19, 23); + let msg = ""; + try { + api.fail(); + } catch (e) { + msg = e.message; + } + return sum + ":" + msg; + } + return { run }; + "#, + ) + .expect("session init"); + + let run = sess.export_fn("run").unwrap(); + let out = sess.call_fn(run, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(out), Some("42:ns boom")); +} + +#[test] +fn pinned_callbacks_and_objects_survive_full_gc() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + let total = 0; + function makeHandler(step) { + return (x) => { + total += x * step; + return total; + }; + } + function churn() { + let acc = 0; + for (let i = 0; i < 5000; i++) { + const o = { a: i, b: "item-" + i }; + acc += o.a; + } + return acc; + } + return { makeHandler, churn }; + "#, + ) + .expect("session init"); + + let make_handler = sess.export_fn("makeHandler").unwrap(); + let churn = sess.export_fn("churn").unwrap(); + let cb_val = sess.call_fn(make_handler, &[Val::num(10.0)]).unwrap(); + let cb = sess.pin_fn(cb_val).expect("pin closure"); + + assert_eq!( + sess.call_fn(cb, &[Val::num(2.0)]).unwrap().as_f64(), + Some(20.0) + ); + let _ = sess.call_fn(churn, &[]).unwrap(); + sess.collect_garbage(); + assert_eq!( + sess.call_fn(cb, &[Val::num(5.0)]).unwrap().as_f64(), + Some(70.0) + ); +} + +#[test] +fn gc_write_barrier_protects_white_objects_pinned_or_globalized_mid_mark() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function makeEphemeral(tag) { + return { tag, nested: { payload: "alive-" + tag, n: 42 } }; + } + function allocatePressure() { + const keep = []; + for (let i = 0; i < 6000; i++) { + keep.push({ i, text: "fill-" + i }); + } + return keep.length; + } + function readGlobalPayload() { + return midMarkGlobal.nested.payload; + } + return { makeEphemeral, allocatePressure, readGlobalPayload }; + "#, + ) + .expect("session init"); + + let make_ephemeral = sess.export_fn("makeEphemeral").unwrap(); + let allocate_pressure = sess.export_fn("allocatePressure").unwrap(); + let read_global_payload = sess.export_fn("readGlobalPayload").unwrap(); + + // Ensure GC starts cleanly from Phase::Idle. + sess.collect_garbage(); + + // Create two unrooted objects while GC is idle (both start WHITE on next mark cycle). + let tag_a = sess.ctx().new_str("pin"); + let tag_b = sess.ctx().new_str("global"); + let white_for_pin = sess.call_fn(make_ephemeral, &[tag_a]).unwrap(); + let white_for_global = sess.call_fn(make_ephemeral, &[tag_b]).unwrap(); + + // Allocate >64K slots directly from Rust so heap crosses gc.trigger while still in Phase::Idle, + // then run a single gc_step() to transition deterministically into Phase::Mark while both + // unrooted objects are WHITE. + { + let mut ctx = sess.ctx(); + for _ in 0..75_000 { + let _ = ctx.new_object(0); + } + } + sess.gc_step(); + + // Root both WHITE objects mid-mark via pin_val and set_global. + let pinned_handle = sess.pin_val(white_for_pin); + sess.set_global("midMarkGlobal", white_for_global); + + // Finish the mark/sweep cycle and allocate over any freed slots. + sess.collect_garbage(); + let _ = sess.call_fn(allocate_pressure, &[]).unwrap(); + sess.collect_garbage(); + + let k_nested = sess.key("nested"); + let k_payload = sess.key("payload"); + let k_n = sess.key("n"); + + { + let ctx = sess.ctx(); + let val = ctx.get_val(pinned_handle); + let nested = ctx.obj_get(val, k_nested).expect("nested survived GC"); + assert_eq!(ctx.obj_get_str(nested, k_payload), Some("alive-pin")); + assert_eq!(ctx.obj_get_f64(nested, k_n), Some(42.0)); + } + + let global_payload = sess.call_fn(read_global_payload, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(global_payload), Some("alive-global")); +} + +#[test] +fn call_direct_mid_mark_write_barrier_protects_white_argument_stored_in_black_container() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + let blackBox = null; + function makeEphemeral() { + return { inner: { secret: "survived-call-direct" } }; + } + function allocBlackAndStore(v) { + // Allocated during Phase::Mark => immediately BLACK; storing v into it relies on + // call_direct having shaded v on entry! + blackBox = { held: v }; + } + function readSecret() { + return blackBox.held.inner.secret; + } + return { makeEphemeral, allocBlackAndStore, readSecret }; + "#, + ) + .expect("session init"); + + let make_ephemeral = sess.export_fn("makeEphemeral").unwrap(); + let alloc_and_store = sess.export_fn("allocBlackAndStore").unwrap(); + let read_secret = sess.export_fn("readSecret").unwrap(); + + sess.collect_garbage(); + let white_arg = sess.call_fn(make_ephemeral, &[]).unwrap(); + + // Enter Phase::Mark while white_arg is unrooted (WHITE). + { + let mut ctx = sess.ctx(); + for _ in 0..75_000 { + let _ = ctx.new_object(0); + } + } + sess.gc_step(); + + // Pass WHITE arg into JS via call_fn; JS stores it into a freshly allocated BLACK object. + let _ = sess.call_fn(alloc_and_store, &[white_arg]).unwrap(); + + // Sweep and churn heap. + sess.collect_garbage(); + { + let mut ctx = sess.ctx(); + for _ in 0..5_000 { + let _ = ctx.new_object(0); + } + } + sess.collect_garbage(); + + let out = sess.call_fn(read_secret, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(out), Some("survived-call-direct")); +} + +#[test] +fn exports_stay_rooted_independently_of_user_pin_slot_zero() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + return { + ping() { return "still-alive"; }, + }; + "#, + ) + .expect("session init"); + + // First user pin takes pinned slot 0; unpinning it must never affect Session::exports. + let first_pin = sess.pin_val(Val::num(123.0)); + assert_eq!(first_pin.raw() as u32, 0); + sess.unpin_val(first_pin); + sess.collect_garbage(); + { + let mut ctx = sess.ctx(); + for _ in 0..5_000 { + let _ = ctx.new_object(0); + } + } + sess.collect_garbage(); + + let ping = sess.export_fn("ping").expect("exports still rooted"); + let out = sess.call_fn(ping, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(out), Some("still-alive")); +} + +#[test] +fn pin_handles_reject_aba_reuse_and_reuse_undefined_slots() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function fnA() { return 1; } + function fnB() { return 2; } + return { fnA, fnB }; + "#, + ) + .expect("session init"); + + let k_fn_a = sess.key("fnA"); + let k_fn_b = sess.key("fnB"); + let exports = sess.exports(); + let fn_a_val = sess.ctx().obj_get(exports, k_fn_a).unwrap(); + let fn_b_val = sess.ctx().obj_get(exports, k_fn_b).unwrap(); + + let h_a = sess.pin_fn(fn_a_val).unwrap(); + let slot_a = h_a.raw() as u32; + let gen_a = (h_a.raw() >> 32) as u32; + assert_eq!(gen_a, 1); + sess.unpin_fn(h_a); + + // Next pin must reuse the same slot with an incremented generation. + let h_b = sess.pin_fn(fn_b_val).unwrap(); + let slot_b = h_b.raw() as u32; + let gen_b = (h_b.raw() >> 32) as u32; + assert_eq!(slot_a, slot_b); + assert_eq!(gen_b, gen_a + 1); + + // Stale handle h_a must read as undefined and fail to call (never invoking fnB!). + assert!(sess.get_fn(h_a).is_undefined()); + assert!(sess.call_fn(h_a, &[]).is_err()); + + // Unpinning stale h_a must NOT free h_b. + sess.unpin_fn(h_a); + assert_eq!(sess.call_fn(h_b, &[]).unwrap().as_f64(), Some(2.0)); + + // Pinning and unpinning Val::UNDEFINED repeatedly must reuse the same slot without leaking. + let first_undef = sess.pin_val(Val::UNDEFINED); + let first_idx = first_undef.raw() as u32; + sess.unpin_val(first_undef); + for _ in 0..200 { + let h = sess.pin_val(Val::UNDEFINED); + assert_eq!(h.raw() as u32, first_idx); + sess.unpin_val(h); + } +} + +#[test] +fn local_host_functions_are_reclaimed_by_gc_and_stale_vals_are_bounds_checked() { + struct DropCounter(Rc>); + impl Drop for DropCounter { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + let current = null; + function setHandler(fn) { current = fn; } + function invoke(x) { return current(x); } + return { setHandler, invoke }; + "#, + ) + .expect("session init"); + + let set_handler = sess.export_fn("setHandler").unwrap(); + let invoke = sess.export_fn("invoke").unwrap(); + let drops = Rc::new(Cell::new(0usize)); + let mut last_stale_fn = Val::UNDEFINED; + + for i in 0..32usize { + let guard = DropCounter(drops.clone()); + let local_fn = sess.ctx().new_local_fn("handler", move |_ctx, args| { + let _keep = &guard; + let x = args.get(0).as_f64().unwrap_or(0.0); + Ok(Val::num(x + i as f64)) + }); + last_stale_fn = local_fn; + let _ = sess.call_fn(set_handler, &[local_fn]).unwrap(); + let out = sess.call_fn(invoke, &[Val::num(10.0)]).unwrap(); + assert_eq!(out.as_f64(), Some(10.0 + i as f64)); + } + + // Clear the final reference and collect garbage; all 32 local closures must be dropped + // and trailing heap chunks truncated. + let _ = sess.call_fn(set_handler, &[Val::NULL]).unwrap(); + let stale_obj = sess.ctx().new_object(1); + sess.collect_garbage(); + assert_eq!(drops.get(), 32); + + // Accessing swept / truncated stale Vals via HostCtx must return None/false cleanly, never panic! + let k_x = sess.key("x"); + { + let mut ctx = sess.ctx(); + assert!(!ctx.is_fn(last_stale_fn)); + assert!(!ctx.is_object(stale_obj)); + assert!(!ctx.is_plain_object(stale_obj)); + assert!(!ctx.is_array(stale_obj)); + assert!(!ctx.is_bytes(stale_obj)); + assert!(!ctx.obj_is_frozen(stale_obj)); + assert_eq!(ctx.obj_id(stale_obj), None); + assert!(ctx.obj_get(stale_obj, k_x).is_none()); + assert!(!ctx.obj_for_each(stale_obj, |_, _| {})); + assert!(!ctx.array_for_each(stale_obj, |_| {})); + assert_eq!(ctx.array_len(stale_obj), None); + assert!(ctx.array_get(stale_obj, 0).is_none()); + assert_eq!(ctx.as_bytes(stale_obj), None); + assert_eq!(ctx.pin_fn(last_stale_fn), None); + ctx.obj_set(stale_obj, k_x, Val::num(1.0)); + ctx.array_push(stale_obj, Val::num(1.0)); + } + assert!(sess.call_val(last_stale_fn, Val::UNDEFINED, &[]).is_err()); +} + +#[test] +fn pinned_keys_vs_dynamic_unrooted_keys() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function readKey(obj, name) { return obj[name]; } + return { readKey }; + "#, + ) + .expect("session init"); + + let read_key = sess.export_fn("readKey").unwrap(); + let fixed_k = sess.key("fixedProp"); + + // Warm up and measure baseline memory. + sess.collect_garbage(); + let baseline = sess.memory_bytes(); + + // Create many transient objects using dynamic unrooted keys via obj_set_str. + for round in 0..4 { + { + let mut ctx = sess.ctx(); + for i in 0..500 { + let obj = ctx.new_object(2); + ctx.obj_set_str( + obj, + &format!("dynamic_ephemeral_key_{round}_{i}_payload_padding"), + Val::num(i as f64), + ); + ctx.obj_set_str( + obj, + &format!("other_dynamic_key_{round}_{i}"), + Val::bool(true), + ); + } + } + sess.collect_garbage(); + } + + let after_dynamic = sess.memory_bytes(); + // Dynamic keys were not permanently rooted in host_atoms, so heap stays close to baseline. + assert!( + after_dynamic < baseline + 64 * 1024, + "dynamic keys leaked memory: baseline={baseline}, after={after_dynamic}" + ); + + // Pinned key still works cleanly after repeated full GCs. + let obj = { + let mut ctx = sess.ctx(); + ctx.new_object_with(&[(fixed_k, Val::num(777.0))]) + }; + let name_val = sess.ctx().new_str("fixedProp"); + assert_eq!( + sess.call_fn(read_key, &[obj, name_val]).unwrap().as_f64(), + Some(777.0) + ); + assert_eq!(sess.ctx().key_name(fixed_k), "fixedProp"); +} + +#[test] +fn host_ctx_inspects_dense_and_sparse_arrays_and_sliced_bytes_and_object_invariants() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function makeDenseWithHole() { + const a = [1, , 3]; + return a; + } + function makeSparseWithAccessor() { + const a = [10, 20]; + a[10000005] = 30; + Object.defineProperty(a, "extra", { + get() { return 999; }, + enumerable: true, + configurable: true, + }); + return a; + } + function makeFrozen() { + return Object.freeze({ x: 1, y: "hi" }); + } + function makeWithAccessorAndSymbol() { + const o = { a: 1, [Symbol.toStringTag]: "Custom" }; + Object.defineProperty(o, "acc", { + get() { return 123; }, + enumerable: true, + configurable: true, + }); + return o; + } + function objectKeys(o) { + return Object.keys(o).join(","); + } + function makeByteViews() { + const ab = new ArrayBuffer(12); + const full = new Uint8Array(ab); + for (let i = 0; i < 12; i++) full[i] = i + 1; + const sub = full.subarray(3, 7); + const offsetView = new Uint8Array(ab, 4, 4); + const i32 = new Int32Array(ab, 0, 2); + return { ab, sub, offsetView, i32 }; + } + function echoBytes(u8) { + const out = new Uint8Array(u8.length); + for (let i = 0; i < u8.length; i++) out[i] = u8[i] ^ 0xFF; + return out; + } + return { + makeDenseWithHole, + makeSparseWithAccessor, + makeFrozen, + makeWithAccessorAndSymbol, + objectKeys, + makeByteViews, + echoBytes, + }; + "#, + ) + .expect("session init"); + + let make_dense = sess.export_fn("makeDenseWithHole").unwrap(); + let make_sparse = sess.export_fn("makeSparseWithAccessor").unwrap(); + let make_frozen = sess.export_fn("makeFrozen").unwrap(); + let make_acc_sym = sess.export_fn("makeWithAccessorAndSymbol").unwrap(); + let object_keys = sess.export_fn("objectKeys").unwrap(); + let make_byte_views = sess.export_fn("makeByteViews").unwrap(); + let echo_bytes = sess.export_fn("echoBytes").unwrap(); + + // Dense array with hole + let dense = sess.call_fn(make_dense, &[]).unwrap(); + { + let ctx = sess.ctx(); + assert!(ctx.is_array(dense)); + assert_eq!(ctx.type_name(dense), "array"); + assert_eq!(ctx.array_len(dense), Some(3)); + assert_eq!(ctx.array_get(dense, 0).and_then(Val::as_i64), Some(1)); + assert!(ctx.array_get(dense, 1).unwrap().is_undefined()); + assert_eq!(ctx.array_get(dense, 2).and_then(Val::as_i64), Some(3)); + assert!(ctx.array_get(dense, 3).is_none()); + + let mut seen = Vec::new(); + assert!(ctx.array_for_each(dense, |v| seen.push(v.as_i64()))); + assert_eq!(seen, vec![Some(1), None, Some(3)]); + } + + // Sparse array with an accessor at 10_000_004: must NOT leak internal Kind::Accessor! + let sparse = sess.call_fn(make_sparse, &[]).unwrap(); + { + let ctx = sess.ctx(); + assert!(ctx.is_array(sparse)); + assert_eq!(ctx.array_len(sparse), Some(10_000_006)); + assert_eq!(ctx.array_get(sparse, 0).and_then(Val::as_i64), Some(10)); + assert_eq!(ctx.array_get(sparse, 1).and_then(Val::as_i64), Some(20)); + assert!(ctx.array_get(sparse, 500_000).unwrap().is_undefined()); + assert!(ctx.array_get(sparse, 10_000_004).unwrap().is_undefined()); + assert_eq!( + ctx.array_get(sparse, 10_000_005).and_then(Val::as_i64), + Some(30) + ); + assert!(ctx.array_get(sparse, 10_000_006).is_none()); + + let mut seen = Vec::new(); + assert!(ctx.array_for_each(sparse, |v| { + // None of the yielded items may be an internal accessor object. + assert!(!v.is_obj_ref()); + seen.push(v.as_i64()); + })); + assert_eq!(seen, vec![Some(10), Some(20), Some(30)]); + } + + // Pushing to sparse array extends length cleanly. + sess.ctx().array_push(sparse, Val::num(40.0)); + assert_eq!(sess.ctx().array_len(sparse), Some(10_000_007)); + assert_eq!( + sess.ctx() + .array_get(sparse, 10_000_006) + .and_then(Val::as_i64), + Some(40) + ); + + // Bytes views: subarray, byteOffset, ArrayBuffer, Int32Array, and type_name + let views = sess.call_fn(make_byte_views, &[]).unwrap(); + let k_ab = sess.key("ab"); + let k_sub = sess.key("sub"); + let k_off = sess.key("offsetView"); + let k_i32 = sess.key("i32"); + { + let ctx = sess.ctx(); + let ab = ctx.obj_get(views, k_ab).unwrap(); + let sub = ctx.obj_get(views, k_sub).unwrap(); + let off = ctx.obj_get(views, k_off).unwrap(); + let i32_v = ctx.obj_get(views, k_i32).unwrap(); + + assert_eq!(ctx.type_name(ab), "ArrayBuffer"); + assert_eq!( + ctx.as_bytes(ab), + Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12][..]) + ); + assert_eq!(ctx.type_name(sub), "Uint8Array"); + assert_eq!(ctx.as_bytes(sub), Some(&[4, 5, 6, 7][..])); + assert_eq!(ctx.as_bytes(off), Some(&[5, 6, 7, 8][..])); + assert_eq!(ctx.type_name(i32_v), "Int32Array"); + assert_eq!(ctx.as_bytes(i32_v), Some(&[1, 2, 3, 4, 5, 6, 7, 8][..])); + } + + let input_bytes = sess.ctx().new_bytes(&[0x00, 0x0F, 0xAA, 0xFF]); + assert!(sess.ctx().is_bytes(input_bytes)); + assert_eq!(sess.ctx().type_name(input_bytes), "Uint8Array"); + assert_eq!( + sess.ctx().as_bytes(input_bytes), + Some(&[0x00, 0x0F, 0xAA, 0xFF][..]) + ); + let echoed = sess.call_fn(echo_bytes, &[input_bytes]).unwrap(); + assert_eq!( + sess.ctx().as_bytes(echoed), + Some(&[0xFF, 0xF0, 0x55, 0x00][..]) + ); + + // Frozen object must refuse obj_set mutations cleanly. + let frozen = sess.call_fn(make_frozen, &[]).unwrap(); + let k_x = sess.key("x"); + let k_z = sess.key("z"); + sess.ctx().obj_set(frozen, k_x, Val::num(999.0)); + sess.ctx().obj_set(frozen, k_z, Val::num(123.0)); + { + let ctx = sess.ctx(); + assert!(ctx.is_object(frozen)); + assert!(ctx.is_plain_object(frozen)); + assert!(ctx.obj_is_frozen(frozen)); + assert!(ctx.obj_id(frozen).is_some()); + assert!(!ctx.is_fn(frozen)); + assert_eq!(ctx.obj_get_f64(frozen, k_x), Some(1.0)); + assert!(ctx.obj_get(frozen, k_z).is_none()); + + let mut pairs = Vec::new(); + assert!(ctx.obj_for_each(frozen, |k, v| { + pairs.push((k.to_owned(), v.as_i64(), ctx.to_string_lossy(v))); + })); + assert_eq!( + pairs, + vec![ + ("x".to_owned(), Some(1), None), + ("y".to_owned(), None, Some("hi".to_owned())), + ] + ); + + let mut keys = Vec::new(); + assert!(ctx.obj_for_each_key(frozen, |k, name, _| { + if name == "x" { + // "x" was rooted above via sess.key("x"), so obj_for_each_key yields Some(Key). + let k = k.expect("rooted key x"); + assert_eq!(ctx.key_name(k), "x"); + } else { + // "y" was never rooted via ctx.key(...), so no unrooted Key escapes. + assert_eq!(k, None); + } + keys.push(name.to_owned()); + })); + assert_eq!(keys, vec!["x".to_owned(), "y".to_owned()]); + } + + // Symbol keys (like Symbol.toStringTag) must be skipped by obj_for_each/obj_for_each_key, + // and overwriting a configurable accessor via obj_set resets flags to a normal data property. + let sym_obj = sess.call_fn(make_acc_sym, &[]).unwrap(); + let k_acc = sess.key("acc"); + { + let ctx = sess.ctx(); + let mut names = Vec::new(); + assert!(ctx.obj_for_each(sym_obj, |k, _| names.push(k.to_owned()))); + assert_eq!(names, vec!["a".to_owned()]); + assert!(ctx.obj_get(sym_obj, k_acc).is_none()); + } + sess.ctx().obj_set(sym_obj, k_acc, Val::num(555.0)); + assert_eq!(sess.ctx().obj_get_f64(sym_obj, k_acc), Some(555.0)); + + // Duplicate keys in new_object_with must deduplicate (last wins) so Object.keys has no dupes. + let k_a = sess.key("a"); + let k_b = sess.key("b"); + let dedup_obj = sess.ctx().new_object_with(&[ + (k_a, Val::num(1.0)), + (k_b, Val::num(2.0)), + (k_a, Val::num(3.0)), + ]); + assert_eq!(sess.ctx().obj_get_f64(dedup_obj, k_a), Some(3.0)); + let keys_str = sess.call_fn(object_keys, &[dedup_obj]).unwrap(); + assert_eq!(sess.ctx().as_str(keys_str), Some("a,b")); + + // Val predicates & strict integer conversions + assert!(Val::UNDEFINED.is_nullish()); + assert!(Val::NULL.is_nullish()); + assert!(Val::bool(true).is_bool()); + assert_eq!(Val::bool(true).as_bool(), Some(true)); + assert!(Val::num(42.0).is_num()); + assert_eq!(Val::num(42.0).as_i64(), Some(42)); + assert_eq!(Val::num(42.5).as_i64(), None); + assert_eq!(Val::num(42.0).as_u32(), Some(42)); + assert_eq!(Val::num(-5.0).as_u32(), None); + assert_eq!(Val::num(f64::NAN).as_u32(), None); + assert_eq!(Val::num(f64::INFINITY).as_u32(), None); + assert_eq!(Val::num(1.5).as_u32(), None); + assert_eq!(Val::num(-5.0).as_i32(), Some(-5)); + assert_eq!(Val::num(f64::NAN).as_i32(), None); + assert_eq!(Val::num(1e20).as_i32(), None); + let s = sess.ctx().new_str("hello"); + assert!(s.is_str()); + assert!(frozen.is_obj_ref()); +} + +#[test] +fn direct_host_errors_and_reentrant_call_fn_val_and_recursion_limit() { + let rt = Runtime::make().globals(|_| { + vec![ + ( + "boom", + HostValue::Function(HostFunction::direct(|ctx, _| { + Err(ctx.type_error("bad direct arg")) + })), + ), + ( + "callBack", + HostValue::Function(HostFunction::direct(|ctx, args| { + let f = args.get(0); + let arg = args.get(1); + ctx.call_fn_val(f, Val::UNDEFINED, &[arg]) + })), + ), + ] + }); + + let mut sess = rt + .session( + r#" + function catchBoom() { + try { + boom(); + return "ok"; + } catch (e) { + return e.message; + } + } + function roundTrip(x) { + return callBack((v) => v * 7, x); + } + function mutualRecurse() { + function ping(n) { + return callBack(ping, n + 1); + } + try { + ping(0); + return "no error"; + } catch (e) { + return e.name + ":" + e.message; + } + } + return { catchBoom, roundTrip, mutualRecurse }; + "#, + ) + .expect("session init"); + + let catch_boom = sess.export_fn("catchBoom").unwrap(); + let round_trip = sess.export_fn("roundTrip").unwrap(); + let mutual_recurse = sess.export_fn("mutualRecurse").unwrap(); + + let out = sess.call_fn(catch_boom, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(out), Some("bad direct arg")); + + let rt_out = sess.call_fn(round_trip, &[Val::num(6.0)]).unwrap(); + assert_eq!(rt_out.as_f64(), Some(42.0)); + + let rec_out = sess.call_fn(mutual_recurse, &[]).unwrap(); + let ctx = sess.ctx(); + let rec_msg = ctx.as_str(rec_out).unwrap_or(""); + assert!( + rec_msg.contains("RangeError") && rec_msg.contains("Maximum call stack size exceeded"), + "expected RangeError stack overflow, got: {rec_msg}" + ); +} + +#[test] +fn drain_jobs_supports_300_awaits_budgeted_draining_and_fatal_loop_cutoff() { + let rt = Runtime::make().limits(Limits { + clock: Clock::Wall, + ..Limits::default() + }); + let mut sess = rt + .session( + r#" + let total = 0; + async function awaitMany() { + let sum = 0; + for (let i = 0; i < 300; i++) { + sum += await i; + } + total = sum; + } + function getTotal() { + return total; + } + function startInfiniteMicrotasks() { + function loop() { + Promise.resolve().then(loop); + } + loop(); + } + return { awaitMany, getTotal, startInfiniteMicrotasks }; + "#, + ) + .expect("session init"); + + let await_many = sess.export_fn("awaitMany").unwrap(); + let get_total = sess.export_fn("getTotal").unwrap(); + let start_loop = sess.export_fn("startInfiniteMicrotasks").unwrap(); + + // Budgeted draining is non-destructive: drain 10 jobs, verify more remain, then finish all 300 awaits! + let _ = sess.call_fn(await_many, &[]).unwrap(); + assert!(sess.has_pending_jobs()); + assert!(sess.drain_jobs_budget(10).expect("partial drain")); + assert!(sess.has_pending_jobs()); + sess.drain_jobs().expect("finish 300 awaits"); + assert!(!sess.has_pending_jobs()); + // sum(0..300) = 299 * 300 / 2 = 44850 + assert_eq!( + sess.call_fn(get_total, &[]).unwrap().as_f64(), + Some(44_850.0) + ); + + // Infinite microtask loop trips drain_jobs() cap; arm_slice trips fatal SliceExceeded and clears jobs. + let _ = sess.call_fn(start_loop, &[]).unwrap(); + let cap_err = sess.drain_jobs().expect_err("must cap infinite microtasks"); + assert_eq!(cap_err.kind, DiagnosticKind::SliceExceeded); + assert!(sess.has_pending_jobs()); + + sess.arm_slice(20); + let fatal_err = sess + .drain_jobs_budget(usize::MAX) + .expect_err("slice must cut off runaway microtasks"); + sess.disarm_slice(); + assert_eq!(fatal_err.kind, DiagnosticKind::SliceExceeded); + assert!(!sess.has_pending_jobs()); +} + +#[test] +fn take_unhandled_rejections_never_executes_user_to_string_or_getters() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function triggerRejections() { + Promise.reject(new TypeError("invalid input")); + Promise.reject("plain rejection"); + Promise.reject({ toString() { while (true) {} } }); + Promise.reject({ + [Symbol.toPrimitive]() { while (true) {} }, + get message() { while (true) {} } + }); + } + return { triggerRejections }; + "#, + ) + .expect("session init"); + + let trigger = sess.export_fn("triggerRejections").unwrap(); + let _ = sess.call_fn(trigger, &[]).unwrap(); + sess.drain_jobs().expect("drain rejections"); + + let started = Instant::now(); + let rejections = sess.take_unhandled_rejections(); + assert!( + started.elapsed() < Duration::from_secs(2), + "take_unhandled_rejections took too long" + ); + assert_eq!(rejections.len(), 4); + assert_eq!(rejections[0], "TypeError: invalid input"); + assert_eq!(rejections[1], "plain rejection"); + assert_eq!(rejections[2], "[object]"); + assert_eq!(rejections[3], "[object]"); + assert!(sess.take_unhandled_rejections().is_empty()); +} + +#[test] +fn session_start_enforces_thread_cpu_timeout_and_rejects_incomplete_init() { + let rt_cpu = Runtime::make().limits(Limits { + clock: Clock::ThreadCpu, + timeout_ms: Some(40), + ..Limits::default() + }); + let outcome = match rt_cpu.session("while (true) {}") { + Ok(_) => panic!("infinite loop under ThreadCpu must time out"), + Err(err) => err, + }; + let diag = outcome.result.expect_err("expected TimeoutExceeded"); + assert_eq!(diag.kind, DiagnosticKind::TimeoutExceeded); + + // Top-level init that awaits an unresolved promise never completes -> rejected cleanly. + let rt_pending = Runtime::make(); + let pending_outcome = match rt_pending.session("await new Promise(() => {});") { + Ok(_) => panic!("incomplete top-level init must fail"), + Err(err) => err, + }; + assert!(pending_outcome.result.is_err()); +} + +#[test] +fn arm_and_disarm_slice_recovers_from_infinite_loops() { + let rt = Runtime::make().limits(Limits { + clock: Clock::Wall, + ..Limits::default() + }); + let mut sess = rt + .session( + r#" + function spin() { + while (true) {} + } + async function asyncSpin() { + while (true) {} + } + function add(a, b) { + return a + b; + } + return { spin, asyncSpin, add }; + "#, + ) + .expect("session init"); + + let spin = sess.export_fn("spin").unwrap(); + let async_spin = sess.export_fn("asyncSpin").unwrap(); + let add = sess.export_fn("add").unwrap(); + + // Sync infinite loop hits SliceExceeded and recovers. + sess.arm_slice(20); + let err = sess.call_fn(spin, &[]).expect_err("spin must time out"); + sess.disarm_slice(); + assert_eq!(err.kind, DiagnosticKind::SliceExceeded); + + // After disarm_slice, normal calls work cleanly. + assert_eq!( + sess.call_fn(add, &[Val::num(2.0), Val::num(3.0)]) + .unwrap() + .as_f64(), + Some(5.0) + ); + + // Async infinite loop also unwinds cleanly (freeing its coroutine) and recovers. + sess.arm_slice(20); + let err = sess + .call_fn(async_spin, &[]) + .expect_err("asyncSpin must time out"); + sess.disarm_slice(); + assert_eq!(err.kind, DiagnosticKind::SliceExceeded); + + sess.arm_slice(200); + let sum = sess + .call_fn(add, &[Val::num(10.0), Val::num(25.0)]) + .unwrap(); + sess.disarm_slice(); + assert_eq!(sum.as_f64(), Some(35.0)); +} + +#[test] +fn collect_garbage_mid_mark_collects_newly_unpinned_objects() { + struct DropGuard(Rc>); + impl Drop for DropGuard { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + + let rt = Runtime::make(); + let mut sess = rt.session("return {};").expect("session init"); + + sess.collect_garbage(); + let drops = Rc::new(Cell::new(0usize)); + let guard = DropGuard(drops.clone()); + let local_fn = sess.ctx().new_local_fn("ephemeral", move |_, _| { + let _keep = &guard; + Ok(Val::UNDEFINED) + }); + let h = sess.pin_val(local_fn); + assert_eq!(drops.get(), 0); + + // Cross GC trigger and enter Phase::Mark while h is still pinned (so local_fn is marked live + // in the in-progress cycle). + { + let mut ctx = sess.ctx(); + for _ in 0..75_000 { + let _ = ctx.new_object(0); + } + } + sess.gc_step(); + assert_eq!(drops.get(), 0); + + // Unpin h mid-mark, then call collect_garbage() ONCE. It must finish the in-progress cycle + // and run a fresh full cycle so the newly unpinned closure is actually swept and dropped! + sess.unpin_val(h); + sess.collect_garbage(); + assert_eq!( + drops.get(), + 1, + "expected unpinned mid-mark closure to be actually swept and dropped" + ); +} + +#[test] +fn single_call_fn_with_many_transient_allocations_runs_incremental_gc_without_oom() { + let rt = Runtime::make().limits(Limits { + max_heap_bytes: Some(8 * 1024 * 1024), + ..Limits::default() + }); + let mut sess = rt + .session( + r#" + function allocateTransient() { + let sum = 0; + for (let i = 0; i < 260000; i++) { + const tmp = { x: i, y: i + 1 }; + sum += tmp.x & 1; + } + return sum; + } + return { allocateTransient }; + "#, + ) + .expect("session init"); + + let alloc_fn = sess.export_fn("allocateTransient").unwrap(); + let out = sess + .call_fn(alloc_fn, &[]) + .expect("incremental GC must prevent OOM on 260k transient objects"); + assert_eq!(out.as_f64(), Some(130_000.0)); +} + +#[test] +fn per_session_user_data_and_nested_session_drop_safety() { + #[derive(Clone)] + struct AppState { + hits: Rc>, + } + + let rt = Runtime::make().globals(|_| { + vec![( + "bump", + HostValue::Function(HostFunction::direct(|ctx, _| { + let next = ctx + .with_user_data::(|s| { + let v = s.hits.get() + 1; + s.hits.set(v); + v + }) + .unwrap_or(0); + Ok(Val::num(next as f64)) + })), + )] + }); + + let mut outer = rt + .session("return { go: () => bump() };") + .expect("outer session"); + let state = AppState { + hits: Rc::new(Cell::new(0)), + }; + outer.set_user_data(state.clone()); + + let go = outer.export_fn("go").unwrap(); + assert_eq!(outer.call_fn(go, &[]).unwrap().as_f64(), Some(1.0)); + assert_eq!(outer.call_fn(go, &[]).unwrap().as_f64(), Some(2.0)); + assert_eq!(outer.get_user_data::().unwrap().hits.get(), 2); + + outer.with_user_data_mut::(|s| s.hits.set(10)); + assert_eq!(outer.call_fn(go, &[]).unwrap().as_f64(), Some(11.0)); + + // Store a nested Session inside user_data to ensure dropping outer does not re-entrantly + // borrow SESSION_STORES while removing the outer store. + struct NestedSession(#[allow(dead_code)] Session); + let inner = rt.session("return {};").expect("inner session"); + outer.set_user_data(NestedSession(inner)); + drop(outer); +} + +#[test] +fn direct_callback_reentering_js_cannot_bypass_arm_slice() { + let rt = Runtime::make() + .limits(Limits { + clock: Clock::Wall, + ..Limits::default() + }) + .globals(|_| { + vec![( + "callBack", + HostValue::Function(HostFunction::direct(|ctx, args| { + ctx.call_fn_val(args.get(0), Val::UNDEFINED, &[]) + })), + )] + }); + + let mut sess = rt + .session( + r#" + function spinViaDirect() { + for (;;) { + callBack(() => { + let x = 0; + for (let i = 0; i < 500; i++) x += i; + return x; + }); + } + } + return { spinViaDirect }; + "#, + ) + .expect("session init"); + + let spin = sess.export_fn("spinViaDirect").unwrap(); + sess.arm_slice(25); + let err = sess + .call_fn(spin, &[]) + .expect_err("direct re-entry must still trip arm_slice"); + sess.disarm_slice(); + assert_eq!(err.kind, DiagnosticKind::SliceExceeded); +} + +#[test] +fn obj_set_preserves_existing_data_property_descriptor_flags() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function makeObj() { + const o = {}; + Object.defineProperty(o, "hidden", { + value: 1, + writable: true, + enumerable: false, + configurable: false, + }); + return o; + } + function inspect(o) { + const d = Object.getOwnPropertyDescriptor(o, "hidden"); + return [d.value, d.writable, d.enumerable, d.configurable].join(":"); + } + return { makeObj, inspect }; + "#, + ) + .expect("session init"); + + let make_obj = sess.export_fn("makeObj").unwrap(); + let inspect = sess.export_fn("inspect").unwrap(); + + let obj = sess.call_fn(make_obj, &[]).unwrap(); + let k_hidden = sess.key("hidden"); + sess.ctx().obj_set(obj, k_hidden, Val::num(42.0)); + + let out = sess.call_fn(inspect, &[obj]).unwrap(); + assert_eq!(sess.ctx().as_str(out), Some("42:true:false:false")); +} + +#[test] +fn writing_stale_post_gc_val_sanitizes_to_undefined_without_panicking() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function inspectProp(o, arg) { + return typeof o.stale + ":" + typeof arg; + } + return { inspectProp }; + "#, + ) + .expect("session init"); + + let inspect_prop = sess.export_fn("inspectProp").unwrap(); + + // Allocate an unrooted object and sweep + truncate trailing heap chunks so its Id is OOB. + let stale_obj = sess.ctx().new_object(1); + sess.collect_garbage(); + + let holder = sess.ctx().new_object(1); + let k_stale = sess.key("stale"); + sess.ctx().obj_set(holder, k_stale, stale_obj); + + let out = sess.call_fn(inspect_prop, &[holder, stale_obj]).unwrap(); + assert_eq!(sess.ctx().as_str(out), Some("undefined:undefined")); +} + +#[test] +fn cross_session_handles_are_rejected_for_read_call_and_unpin() { + let rt = Runtime::make(); + let mut sess_a = rt + .session("function a() { return 111; } return { a, val: { x: 1 } };") + .expect("session a"); + let mut sess_b = rt + .session("function b() { return 222; } return { b, val: { x: 2 } };") + .expect("session b"); + + let fn_a = sess_a.export_fn("a").unwrap(); + let fn_b = sess_b.export_fn("b").unwrap(); + + let k_val_a = sess_a.key("val"); + let k_val_b = sess_b.key("val"); + let exp_a = sess_a.exports(); + let exp_b = sess_b.exports(); + let v_a = sess_a.ctx().obj_get(exp_a, k_val_a).unwrap(); + let v_b = sess_b.ctx().obj_get(exp_b, k_val_b).unwrap(); + let h_a = sess_a.pin_val(v_a); + let h_b = sess_b.pin_val(v_b); + + // Handle from Session A must NEVER read, call, or unpin Session B's matching slot. + assert!(sess_b.get_fn(fn_a).is_undefined()); + assert!(sess_b.get_val(h_a).is_undefined()); + assert!(sess_b.call_fn(fn_a, &[]).is_err()); + sess_b.unpin_fn(fn_a); + sess_b.unpin_val(h_a); + + // Session B's own handles remain completely intact! + assert_eq!(sess_b.call_fn(fn_b, &[]).unwrap().as_f64(), Some(222.0)); + let k_x_b = sess_b.key("x"); + let b_val = sess_b.get_val(h_b); + assert_eq!(sess_b.ctx().obj_get_f64(b_val, k_x_b), Some(2.0)); +} + +#[test] +fn std_bigint_prototype_stays_rooted_after_replacing_bigint_global() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function touchBigInt() { + return BigInt(1).toString(); + } + function formatLiteral() { + return (12345678901234567890n).toString(); + } + return { touchBigInt, formatLiteral }; + "#, + ) + .expect("session init"); + + let touch = sess.export_fn("touchBigInt").unwrap(); + let format_lit = sess.export_fn("formatLiteral").unwrap(); + + let s1 = sess.call_fn(touch, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(s1), Some("1")); + + // Overwrite BigInt global and force full GC + churn; std.bigint must remain rooted! + sess.set_global("BigInt", Val::UNDEFINED); + sess.collect_garbage(); + { + let mut ctx = sess.ctx(); + for _ in 0..5_000 { + let _ = ctx.new_object(0); + } + } + sess.collect_garbage(); + + let s2 = sess.call_fn(format_lit, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(s2), Some("12345678901234567890")); +} + +#[test] +fn array_from_async_and_iter_close_run_cleanly_under_session_and_gc_stress() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + let out = null; + async function run() { + let closed = 0; + const iter = { + i: 0, + [Symbol.iterator]() { return this; }, + next() { + if (this.i++ < 5) { + return { value: Promise.reject("stop-" + this.i), done: false }; + } + return { value: undefined, done: true }; + }, + return() { + closed += 1; + // Allocate inside iter_close to exercise GC under stress! + for (let j = 0; j < 200; j++) { + const o = { j, s: "close-" + j }; + if (o.j < 0) break; + } + return { value: undefined, done: true }; + }, + }; + try { + await Array.fromAsync(iter); + out = "unexpected-ok"; + } catch (e) { + out = e + ":closed=" + closed; + } + } + function getOut() { return out; } + return { run, getOut }; + "#, + ) + .expect("session init"); + + let run_fn = sess.export_fn("run").unwrap(); + let get_out = sess.export_fn("getOut").unwrap(); + + let _ = sess.call_fn(run_fn, &[]).unwrap(); + sess.drain_jobs().expect("drain Array.fromAsync"); + let out = sess.call_fn(get_out, &[]).unwrap(); + assert_eq!(sess.ctx().as_str(out), Some("stop-1:closed=1")); +} + +#[test] +fn stale_raw_val_during_phase_sweep_is_sanitized_to_undefined() { + let rt = Runtime::make(); + let mut sess = rt + .session( + r#" + function makeEphemeral() { + return { tag: "doomed-in-sweep" }; + } + return { makeEphemeral }; + "#, + ) + .expect("session init"); + + let make_ephemeral = sess.export_fn("makeEphemeral").unwrap(); + sess.collect_garbage(); + + // Allocate many unrooted objects so sweeping takes multiple incremental gc_step() calls, + // and keep a raw unpinned Val to the last doomed object (high heap id, near end of sweep range). + { + let mut ctx = sess.ctx(); + for _ in 0..80_000 { + let _ = ctx.new_object(0); + } + } + let doomed_obj = sess.call_fn(make_ephemeral, &[]).unwrap(); + let doomed_str = sess.ctx().new_str("doomed-sweep-string"); + + // Advance incremental GC steps until Mark finishes and Phase::Sweep begins (works under both + // normal mode and PSYCHOSCRIPT_GC_STRESS=1). Once Phase::Sweep starts, live_obj rejects the + // doomed WHITE slot even before the sweep cursor reaches it. + let mut entered_sweep = false; + for _ in 0..500 { + sess.gc_step(); + if !sess.ctx().is_object(doomed_obj) { + entered_sweep = true; + break; + } + } + assert!( + entered_sweep, + "GC must reject doomed WHITE object upon entering Phase::Sweep" + ); + + // Even if we're mid-Sweep before doomed_obj's slot is reached, sanitize_val / pin_val / live_obj + // must treat the unswept WHITE slot as dead (undefined) rather than pinning a doomed id! + let pinned_obj = sess.pin_val(doomed_obj); + let pinned_str = sess.pin_val(doomed_str); + assert!(sess.get_val(pinned_obj).is_undefined()); + assert!(sess.get_val(pinned_str).is_undefined()); + assert!(!sess.ctx().is_object(doomed_obj)); + assert_eq!(sess.ctx().as_str(doomed_str), None); + + // Finish sweep cleanly; pinned handles stay safely undefined. + sess.collect_garbage(); + assert!(sess.get_val(pinned_obj).is_undefined()); + assert!(sess.get_val(pinned_str).is_undefined()); +} + +#[test] +fn standalone_execute_runs_have_distinct_handle_session_ids() { + let saved = Arc::new(Mutex::new(None::)); + let rt = Runtime::make().globals({ + let saved = saved.clone(); + move |_| { + let saved = saved.clone(); + vec![( + "pinOrRead", + HostValue::Function(HostFunction::direct(move |ctx, args| { + let mut guard = saved.lock().unwrap(); + if let Some(prev_handle) = *guard { + // Must reject handle created in an earlier Runtime::execute VM! + let v = ctx.get_val(prev_handle); + return Ok(Val::bool(v.is_undefined())); + } + let h = ctx.pin_val(args.get(0)); + *guard = Some(h); + Ok(Val::bool(true)) + })), + )] + } + }); + + let r1 = rt.execute("return pinOrRead({ a: 1 });").result.unwrap(); + assert_eq!(r1, psychoscript::Data::Bool(true)); + + // In a second standalone execute() VM, reading the handle from run 1 must return undefined. + let r2 = rt.execute("return pinOrRead({ a: 2 });").result.unwrap(); + assert_eq!(r2, psychoscript::Data::Bool(true)); +} From 9b2db76fd4609cc5a584e31f64613f85c0e18401 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 16:39:17 +0000 Subject: [PATCH 2/6] fix(rust): a session is a kept run, saved as one; direct host functions on the host call path Review changes for #157: the session drives its calls with the program driver (jobs, async host calls, GC at the existing safe points, limits per call), its failures stick, its value crosses as a run's result, and it saves and restores through the snapshot machinery. HostFunction::direct goes through call_host with the sync call's accounting; HostCtx reads, writes and calls as the program does, and its values can't outlive the call. --- rust/README.md | 4 +- rust/crates/psychoscript/src/collector.rs | 200 +- rust/crates/psychoscript/src/cross.rs | 8 + rust/crates/psychoscript/src/host.rs | 148 +- rust/crates/psychoscript/src/host_function.rs | 24 +- rust/crates/psychoscript/src/lib.rs | 2 +- rust/crates/psychoscript/src/program.rs | 147 +- rust/crates/psychoscript/src/promise.rs | 8 - rust/crates/psychoscript/src/reach.rs | 13 +- rust/crates/psychoscript/src/run.rs | 7 +- rust/crates/psychoscript/src/runtime.rs | 21 +- rust/crates/psychoscript/src/session.rs | 1940 +++-------------- rust/crates/psychoscript/src/snapshot.rs | 79 +- rust/crates/psychoscript/src/strings.rs | 28 - rust/crates/psychoscript/src/vm.rs | 378 +--- rust/crates/psychoscript/tests/session.rs | 1827 ++++------------ 16 files changed, 957 insertions(+), 3877 deletions(-) diff --git a/rust/README.md b/rust/README.md index e223af31..315320b7 100644 --- a/rust/README.md +++ b/rust/README.md @@ -69,6 +69,8 @@ Only Rust has: - Located host errors: [`HostError::located`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs) (`HostValue::Located`), caught as a standard error at the call, with the host error's own fields. - The program's own lines: [`Runtime::program_lines`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs); an error raised in the host's code around them (a prelude), or by a host function called from there, is located at the nearest frame of the program, as is [`Call::location`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs). - Always-on typed arrays: `ArrayBuffer` and every standard typed array besides Uint8Array, as [`HostValue::TypedArray`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs): lent without a copy to sync host functions, copied for async and durable ones. +- Direct host functions: [`HostFunction::direct`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/session.rs) gets the program's own values, with no copy, through the call's `HostCtx` (read, write and call as the program does: getters and setters run, frozen objects refuse; a typed array's bytes in place) and returns its value or what it throws. The values are the call's only: nothing collects the heap during a host call, and a `Val` can't outlive it. It is a synchronous host call (its time is the host's, a suspend is refused while it runs), and runs where the run computes, which for a run driven as a future may be its worker. +- Sessions: [`Runtime::session`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/session.rs) runs a program whose top level returns an object of functions and keeps the run; `Session::call(name, args)` runs one as a run runs (its limits from the call, async host calls driven, its value crossing back as an `Outcome`), with the program's state kept from call to call. A failure that ends a run leaves the session failed. `Session::save` gives the state between calls as a suspended run's, and `Runtime::restore_session` continues it, also in another process of the same build. - Lazy built-in groups: [`LAZY`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/builtins/mod.rs) sets up `RegExp`, `Date`, the typed arrays and the other groups only when a program uses them. - Optional `locale` feature (`default = ["locale"]`): disable it with `default-features = false` to drop ICU4X's compiled CLDR tables (~5 MB) in lean embedded or `wasm32` builds. With `locale` off and no provider of the host's (below), `locales` and `options` are ignored: `Date.prototype.toLocale*String` returns UTC ISO-8601 strings (`YYYY-MM-DDTHH:mm:ss.sssZ`, date slice, or time slice, or `"Invalid Date"`), `Number`/`BigInt.prototype.toLocaleString` use decimal `toString`, and `String.prototype.localeCompare` compares NFC-normalized UTF-16 code units. - A pluggable locale provider: [`Runtime::locale`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) sets the [`LocaleProvider`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/locale.rs) (`Send + Sync`) that formats dates for `toLocale*String`, numbers and BigInts for `toLocaleString`, and compares strings for `localeCompare`, in place of the default: `IcuLocale` with `locale`, `FallbackLocale` (the fallbacks above) without it. PsychoScript still reads and validates the locales and options and throws their errors, as with `locale`, so the provider gets the locale tags and the resolved options as plain Rust data and only formats or compares; it checks `timeZone` itself (PsychoScript's zone data checks it only for the defaults), and an `Err` it returns, for what only it can know, is thrown as a `RangeError`. It is host configuration like the globals, not saved with a run. A `wasm32` host without `locale` can hand them to the browser's `Intl` through `wasm-bindgen` (`js_sys::Intl::DateTimeFormat`, `NumberFormat`, `Collator`, or `toLocaleString` on a `js_sys::Date`), turning each option back into its `Intl` name. @@ -121,7 +123,7 @@ reference, never from hand: - `conformance/host.json` (`host.ts`), `boundary.json` (`boundary.ts`) and `streaming.json` (`streaming.ts`), replayed by `crates/psychoscript/tests/`. - Rust-only features have no reference: their expected results are written in Rust's own tests - (`crates/psychoscript/tests/heap.rs`, `clock.rs`, `typed.rs`, `host_recording.rs`, `value_depth.rs`; the programs + (`crates/psychoscript/tests/heap.rs`, `clock.rs`, `typed.rs`, `host_recording.rs`, `value_depth.rs`, `session.rs`; the programs of `tests/cases/*.js` also run in round-trip mode). - test262, both ways: `test262/rust-skipped.txt` (fails here, passes in the reference) and `test262/reference-gaps.txt` (passes here, fails in the reference) are empty and may only stay so. diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index 2e106c2b..ca606c66 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -480,12 +480,6 @@ impl Gc { std::mem::replace(&mut self.made, outer).unwrap_or_default() } - /// Whether the collector alone set `suspend_wanted` so a top-level call may take a GC step at a back-edge. - #[inline(always)] - pub(crate) fn owns_suspend(&self) -> bool { - self.owns_suspend - } - /// Someone other than the collector asks the run to stop. pub(crate) fn disown_suspend(&mut self) { self.owns_suspend = false; @@ -551,18 +545,6 @@ impl StrGc { grow_free: Vec::new(), } } - - /// Whether string slot `idx` is live and not scheduled to be swept in an active post-mark phase. - #[inline(always)] - pub(crate) fn is_live(&self, idx: usize) -> bool { - match self.color.get(idx) { - Some(&FREE) => false, - Some(&WHITE) if matches!(self.phase, Phase::Idle | Phase::Mark) => true, - Some(&WHITE) if self.phase == Phase::Sweep => idx < self.sweep.0 || idx >= self.sweep.1, - Some(&WHITE) => false, - _ => true, - } - } } impl Strings { @@ -1140,171 +1122,11 @@ impl Vm { } } - /// Whether heap object `id` is live and not scheduled to be swept in an active post-mark phase. - #[inline(always)] - pub(crate) fn is_live_obj(&self, id: Id) -> bool { - let i = id as usize; - if i >= self.heap.len() { - return false; - } - match self.heap.marks.color.get(i) { - Some(&FREE) => false, - Some(&WHITE) if matches!(self.gc.phase, Phase::Idle | Phase::Mark) => true, - Some(&WHITE) if self.gc.phase == Phase::Sweep => { - i < self.gc.obj_sweep.0 || i >= self.gc.obj_sweep.1 - } - Some(&WHITE) => false, - _ => true, - } - } - - /// Bounds- and liveness-checked read of heap object `id`. - #[inline(always)] - pub(crate) fn live_obj(&self, id: Id) -> Option<&Obj> { - self.is_live_obj(id).then(|| &self.heap[id as usize]) - } - - /// Bounds- and liveness-checked mutable read of heap object `id`, running the SATB barrier. - #[inline(always)] - pub(crate) fn live_obj_mut(&mut self, id: Id) -> Option<&mut Obj> { - if !self.is_live_obj(id) { - return None; - } - Some(&mut self.heap[id as usize]) - } - - /// Whether the incremental collector is currently in `Phase::Mark`. - #[inline(always)] - pub(crate) fn gc_is_marking(&self) -> bool { - self.gc.phase == Phase::Mark - } - - /// Write barrier for rooting a value outside the heap (e.g. `Vm::pinned`, `Vm::global_map`, - /// `Vm::globals`) or writing into an already-black host-mutated object while incremental GC is - /// in `Phase::Mark`. Because incremental marking has no atomic remark pass, a white object - /// newly stored into an already-scanned root or black object would otherwise be swept. - #[inline] - pub(crate) fn gc_shade(&mut self, val: Value) { - if self.gc.phase != Phase::Mark { - return; - } - self.gc_shade_slow(val); - } - - #[cold] - #[inline(never)] - fn gc_shade_slow(&mut self, val: Value) { - match val { - Value::Big(id) if !crate::builtins::bigint::on_heap(id) => {} - Value::Obj(id) | Value::Big(id) => { - if self.heap.marks.color.get(id as usize) == Some(&WHITE) { - self.heap.marks.color[id as usize] = GREY; - self.heap.marks.grey.push(id); - } - } - Value::Str(s) => { - let idx = s as usize; - if let Some(c) = self.atoms.gc.color.get_mut(idx) - && *c == WHITE - { - *c = BLACK; - let g = self.atoms.bufs[idx].grow as usize; - if self.atoms.gc.retired.get(g) != Some(&true) - && let Some(l) = self.atoms.gc.grow_live.get_mut(g) - { - *l = true; - } - } - } - _ => {} - } - } - - /// Shades an atom key written into a live object during an active GC cycle. - #[inline] - pub(crate) fn gc_shade_atom(&mut self, a: Atom) { - if self.gc.phase != Phase::Idle - && let Some(&sid) = self.atoms.atom_str.get(a as usize) - && sid != crate::strings::NO_ATOM - { - self.atoms.shade_atom(a); - } - } - - /// Runs a full GC cycle (finishing any in-progress cycle first, then executing one complete - /// `Idle -> Mark -> Sweep -> Idle` pass) and releases empty trailing heap chunks back to the OS. - pub(crate) fn gc_collect_full(&mut self) { - let busy = self.replay_meter.is_some() - || !self.replay.is_empty() - || self.convert_req.is_some() - || self.json_walk != 0; - if busy { - return; - } - // If a cycle was already underway, finish it first so a fresh Idle -> Mark -> Sweep -> Idle - // pass collects anything unpinned or dropped during the prior mark phase. - if self.gc.phase != Phase::Idle { - while self.gc.phase != Phase::Idle { - self.gc.debt = MAX_WORK; - self.gc_step(); - } - } - loop { - self.gc.debt = MAX_WORK; - self.gc_step(); - if self.gc.phase == Phase::Idle { - break; - } - } - self.gc.requested = false; - if self.gc.owns_suspend { - self.gc.owns_suspend = false; - self.suspend_wanted = false; - } - let old_len = self.heap.len(); - let floor = self.snapshot_base.heap.max(self.heap.base.get().len()); - let mut top = old_len; - while top > floor && self.heap.marks.color.get(top - 1) == Some(&FREE) { - top -= 1; - } - if top < old_len { - while self.heap.drop_free_tail(top) > 0 {} - let new_len = self.heap.len(); - self.heap.chunks.shrink_to_fit(); - self.heap.marks.color.shrink_to_fit(); - self.gc.free.retain(|&id| (id as usize) < new_len); - self.gc.free.shrink_to_fit(); - if let Some(m) = self.heap_meter.as_deref_mut() { - m.on_heap_truncate(old_len, new_len); - } - } - self.gc_poll(); - } - /// Whether a step is due, for the host stop. pub(crate) fn gc_pending(&self) -> bool { self.gc.requested } - /// Runs one bounded incremental GC step when the VM is not inside a non-reentrant conversion. - pub(crate) fn gc_step_once(&mut self) { - let busy = self.replay_meter.is_some() - || !self.replay.is_empty() - || self.convert_req.is_some() - || self.json_walk != 0; - if busy { - return; - } - if self.gc.phase != Phase::Idle || self.gc.requested || self.gc_used() >= self.gc.trigger { - self.gc.requested = false; - self.gc_step(); - if self.gc.owns_suspend && !self.gc.requested { - self.gc.owns_suspend = false; - self.suspend_wanted = false; - } - } - } - fn gc_step(&mut self) { #[cfg(feature = "gc-stats")] let started = crate::time::Instant::now(); @@ -1411,26 +1233,8 @@ impl Vm { match self.heap.marks.color[at] { WHITE => { self.heap.marks.color[at] = FREE; - let reclaim_fn = match &self.heap[at].kind { - Kind::BigInt(n) => { - self.bigints.forget(at as Id, n); - None - } - Kind::Native { - f, - data: Value::Num(index), - .. - } if std::ptr::fn_addr_eq( - *f, - crate::host::host_native as crate::vm::NativeFn, - ) => - { - Some(*index as usize) - } - _ => None, - }; - if let Some(idx) = reclaim_fn { - self.host.reclaim_function(idx); + if let Kind::BigInt(n) = &self.heap[at].kind { + self.bigints.forget(at as Id, n); } *self.heap.slot_mut(at) = Obj::new(None, Kind::Ordinary); self.gc.free.push(at as Id); diff --git a/rust/crates/psychoscript/src/cross.rs b/rust/crates/psychoscript/src/cross.rs index 5a3840b8..e7c78def 100644 --- a/rust/crates/psychoscript/src/cross.rs +++ b/rust/crates/psychoscript/src/cross.rs @@ -408,6 +408,14 @@ fn plain_scalar(vm: &Vm, v: &Value) -> Option { /// The program returned `v`: its result once it has crossed. pub fn program_result(vm: &mut Vm, v: Value) -> Result<(), Value> { + // A session's top level returns what its calls call, which stays in the run uncrossed (`session.rs`). + if let Some(s) = vm.session.as_deref_mut() + && s.exports.is_none() + { + s.exports = Some(v); + vm.outcome = Some(Ok(Value::Undef)); + return Ok(()); + } if !thenable(vm, &v) { match fast(vm, &v) { Ok(Fast::Json(j)) => { diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 3f3f177c..2a41b3fa 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -190,10 +190,6 @@ pub struct FnEntry { /// Whether it is among the globals, even where no path leads (inside an array): such a function never crosses /// back to the host as itself. pub(crate) installed: bool, - /// Whether GC may reclaim this slot when its JS wrapper object is swept (true for direct/local host fns). - pub(crate) reclaimable: bool, - /// Owning `(session_id, local_idx, generation)` in `SESSION_STORES` when created by `HostCtx::new_local_fn`. - pub(crate) local_slot: Option<(u64, usize, u32)>, } /// A host call in flight, as a suspend sees it. @@ -306,9 +302,7 @@ pub struct RunHost { pub(crate) run: Run, pub(crate) next_call: u64, pub tasks: Tasks<'static, Settlement>, - pub(crate) functions: Vec>, - /// Free indices in `functions` reclaimed when direct/local host functions are swept by GC. - pub(crate) free_functions: Vec, + pub(crate) functions: Vec, /// Host calls in flight. pub calls: Vec, /// Results whose functions survive a suspend through their owner's hooks. @@ -410,7 +404,6 @@ impl RunHost { next_call: 0, tasks: Tasks::default(), functions: Vec::new(), - free_functions: Vec::new(), calls: Vec::new(), results: Vec::new(), restarts: Vec::new(), @@ -855,7 +848,7 @@ pub fn call_namespace(vm: &mut Vm, id: Id, args: &[Value], callee: Value) -> Res path, owner: None, }; - call_host(vm, &f, args, target, callee) + call_host(vm, &f, Value::Undef, args, target, callee) } /// The raw strings of a tagged template's strings array in the first argument: one of the template objects the program @@ -895,31 +888,18 @@ struct Target { /// async or durable function's call starts at once and the program gets its promise; a failure crossing rejects it. /// A synchronous one is called now: its value crosses back at once, and work it left pending is a promise. When the /// runtime awaits promises in arguments and one hasn't fulfilled, the call waits for them first. -fn call_host(vm: &mut Vm, f: &Callee, args: &[Value], target: Target, callee: Value) -> Res { - if let Callee::Fn(hf) = f - && let Body::Direct(d) = &hf.body +fn call_host( + vm: &mut Vm, + f: &Callee, + this: Value, + args: &[Value], + target: Target, + callee: Value, +) -> Res { + if let Callee::Fn(f) = f + && let Body::Direct(body) = &f.body { - if vm.native_depth >= crate::vm::MAX_NATIVE_DEPTH || vm.stack_spent() { - return Err(vm.range_error("Maximum call stack size exceeded")); - } - let d = d.clone(); - let prev_gc_safe = vm.session_gc_safe; - vm.session_gc_safe = false; - vm.native_depth += 1; - let mut ctx = crate::session::HostCtx::new(vm); - let res = d( - &mut ctx, - crate::session::DirectArgs::with_this(Value::Undef, args), - ); - vm.native_depth -= 1; - vm.session_gc_safe = prev_gc_safe; - if vm.fatal.is_some() { - return Err(Value::Undef); - } - return match res { - Ok(v) => Ok(vm.sanitize_val(v.0)), - Err(e) => Err(vm.sanitize_val(e.0)), - }; + return crate::session::call_direct(vm, body.clone(), this, args, &target.label); } let takes = matches!(f, Callee::Fn(f) if f.takes_functions); let raw = template_raw(vm, args); @@ -1540,9 +1520,9 @@ fn hosted(vm: &Vm, id: Id) -> Option { if !std::ptr::fn_addr_eq(*f, host_native as crate::vm::NativeFn) { return None; } - let entry = vm.host.functions.get(*index as usize)?.as_ref()?; + let entry = vm.host.functions.get(*index as usize)?; match &entry.f { - Callee::Fn(f) if !entry.installed && entry.local_slot.is_none() => Some(f.clone()), + Callee::Fn(f) if !entry.installed => Some(f.clone()), _ => None, } } @@ -2434,58 +2414,13 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option Value { - wrap_direct_with_local(vm, f, None) -} - -/// Like [`wrap_direct`], tagging the entry with a session-local closure slot to release on GC sweep. -pub(crate) fn wrap_direct_with_local( - vm: &mut Vm, - f: HostFunction, - local_slot: Option<(u64, usize, u32)>, -) -> Value { - let constructible = f.constructible; - let label = f.name.to_string(); - let name = f.name().to_owned(); - let length = f.length; - let entry = FnEntry { - f: Callee::Fn(f), - label, - path: None, - owner: None, - installed: false, - reclaimable: true, - local_slot, - }; - let index = if let Some(slot) = vm.host.free_functions.pop() { - vm.host.functions[slot as usize] = Some(entry); - slot as usize - } else { - let idx = vm.host.functions.len(); - vm.host.functions.push(Some(entry)); - idx - }; + }); let made = native(vm, &name, length, host_native, Value::Num(index as f64)); if constructible && let Value::Obj(id) = made @@ -2496,54 +2431,11 @@ pub(crate) fn wrap_direct_with_local( made } -impl RunHost { - /// Reclaims a direct/local host function slot when its JS `Kind::Native` wrapper is swept by GC. - pub(crate) fn reclaim_function(&mut self, index: usize) { - if let Some(slot) = self.functions.get_mut(index) - && slot.as_ref().is_some_and(|e| e.reclaimable) - { - if let Some(entry) = slot.take() - && let Some((session_id, local_idx, generation)) = entry.local_slot - { - crate::session::release_local_fn(session_id, local_idx, generation); - } - self.free_functions.push(index as u32); - } - } -} - -pub(crate) fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res { +fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res { let Value::Num(index) = vm.native_data(callee) else { return Ok(Value::Undef); }; - let Some(entry) = vm - .host - .functions - .get(index as usize) - .and_then(|e| e.as_ref()) - else { - return Err(vm.type_error("host function is no longer alive")); - }; - if let Callee::Fn(f) = &entry.f - && let Body::Direct(d) = &f.body - { - if vm.native_depth > crate::vm::MAX_NATIVE_DEPTH || vm.stack_spent() { - return Err(vm.range_error("Maximum call stack size exceeded")); - } - let d = d.clone(); - let prev_gc_safe = vm.session_gc_safe; - vm.session_gc_safe = false; - let mut ctx = crate::session::HostCtx::new(vm); - let res = d(&mut ctx, crate::session::DirectArgs::with_this(this, args)); - vm.session_gc_safe = prev_gc_safe; - if vm.fatal.is_some() { - return Err(Value::Undef); - } - return match res { - Ok(v) => Ok(vm.sanitize_val(v.0)), - Err(e) => Err(vm.sanitize_val(e.0)), - }; - } + let entry = &vm.host.functions[index as usize]; if let Callee::Fn(f) = &entry.f && let Body::Lost(message) = &f.body { @@ -2572,7 +2464,7 @@ pub(crate) fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) path: entry.path.clone(), owner: entry.owner.clone(), }; - call_host(vm, &f, args, target, Value::Obj(callee)) + call_host(vm, &f, this, args, target, Value::Obj(callee)) } // ---------- modules ---------- diff --git a/rust/crates/psychoscript/src/host_function.rs b/rust/crates/psychoscript/src/host_function.rs index f2c4d88f..ae5f1638 100644 --- a/rust/crates/psychoscript/src/host_function.rs +++ b/rust/crates/psychoscript/src/host_function.rs @@ -743,19 +743,13 @@ impl std::ops::Deref for DurableCall { type SyncFn = dyn Fn(Vec, &Call) -> Returned + Send + Sync; type AsyncFn = dyn Fn(Vec, Call) -> BoxFuture<'static, HostResult> + Send + Sync; -type DirectFn = dyn Fn( - &mut crate::session::HostCtx<'_>, - crate::session::DirectArgs<'_>, - ) -> Result - + Send - + Sync; #[derive(Clone)] pub(crate) enum Body { Sync(Arc), Async(Arc), - /// A zero-copy synchronous host function operating directly on VM values via [`HostCtx`](crate::HostCtx). - Direct(Arc), + /// A synchronous function working on the program's values in place (`session.rs`). + Direct(Arc), /// A function a resumed run lost: calling it throws this message at the call. Lost(Arc), /// A live response's state, read with no call of the host (the reference's `hostGetter`). @@ -816,14 +810,16 @@ impl HostFunction { Self::with_body(Body::Sync(Arc::new(move |args, call| f(args, call).into()))) } - /// A zero-copy synchronous host function that reads and constructs VM values directly through - /// [`HostCtx`](crate::HostCtx) without deep-copying through [`HostValue`]. + /// A synchronous function that works on the program's own values, with no copy: it reads its receiver and + /// arguments ([`Args`](crate::Args)) and makes its value through the [`HostCtx`](crate::HostCtx) of the call, and + /// its `Err` is what the call throws. The values are the call's only (nothing collects them meanwhile). It runs + /// where the run computes, which for a run driven as a future may be the run's worker thread. pub fn direct(f: F) -> Self where - F: Fn( - &mut crate::session::HostCtx<'_>, - crate::session::DirectArgs<'_>, - ) -> Result + F: for<'a> Fn( + &mut crate::HostCtx<'a>, + crate::Args<'a>, + ) -> Result, crate::Val<'a>> + Send + Sync + 'static, diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index 29fc5c07..bb79ac1e 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -71,7 +71,7 @@ pub use runtime::{ Outcome, ProgramOptions, Run, Runtime, Translate, TranslateFunctions, TranslatePromises, }; pub use serde_json::Value as Json; -pub use session::{DirectArgs, FnHandle, HostCtx, Key, Session, Val, ValHandle}; +pub use session::{Args, HostCtx, Session, Val}; pub use snapshot::{Snapshot, SnapshotError, from_bytes, to_bytes}; pub use streaming::{HttpBody, StreamingResponse}; diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index 5826c841..2bd781ba 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -234,6 +234,8 @@ pub struct Program<'a> { worker: Option, /// The stretch of compute in progress continues on the worker. move_away: bool, + /// A session's run, which stays when it stops, for the session's next call (`session.rs`). + session: bool, } impl<'a> Program<'a> { @@ -259,6 +261,7 @@ impl<'a> Program<'a> { offload: false, worker: None, move_away: false, + session: false, } } @@ -268,9 +271,103 @@ impl<'a> Program<'a> { state: &Snapshot, ) -> Result { let running = restore(rt, state)?; + if running.vm.session.is_some() { + return Err(snapshot::SnapshotError::new( + "This state is a session's: restore it with Runtime::restore_session.", + )); + } Ok(Self::with(rt, State::Running(running))) } + /// A session's run of `code`, whose top level runs on the first [`Program::drive_session`]. + pub(crate) fn session(rt: &'a Runtime, code: Code<'_>, options: &ProgramOptions) -> Self { + let mut program = Self::new(rt, code, options); + program.session = true; + if let State::Running(r) = &mut program.state { + r.vm.session = Some(Box::default()); + } + program + } + + /// A session's run continuing from its saved state, checked against this runtime. + pub(crate) fn restore_session( + rt: &'a Runtime, + state: &Snapshot, + ) -> Result { + let running = restore(rt, state)?; + if running.vm.session.is_none() { + return Err(snapshot::SnapshotError::new( + "This state is a run's, not a session's: resume it with Runtime::resume.", + )); + } + let mut program = Self::with(rt, State::Running(running)); + program.session = true; + Ok(program) + } + + /// A session's run, unless it failed to compile. + pub(crate) fn session_vm(&mut self) -> Option<&mut Vm> { + match &mut self.state { + State::Running(r) => Some(&mut r.vm), + _ => None, + } + } + + /// Drives a session's run, as [`Program::run`] does, through its top level or a call `start` sets up, with the + /// run's limits counting from now; it stays for the next call. Returns how the top level or the call ended. + pub(crate) fn drive_session(&mut self, start: impl FnOnce(&mut Vm)) -> Outcome { + let probe = 0u8; + match &mut self.state { + State::Failed(outcome) => return (**outcome).clone(), + State::Running(r) => { + r.started = false; + r.timer_armed = false; + r.active_before = Duration::ZERO; + r.vm.start = Instant::now(); + r.vm.start_cpu_meter(); + r.vm.stack_base = &probe as *const u8 as usize; + r.vm.stack_budget = run::RUN_STACK_BUDGET; + if r.vm.fatal.is_none() { + start(&mut r.vm); + } + } + State::Away | State::Done => unreachable!("a session's run stays"), + } + let ended = exec::block_on(std::future::poll_fn(|cx| self.advance(cx))); + let State::Running(r) = &mut self.state else { + unreachable!("a session's run stays") + }; + // The top level ran: what runs next comes from the calls. + r.mark_resumed(); + match ended { + Some(Ok(RunOutcome::Done(outcome))) => outcome, + Some(_) => unreachable!("a session's run is neither suspended nor dropped"), + None => { + r.vm.fatal = Some((crate::DiagnosticKind::ExecutionFailure, CANNOT_WAIT.into())); + run::outcome(&mut r.vm, &r.code) + } + } + } + + /// A session's state between its calls, which [`Program::restore_session`] continues. + pub(crate) fn save_session(&self) -> Result { + let State::Running(r) = &self.state else { + return Err(SuspendError::other( + "The session failed to compile, so it can't be saved.".into(), + )); + }; + if let Some((_, message)) = &r.vm.fatal { + return Err(SuspendError::other(format!( + "The session failed, so it can't be saved: {message}" + ))); + } + let capture = snapshot::Capture { + code: &r.code, + active_ms: 0, + }; + snapshot::capture(&r.vm, &capture).map_err(|refusal| refused(&r.vm, refusal)) + } + /// What suspends this run from another thread. pub fn suspender(&self) -> Suspender { self.shared.watched.store(true, Ordering::Relaxed); @@ -303,12 +400,7 @@ impl<'a> Program<'a> { let State::Running(mut r) = std::mem::replace(&mut self.state, State::Done) else { unreachable!("only a running program waits") }; - r.vm.fatal = Some(( - crate::DiagnosticKind::ExecutionFailure, - "The run waits for asynchronous host work, which a synchronous run can't wait for on wasm32: drive it as a \ - future, with `execute_async` or `run_async`." - .into(), - )); + r.vm.fatal = Some((crate::DiagnosticKind::ExecutionFailure, CANNOT_WAIT.into())); let outcome = RunOutcome::Done(run::finish(*r)); self.shared.finish(&outcome); Ok(outcome) @@ -539,6 +631,13 @@ impl<'a> Program<'a> { } return Poll::Pending; } + // A session's run stays for its next call; an interruption leaves it failed. + if self.session { + let State::Running(r) = &mut self.state else { + unreachable!() + }; + return Poll::Ready(Ok(RunOutcome::Done(run::outcome(&mut r.vm, &r.code)))); + } let State::Running(r) = std::mem::replace(&mut self.state, State::Done) else { unreachable!() }; @@ -580,20 +679,7 @@ impl<'a> Program<'a> { match request { Some(max_bytes) => { let result = captured - .map_err(|refusal| match refusal { - Refusal::Running(calls) => SuspendError::running( - calls - .into_iter() - .map(|(call, path)| RunningCall { - key: r.vm.host.key(call), - path, - }) - .collect(), - ), - Refusal::Other(message) => SuspendError::other(format!( - "The run's state couldn't be saved: {message}" - )), - }) + .map_err(|refusal| refused(&r.vm, refusal)) .and_then(|state| { let size = snapshot::to_bytes(&state).len(); match max_bytes { @@ -692,6 +778,27 @@ impl Drop for Program<'_> { } } +const CANNOT_WAIT: &str = "The run waits for asynchronous host work, which a synchronous run can't wait for on \ + wasm32: drive it as a future, with `execute_async` or `run_async`."; + +/// Why the run's state couldn't be saved. +fn refused(vm: &Vm, refusal: Refusal) -> SuspendError { + match refusal { + Refusal::Running(calls) => SuspendError::running( + calls + .into_iter() + .map(|(call, path)| RunningCall { + key: vm.host.key(call), + path, + }) + .collect(), + ), + Refusal::Other(message) => { + SuspendError::other(format!("The run's state couldn't be saved: {message}")) + } + } +} + fn done_or_suspended(o: RunOutcome) -> Outcome { match o { RunOutcome::Done(o) => o, diff --git a/rust/crates/psychoscript/src/promise.rs b/rust/crates/psychoscript/src/promise.rs index 37cb1749..187c0979 100644 --- a/rust/crates/psychoscript/src/promise.rs +++ b/rust/crates/psychoscript/src/promise.rs @@ -329,14 +329,6 @@ impl Vm { } pub fn run_job(&mut self, job: Job) -> Result<(), Value> { - let prev_gc_safe = self.session_gc_safe; - self.session_gc_safe = false; - let r = self.run_job_inner(job); - self.session_gc_safe = prev_gc_safe; - r - } - - fn run_job_inner(&mut self, job: Job) -> Result<(), Value> { match job { Job::Thenable { promise, diff --git a/rust/crates/psychoscript/src/reach.rs b/rust/crates/psychoscript/src/reach.rs index 51a37596..d6a25612 100644 --- a/rust/crates/psychoscript/src/reach.rs +++ b/rust/crates/psychoscript/src/reach.rs @@ -32,16 +32,8 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { t.frame(f); } t.vals(vm.globals.iter()); - if let Some(roots) = vm.host_roots.as_deref() { - t.val(&roots.session_exports); - for slot in &roots.pinned { - if let Some(v) = &slot.value { - t.val(v); - } - } - for &a in &roots.host_atoms { - t.atom(a); - } + if let Some(s) = &vm.session { + t.vals(s.exports.iter()); } for (k, v) in &vm.global_map { t.atom(*k); @@ -77,7 +69,6 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { std.headers, std.array_buffer, std.data_view, - std.bigint, ] .into_iter() .chain(std.typed) diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index 7e8ccb02..4dc50d79 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -323,9 +323,12 @@ pub fn call_main(vm: &mut Vm) { /// The outcome of a run that ended: host work it left running is interrupted, then the result is copied out. pub fn finish(r: Running) -> Outcome { let Running { mut vm, code, .. } = r; - let code: &str = &code; vm.host.tasks.clear(); - let vm = &mut vm; + outcome(&mut vm, &code) +} + +/// The outcome of the run's program, or of a session's call, copied out of the VM: its result, warnings and logs. +pub fn outcome(vm: &mut Vm, code: &str) -> Outcome { if vm.outcome.is_some() { vm.heap_final(); } diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 5d5b65a6..d00ea14d 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -319,21 +319,24 @@ impl Runtime { Program::new(self, code.into(), options) } - /// Compiles and runs `code`'s top-level setup, returning a persistent [`Session`](crate::Session) for repeated - /// low-latency calls into guest functions. - pub fn session<'c>(&self, code: impl Into>) -> Result> { - crate::Session::start(self, code.into(), &ProgramOptions::default()) - } - - /// [`Runtime::session`] with [`ProgramOptions`]. - pub fn session_with<'c>( + /// Runs `code`'s top level, as a run of it would, and keeps the run as a [`Session`](crate::Session) to call the + /// functions in what the top level returns (an object of them), which stays in the run instead of crossing back: + /// the session, and how its top level ended (its logs; `null` for its value). A session whose top level failed + /// fails every call the same way. + pub fn session<'c>( &self, code: impl Into>, options: &ProgramOptions, - ) -> Result> { + ) -> (crate::Session<'_>, Outcome) { crate::Session::start(self, code.into(), options) } + /// A session continuing from the state [`Session::save`](crate::Session::save) gave, here or in another process + /// built from the same version; checked as [`Runtime::resume`] checks a suspended run's. + pub fn restore_session(&self, state: &Snapshot) -> Result, SnapshotError> { + crate::Session::restore(self, state) + } + /// Parses and compiles a program once, for [`Runtime::program`] and the `execute` methods to run many times /// without doing it again; or the diagnostic a run of it would fail with first (an empty program, a syntax /// error). Unsupported syntax still fails where it runs, as from source. A compiled program runs in any runtime. diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs index d731faee..b918246f 100644 --- a/rust/crates/psychoscript/src/session.rs +++ b/rust/crates/psychoscript/src/session.rs @@ -1,1770 +1,412 @@ -//! Persistent VM sessions and zero-copy synchronous host callbacks for low-latency embedders. -//! -//! A [`Session`] keeps a live VM across repeated calls into guest functions ([`Session::call_fn`]), -//! and [`HostFunction::direct`](crate::HostFunction::direct) lets synchronous host functions read -//! and build VM values directly through [`HostCtx`] without deep-copying through [`HostValue`](crate::HostValue). +//! A session: a run whose top level returns functions, kept to call them again and again, and saved between calls as +//! any run is. And the zero-copy host functions, [`HostFunction::direct`](crate::HostFunction::direct), which work on +//! the program's own values through a [`HostCtx`]. -use std::any::{Any, TypeId}; use std::borrow::Cow; -use std::cell::RefCell; use std::marker::PhantomData; -use std::rc::Rc; use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; -use rustc_hash::FxHashMap; - -use crate::object::{ - ACCESSOR, DEFAULT_FLAGS, ENUMERABLE, FIXED, FROZEN, Kind, NON_EXTENSIBLE, PENDING_STACK, - SPARSE, WRITABLE, -}; -use crate::ops::MAX_ARRAY_LEN; -use crate::run; -use crate::runtime::ProgramOptions; -use crate::strings::{Atom, SYM_LAST}; +use crate::accessors::Read; +use crate::object::Kind; +use crate::program::Program; use crate::value::Value; use crate::vm::Vm; -use crate::{Code, Diagnostic, DiagnosticKind, HostFunction, Limits, Outcome, Runtime}; - -/// Largest integer exactly representable in IEEE 754 f64 (2^53 - 1). -const MAX_SAFE_INT: f64 = 9_007_199_254_740_991.0; - -/// Default per-call microtask budget for [`Session::drain_jobs`]. -const DEFAULT_DRAIN_JOBS_BUDGET: usize = 4096; - -static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1); - -type LocalDirectFn = dyn Fn(&mut HostCtx<'_>, DirectArgs<'_>) -> Result; - -struct LocalFnSlot { - func: Option>, - generation: u32, -} +use crate::{Code, Data, Outcome, ProgramOptions, Runtime, Snapshot, SnapshotError, SuspendError}; +/// What a session's run keeps: the value its top level returned, once it has. #[derive(Default)] -struct SessionStore { - local_fns: Vec, - local_fns_free: Vec, - user_data: FxHashMap>>>, +pub(crate) struct SessionState { + pub exports: Option, } -thread_local! { - static SESSION_STORES: RefCell> = RefCell::new(FxHashMap::default()); -} - -#[inline(always)] -fn next_generation(generation: u32) -> u32 { - let next = generation.wrapping_add(1); - if next == 0 { 1 } else { next } -} - -/// Allocates a unique non-zero id for every `Vm` instance so typed `ValHandle`/`FnHandle` values -/// can never collide across standalone `Runtime::execute` runs or `Session` instances. -pub(crate) fn next_session_id() -> u64 { - let id = NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed); - if id == 0 { - NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed) - } else { - id - } -} - -fn alloc_session_store(id: u64) { - let _ = SESSION_STORES.try_with(|m| { - m.borrow_mut().insert(id, SessionStore::default()); - }); -} - -fn drop_session_store(id: u64) { - if id != 0 { - let removed = SESSION_STORES - .try_with(|m| m.borrow_mut().remove(&id)) - .ok() - .flatten(); - // Drop outside the RefCell borrow guard so nested Session drops cannot panic. - drop(removed); - } -} - -/// RAII guard ensuring a newly allocated session store is released if `Session::start` unwinds -/// or returns an error before constructing `Session`. -struct SessionInitGuard { - session_id: u64, - active: bool, -} - -impl SessionInitGuard { - fn new(session_id: u64) -> Self { - Self { - session_id, - active: true, - } - } - - fn disarm(&mut self) { - self.active = false; - } +/// A run kept to call the functions its top level returned ([`Runtime::session`]). Each call runs as a run does, with +/// the run's limits counting from the call, its async host calls driven to their end, and its value crossing back as +/// a run's result does; what the program keeps (its variables, its objects) stays from call to call. A failure that +/// ends a run (a limit, an interruption) leaves the session failed: every later call fails with it. Between calls it +/// saves as a suspended run does ([`Session::save`]), to continue in another process built from the same version. +pub struct Session<'a> { + program: Program<'a>, } -impl Drop for SessionInitGuard { - fn drop(&mut self) { - if self.active { - drop_session_store(self.session_id); +impl<'a> Session<'a> { + pub(crate) fn start( + rt: &'a Runtime, + code: Code<'_>, + options: &ProgramOptions, + ) -> (Self, Outcome) { + let mut program = Program::session(rt, code, options); + let outcome = program.drive_session(|_| {}); + if let (Err(failed), Some(vm)) = (&outcome.result, program.session_vm()) { + vm.fatal + .get_or_insert_with(|| (failed.kind.clone(), failed.message.to_run_text())); + } + (Self { program }, outcome) + } + + pub(crate) fn restore(rt: &'a Runtime, state: &Snapshot) -> Result { + Program::restore_session(rt, state).map(|program| Self { program }) + } + + /// Calls the function the top level returned as `name`, with `args` as its arguments and what the top level + /// returned as `this`, and runs until its value, awaited if a promise, has crossed back: its outcome, with what the + /// run logged since the last outcome. Jobs and host calls the call leaves pending go on in later calls. + pub fn call(&mut self, name: &str, args: &[Data]) -> Outcome { + self.program.drive_session(|vm| call(vm, name, args)) + } + + /// The session's state as of its last call, which [`Runtime::restore_session`] continues. Fails while a host call + /// that can't be saved is in flight (as [`Suspender::suspend`](crate::Suspender::suspend) does), or once the + /// session failed. The session goes on either way. + pub fn save(&self) -> Result { + self.program.save_session() + } +} + +/// Sets up the call: a frame that calls the function and settles a promise with how it ended (as `Promise.try` +/// does), whose value crosses back as a program's result does. +fn call(vm: &mut Vm, name: &str, args: &[Data]) { + let exports = vm + .session + .as_ref() + .and_then(|s| s.exports) + .unwrap_or(Value::Undef); + let key = vm + .atoms + .intern(&crate::strings::external_text(name.to_owned())); + let f = match exports { + Value::Obj(_) => match vm.op_read(&exports, key) { + Ok(Read::Value(f)) => Ok(f), + Ok(Read::Getter(g)) => vm.call(&g, exports, &[]), + Err(e) => Err(e), + }, + _ => Ok(Value::Undef), + }; + let f = match f { + Ok(f) if vm.is_callable(&f) => Ok(f), + Ok(_) => { + let message = format!("The session has no function {name}."); + Err(vm.type_error(&message)) + } + e => e, + }; + let f = match f { + Ok(f) => f, + Err(e) => { + vm.outcome.get_or_insert(Err(e)); + return; } - } -} - -fn store_local_fn(session_id: u64, f: Rc) -> Option<(usize, u32)> { - if session_id == 0 { - return None; - } - SESSION_STORES - .try_with(|m| { - let mut map = m.borrow_mut(); - let store = map.get_mut(&session_id)?; - if let Some(idx) = store.local_fns_free.pop() { - let slot = &mut store.local_fns[idx]; - slot.func = Some(f); - Some((idx, slot.generation)) - } else { - let idx = store.local_fns.len(); - store.local_fns.push(LocalFnSlot { - func: Some(f), - generation: 1, - }); - Some((idx, 1)) - } - }) - .ok() - .flatten() -} - -fn get_local_fn(session_id: u64, idx: usize, generation: u32) -> Option> { - if session_id == 0 || generation == 0 { - return None; - } - SESSION_STORES - .try_with(|m| { - m.borrow() - .get(&session_id) - .and_then(|s| s.local_fns.get(idx)) - .filter(|slot| slot.generation == generation) - .and_then(|slot| slot.func.as_ref()) - .cloned() - }) - .ok() - .flatten() -} - -/// Releases a session-local closure slot when its JS wrapper object is swept by GC. -pub(crate) fn release_local_fn(session_id: u64, idx: usize, generation: u32) { - if session_id == 0 || generation == 0 { - return; - } - let dropped = SESSION_STORES - .try_with(|m| { - let mut map = m.borrow_mut(); - let store = map.get_mut(&session_id)?; - let slot = store.local_fns.get_mut(idx)?; - if slot.generation != generation { - return None; - } - let old = slot.func.take()?; - slot.generation = next_generation(slot.generation); - store.local_fns_free.push(idx); - Some(old) - }) - .ok() - .flatten(); - // Drop outside the RefCell borrow guard in case captured state drops a Session. - drop(dropped); -} - -fn store_set_user_data(session_id: u64, val: T) { - if session_id == 0 { + }; + let args: Vec = args + .iter() + .map(|a| crate::convert::from_data(vm, a)) + .collect(); + let p = vm.new_promise(); + if crate::cross::program_result(vm, Value::Obj(p)).is_err() { return; } - let previous = SESSION_STORES - .try_with(|m| { - m.borrow_mut().get_mut(&session_id).and_then(|store| { - store - .user_data - .insert(TypeId::of::(), Rc::new(RefCell::new(Box::new(val)))) - }) - }) - .ok() - .flatten(); - // Drop replaced user data outside the RefCell borrow guard. - drop(previous); -} - -fn store_get_cell(session_id: u64) -> Option>>> { - if session_id == 0 { - return None; - } - SESSION_STORES - .try_with(|m| { - m.borrow() - .get(&session_id) - .and_then(|s| s.user_data.get(&TypeId::of::())) - .cloned() - }) - .ok() - .flatten() -} - -#[inline(always)] -fn normalize_hole(v: Value) -> Val { - if matches!(v, Value::Uninit) { - Val::UNDEFINED - } else { - Val(v) + let (u, z) = (Value::Undef, Value::Num(0.0)); + let entered = crate::promise::enter_settle( + vm, + u, + crate::promise::TRY, + Value::Obj(p), + u, + z, + f, + exports, + &args, + ); + match entered { + Ok(_) => vm.take_entered(), + Err(e) => vm.reject(p, e), } } -#[inline] -fn lookup_atom(vm: &Vm, name: &str) -> Option { - if !crate::strings::has_mark(name) { - vm.atoms.lookup(name) - } else { - let carrier = crate::strings::external_text(name.to_owned()); - vm.atoms.lookup(&carrier) - } -} +// ---------- direct host functions ---------- -#[inline] -fn lookup_global_by_key(vm: &Vm, key: Key) -> Option { - if let Some(v) = vm.global_map.get(&key.0).copied() { - return (!matches!(v, Value::Uninit)).then_some(Val(v)); - } - vm.global_names - .iter() - .position(|&a| a == key.0) - .and_then(|i| vm.globals.get(i).copied()) - .filter(|v| !matches!(v, Value::Uninit)) - .map(Val) -} - -#[inline] -fn lookup_global(vm: &Vm, name: &str) -> Option { - let atom = lookup_atom(vm, name)?; - lookup_global_by_key(vm, Key(atom)) -} - -/// A lightweight, `Copy` handle to a JS value inside a live VM. +/// A program value a [`HostFunction::direct`](crate::HostFunction::direct) call can use while it runs, and only then: +/// nothing collects the run's heap during a host call, and a `Val` can't outlive the call it was given to. +/// +/// ``` +/// use psychoscript::{HostFunction, Val}; +/// let first = HostFunction::direct(|ctx, args| ctx.get_index(args.get(0), 0)); +/// ``` /// -/// **GC lifetime:** An unpinned `Val` is only valid until the next JS call or GC step -/// ([`Session::call_fn`], [`Session::call_val`], [`HostCtx::call_fn_val`], [`Session::drain_jobs`], -/// [`Session::gc_step`], or [`Session::collect_garbage`]). To keep a value alive across calls or -/// collection cycles, pin it with [`Session::pin_val`] / [`HostCtx::pin_val`] ([`ValHandle`]) or -/// [`Session::pin_fn`] / [`HostCtx::pin_fn`] ([`FnHandle`]). +/// ```compile_fail +/// use psychoscript::{HostFunction, Val}; +/// static KEPT: std::sync::Mutex>> = std::sync::Mutex::new(None); +/// let keeps = HostFunction::direct(|_, args| { +/// *KEPT.lock().unwrap() = Some(args.get(0)); +/// Ok(Val::undefined()) +/// }); +/// ``` #[derive(Clone, Copy, Debug)] -pub struct Val(pub(crate) Value); - -impl Val { - pub const UNDEFINED: Val = Val(Value::Undef); - pub const NULL: Val = Val(Value::Null); - - #[inline(always)] - pub const fn bool(b: bool) -> Self { - Val(Value::Bool(b)) - } - - #[inline(always)] - pub const fn num(n: f64) -> Self { - Val(Value::Num(n)) - } +pub struct Val<'a> { + pub(crate) v: Value, + /// Invariant in `'a`, so a value of one call can't be kept for another. + scope: PhantomData &'a ()>, +} - #[inline(always)] - pub const fn is_undefined(self) -> bool { - matches!(self.0, Value::Undef | Value::Uninit) +impl<'a> Val<'a> { + pub(crate) fn of(v: Value) -> Self { + Val { + v: match v { + Value::Uninit => Value::Undef, + v => v, + }, + scope: PhantomData, + } } - #[inline(always)] - pub const fn is_null(self) -> bool { - matches!(self.0, Value::Null) + pub fn undefined() -> Self { + Self::of(Value::Undef) } - #[inline(always)] - pub const fn is_nullish(self) -> bool { - matches!(self.0, Value::Undef | Value::Uninit | Value::Null) + pub fn null() -> Self { + Self::of(Value::Null) } - #[inline(always)] - pub const fn is_bool(self) -> bool { - matches!(self.0, Value::Bool(_)) + pub fn bool(b: bool) -> Self { + Self::of(Value::Bool(b)) } - #[inline(always)] - pub const fn is_num(self) -> bool { - matches!(self.0, Value::Num(_)) + pub fn num(n: f64) -> Self { + Self::of(Value::Num(n)) } - #[inline(always)] - pub const fn is_str(self) -> bool { - matches!(self.0, Value::Str(_)) + pub fn is_undefined(self) -> bool { + matches!(self.v, Value::Undef) } - #[inline(always)] - pub const fn is_obj_ref(self) -> bool { - matches!(self.0, Value::Obj(_)) + pub fn is_null(self) -> bool { + matches!(self.v, Value::Null) } - #[inline(always)] - pub const fn as_bool(self) -> Option { - match self.0 { + pub fn as_bool(self) -> Option { + match self.v { Value::Bool(b) => Some(b), _ => None, } } - #[inline(always)] - pub const fn as_f64(self) -> Option { - match self.0 { + pub fn as_f64(self) -> Option { + match self.v { Value::Num(n) => Some(n), _ => None, } } - - /// Returns the integer value when this is a finite whole number within `0..=u32::MAX`. - #[inline(always)] - pub fn as_u32(self) -> Option { - match self.0 { - Value::Num(n) - if n.is_finite() && n.fract() == 0.0 && (0.0..=u32::MAX as f64).contains(&n) => - { - Some(n as u32) - } - _ => None, - } - } - - /// Returns the integer value when this is a finite whole number within `i32::MIN..=i32::MAX`. - #[inline(always)] - pub fn as_i32(self) -> Option { - match self.0 { - Value::Num(n) - if n.is_finite() - && n.fract() == 0.0 - && (i32::MIN as f64..=i32::MAX as f64).contains(&n) => - { - Some(n as i32) - } - _ => None, - } - } - - /// Returns the integer value when this is a finite whole number within IEEE 754 safe integer range. - #[inline(always)] - pub fn as_i64(self) -> Option { - match self.0 { - Value::Num(n) if n.is_finite() && n.fract() == 0.0 && n.abs() <= MAX_SAFE_INT => { - Some(n as i64) - } - _ => None, - } - } -} - -impl From for Val { - #[inline(always)] - fn from(b: bool) -> Self { - Val::bool(b) - } -} - -impl From for Val { - #[inline(always)] - fn from(n: f64) -> Self { - Val::num(n) - } -} - -impl From for Val { - #[inline(always)] - fn from(n: u32) -> Self { - Val::num(n as f64) - } -} - -impl From for Val { - #[inline(always)] - fn from(n: i32) -> Self { - Val::num(n as f64) - } -} - -impl From for Val { - #[inline(always)] - fn from(n: i64) -> Self { - Val::num(n as f64) - } -} - -impl From for Val { - #[inline(always)] - fn from(n: usize) -> Self { - Val::num(n as f64) - } -} - -/// A pre-interned, permanently GC-rooted property key for zero-allocation object reads and writes. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Key(pub(crate) Atom); - -impl Key { - #[inline(always)] - pub const fn raw(self) -> u32 { - self.0 - } -} - -/// A GC-rooted, session-scoped, generation-tagged handle to a callable guest function inside a [`Session`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct FnHandle { - session_id: u64, - idx: u32, - generation: u32, } -impl FnHandle { - #[inline(always)] - pub const fn raw(self) -> u64 { - ((self.generation as u64) << 32) | (self.idx as u64) - } -} - -/// A GC-rooted, session-scoped, generation-tagged handle to an arbitrary JS value inside a [`Session`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct ValHandle { - session_id: u64, - idx: u32, - generation: u32, -} - -impl ValHandle { - #[inline(always)] - pub const fn raw(self) -> u64 { - ((self.generation as u64) << 32) | (self.idx as u64) - } -} - -/// Borrowed arguments passed to a [`HostFunction::direct`](crate::HostFunction::direct) callback. +/// The receiver and arguments of a direct host function's call. #[derive(Clone, Copy)] -pub struct DirectArgs<'a> { +pub struct Args<'a> { this: Value, args: &'a [Value], } -impl<'a> DirectArgs<'a> { - #[inline(always)] - pub(crate) fn with_this(this: Value, args: &'a [Value]) -> Self { - Self { this, args } - } - - /// The `this` receiver of the call (with `Value::Uninit` normalized to [`Val::UNDEFINED`]). - #[inline(always)] - pub fn this(&self) -> Val { - normalize_hole(self.this) +impl<'a> Args<'a> { + pub fn this(&self) -> Val<'a> { + Val::of(self.this) } - #[inline(always)] pub fn len(&self) -> usize { self.args.len() } - #[inline(always)] pub fn is_empty(&self) -> bool { self.args.is_empty() } - /// The argument at `index`, or [`Val::UNDEFINED`] if out of range. - #[inline(always)] - pub fn get(&self, index: usize) -> Val { - normalize_hole(self.args.get(index).copied().unwrap_or(Value::Undef)) + /// The argument at `index`; undefined past the last. + pub fn get(&self, index: usize) -> Val<'a> { + Val::of(self.args.get(index).copied().unwrap_or(Value::Undef)) } } -/// Borrowed view into a live VM for zero-copy value inspection and construction. +/// The run a direct host function's call is in: it reads and makes the program's values in place, as the program's +/// own code would. pub struct HostCtx<'a> { vm: &'a mut Vm, + /// Where the host's time in the call started; the program's time in a call the host makes is the program's. + span: Option, } -impl<'a> HostCtx<'a> { - #[inline(always)] - pub(crate) fn new(vm: &'a mut Vm) -> Self { - Self { vm } - } - - /// Interns a property name WITHOUT permanently rooting it in `Vm::host_atoms`. - #[inline] - pub(crate) fn intern_key(&mut self, name: &str) -> Key { - let atom = if !crate::strings::has_mark(name) { - self.vm.atoms.intern(name) - } else { - let carrier = crate::strings::external_text(name.to_owned()); - self.vm.atoms.intern(&carrier) - }; - Key(atom) - } - - /// Interns a property name once and permanently roots it for the lifetime of the VM so GC never - /// reclaims it. Ideal for fixed property/event keys cached by the embedder. - #[inline] - pub fn key(&mut self, name: &str) -> Key { - let key = self.intern_key(name); - let roots = self.vm.host_roots_mut(); - if roots.host_atom_set.insert(key.0) { - roots.host_atoms.push(key.0); - } - key - } - - /// Returns the decoded UTF-8 text of an interned [`Key`], or `""` if the key is invalid. - #[inline] - pub fn key_name(&self, key: Key) -> Cow<'_, str> { - self.vm - .atoms - .text_opt(key.0) - .map(crate::strings::host_text) - .unwrap_or(Cow::Borrowed("")) - } - - /// Whether `v` is a live JS Array. - #[inline(always)] - pub fn is_array(&self, v: Val) -> bool { - let Value::Obj(id) = v.0 else { - return false; - }; - self.vm - .live_obj(id) - .is_some_and(|o| matches!(o.kind, Kind::Array(_))) - } - - /// Whether `v` is a live non-null, non-array, non-callable, non-bytes JS object. - #[inline(always)] - pub fn is_object(&self, v: Val) -> bool { - let Value::Obj(id) = v.0 else { - return false; - }; - let Some(obj) = self.vm.live_obj(id) else { - return false; - }; - !obj.is_callable() && !matches!(obj.kind, Kind::Array(_) | Kind::Bytes(_)) - } - - /// Whether `v` is a live plain ordinary JS object (`{}`). - #[inline(always)] - pub fn is_plain_object(&self, v: Val) -> bool { - let Value::Obj(id) = v.0 else { - return false; - }; - self.vm - .live_obj(id) - .is_some_and(|o| matches!(o.kind, Kind::Ordinary)) - } - - /// Whether `v` is a live callable JS function. - #[inline(always)] - pub fn is_fn(&self, v: Val) -> bool { - let Value::Obj(id) = v.0 else { - return false; - }; - self.vm.live_obj(id).is_some_and(|o| o.is_callable()) - } - - /// Whether `v` is a live `Uint8Array`, `Buffer`, `ArrayBuffer`, or other typed array. - #[inline(always)] - pub fn is_bytes(&self, v: Val) -> bool { - let Value::Obj(id) = v.0 else { - return false; - }; - self.vm - .live_obj(id) - .is_some_and(|o| matches!(o.kind, Kind::Bytes(_))) - } - - /// Human-readable JS type name of `v` for diagnostics. - pub fn type_name(&self, v: Val) -> &'static str { - match v.0 { - Value::Undef | Value::Uninit => "undefined", - Value::Null => "null", - Value::Bool(_) => "boolean", - Value::Num(_) => "number", - Value::Str(_) => "string", - Value::Sym(_) => "symbol", - Value::Big(_) => "bigint", - Value::Obj(id) => { - let Some(obj) = self.vm.live_obj(id) else { - return "undefined"; - }; - if obj.is_callable() { - "function" - } else { - match &obj.kind { - Kind::Array(_) => "array", - Kind::Bytes(b) => b.elem.name(), - _ => "object", - } - } - } - } - } - - /// Returns the heap object id of `v`, if it is a live heap object. - #[inline(always)] - pub fn obj_id(&self, v: Val) -> Option { - let Value::Obj(id) = v.0 else { - return None; - }; - self.vm.live_obj(id).map(|_| id) - } +pub(crate) type DirectFn = + dyn for<'a> Fn(&mut HostCtx<'a>, Args<'a>) -> Result, Val<'a>> + Send + Sync; - /// Whether `v` is a live frozen JS object (`Object.freeze(...)`). - #[inline(always)] - pub fn obj_is_frozen(&self, v: Val) -> bool { - let Value::Obj(id) = v.0 else { - return false; - }; - self.vm.live_obj(id).is_some_and(|o| o.flags & FROZEN != 0) - } - - /// Borrows a JS string value directly as `&str` when it is live, well-formed UTF-8 without carrier marks. - #[inline(always)] - pub fn as_str(&self, v: Val) -> Option<&str> { - let Value::Str(s) = v.0 else { - return None; - }; - let text = self.vm.atoms.get_opt(s)?; - if crate::strings::has_mark(text) { - None - } else { - Some(text) - } - } - - /// Converts a JS string value to an owned UTF-8 `String` (decoding any carrier marks lossily). - pub fn to_string_lossy(&self, v: Val) -> Option { - let Value::Str(s) = v.0 else { - return None; - }; - let text = self.vm.atoms.get_opt(s)?; - Some(crate::strings::host_text(text).into_owned()) - } +/// Calls a direct host function as a synchronous one is called (`host::call_host`): it is the run's synchronous call +/// in progress, and the host's time is not the program's. +pub(crate) fn call_direct( + vm: &mut Vm, + f: Arc, + this: Value, + args: &[Value], + label: &str, +) -> crate::vm::Res { + let call = vm.host.next_call(); + vm.host.enter_sync(call, label.to_owned()); + let span = vm.host_span(); + let mut ctx = HostCtx { vm, span }; + let r = f(&mut ctx, Args { this, args }); + let HostCtx { vm, span } = ctx; + vm.end_host_span(span); + vm.host.leave_sync(); + r.map(|v| v.v).map_err(|e| e.v) +} - /// Formats a JS value purely from heap inspection without ever invoking user JS - /// (`toString`, `valueOf`, `[Symbol.toPrimitive]`, or property getters). - fn format_val_safe(&self, v: Value) -> String { - match v { - Value::Undef | Value::Uninit => "undefined".to_owned(), - Value::Null => "null".to_owned(), - Value::Bool(b) => if b { "true" } else { "false" }.to_owned(), - Value::Num(n) => crate::value::num_to_string(n), - Value::Str(s) => self +impl<'a> HostCtx<'a> { + fn key(&mut self, name: &str) -> crate::strings::Atom { + match crate::strings::has_mark(name) { + false => self.vm.atoms.intern(name), + true => self .vm .atoms - .get_opt(s) - .map(|t| crate::strings::host_text(t).into_owned()) - .unwrap_or_default(), - Value::Sym(s) => crate::ops::symbol_text(s).to_owned(), - Value::Big(id) => format!("{}n", self.vm.big_text(id)), - Value::Obj(id) => { - let Some(obj) = self.vm.live_obj(id) else { - return "undefined".to_owned(); - }; - let name = self.read_data_str_prop(id, self.vm.names.name); - let message = self.read_data_str_prop(id, self.vm.names.message); - let is_err = matches!(obj.kind, Kind::Error(_)); - if is_err || message.is_some() { - let name = name.unwrap_or_else(|| "Error".to_owned()); - let msg = message.unwrap_or_default(); - return match (name.is_empty(), msg.is_empty()) { - (false, false) => format!("{name}: {msg}"), - (false, true) => name, - (true, false) => msg, - (true, true) => "Error".to_owned(), - }; - } - format!("[{}]", self.type_name(Val(v))) - } + .intern(&crate::strings::external_text(name.to_owned())), } } - /// Reads a primitive data property along the prototype chain (bounded depth) without invoking getters. - fn read_data_str_prop(&self, mut id: u32, key: Atom) -> Option { - for _ in 0..16 { - let obj = self.vm.live_obj(id)?; - if let Some(p) = obj.props.prop(key) { - if p.flags & ACCESSOR != 0 { - return None; - } - return match p.value() { - Value::Str(s) => self - .vm - .atoms - .get_opt(s) - .map(|t| crate::strings::host_text(t).into_owned()), - Value::Num(n) => Some(crate::value::num_to_string(n)), - Value::Bool(b) => Some(if b { "true" } else { "false" }.to_owned()), - _ => None, - }; - } - let Some(proto) = obj.proto else { - break; - }; - id = proto; - } - None + /// `typeof v`. + pub fn type_of(&self, v: Val<'a>) -> &'static str { + self.vm.type_of(&v.v) } - /// Allocates a JS string directly in the VM's string arena. - #[inline] - pub fn new_str(&mut self, s: &str) -> Val { - if !crate::strings::has_mark(s) { - Val(self.vm.string_of_str(s)) - } else { - Val(self - .vm - .string_val(crate::strings::external_text(s.to_owned()))) - } + pub fn is_array(&self, v: Val<'a>) -> bool { + matches!(v.v, Value::Obj(id) if matches!(self.vm.heap[id as usize].kind, Kind::Array(_))) } - /// Builds an object with its initial fields in one allocation, deduplicating repeated keys - /// (last value wins) so `Object.keys` never observes duplicate entries. - #[inline] - pub fn new_object_with(&mut self, fields: &[(Key, Val)]) -> Val { - let proto = self.vm.realm.object_proto; - let mut props = crate::object::Props::default(); - if !fields.is_empty() { - props.reserve_exact(fields.len()); - } - for &(k, v) in fields { - if self.vm.atoms.text_opt(k.0).is_none() { - continue; - } - let v = self.vm.sanitize_val(v.0); - self.vm.gc_shade_atom(k.0); - self.vm.gc_shade(v); - props.insert(k.0, v, DEFAULT_FLAGS); - } - let prop_count = props.items.len() as u64; - if prop_count > 0 { - self.vm - .charge_heap(crate::heap::PROPERTY_BYTES * prop_count); - } - let mut obj = crate::object::Obj::new(Some(proto), Kind::Ordinary); - obj.props = props; - let id = self.vm.alloc(obj); - Val(Value::Obj(id)) - } - - /// Creates a plain JS object with property storage pre-reserved for `capacity` fields. - #[inline] - pub fn new_object(&mut self, capacity: usize) -> Val { - let id = self.vm.new_object(); - if capacity > 0 - && let Some(obj) = self.vm.live_obj_mut(id) - { - obj.props.reserve_exact(capacity); - } - Val(Value::Obj(id)) - } - - /// Appends or updates a property on a JS object while preserving object invariants (no duplicate - /// keys, respects frozen/non-writable/non-extensible flags, and charges the heap meter). - #[inline] - pub fn obj_push_new(&mut self, obj: Val, key: Key, val: Val) { - self.obj_set(obj, key, val); - } - - /// Sets a property on an object by pre-interned [`Key`], respecting JS object invariants - /// (frozen/non-extensible/non-writable guards, resetting stale `ACCESSOR`/`PENDING_STACK` flags, - /// and array index synchronization). - #[inline] - pub fn obj_set(&mut self, obj: Val, key: Key, val: Val) { - let Value::Obj(id) = obj.0 else { - return; - }; - if self.vm.atoms.text_opt(key.0).is_none() { - return; - } - let Some(target) = self.vm.live_obj(id) else { - return; - }; - let obj_flags = target.flags; - if obj_flags & FROZEN != 0 { - return; - } - let is_array = matches!(target.kind, Kind::Array(_)); - let val = self.vm.sanitize_val(val.0); - self.vm.gc_shade_atom(key.0); - self.vm.gc_shade(val); - - if is_array { - if key.0 == self.vm.names.length { - return; - } - if let Some(index) = self.vm.atoms.index(key.0) { - let i = index as usize; - let lk = self.vm.names.length; - if obj_flags & SPARSE == 0 { - let cur_len = match &self.vm.heap[id as usize].kind { - Kind::Array(items) => items.len(), - _ => 0, - }; - if i < cur_len { - if let Some(o) = self.vm.live_obj_mut(id) - && let Kind::Array(items) = &mut o.kind - { - items[i] = val; - } - return; - } - if obj_flags & NON_EXTENSIBLE != 0 { - return; - } - if i < MAX_ARRAY_LEN { - let grown = i + 1 - cur_len; - if let Some(o) = self.vm.live_obj_mut(id) - && let Kind::Array(items) = &mut o.kind - { - items.resize(i, Value::Uninit); - items.push(val); - } - self.vm - .charge_heap(crate::heap::ELEMENT_BYTES * grown as u64); - return; - } - let len = cur_len.max(i + 1); - if let Some(o) = self.vm.live_obj_mut(id) { - o.flags |= SPARSE; - o.props.insert(key.0, val, DEFAULT_FLAGS); - o.props.insert(lk, Value::Num(len as f64), 0); - } - self.vm.charge_heap(crate::heap::PROPERTY_BYTES); - return; - } - let cur_len = self.vm.array_len(id); - if let Some(o) = self.vm.live_obj_mut(id) { - if let Kind::Array(items) = &mut o.kind - && i < items.len() - { - items[i] = val; - return; - } - if let Some(pos) = o.props.find(key.0) { - let pf = o.props.items[pos].flags; - if pf & ACCESSOR != 0 { - if pf & FIXED != 0 { - return; - } - o.props.items[pos].set_value(val); - o.props.items[pos].flags = DEFAULT_FLAGS; - } else { - if pf & WRITABLE == 0 { - return; - } - o.props.items[pos].set_value(val); - o.props.items[pos].flags = pf & !PENDING_STACK; - } - return; - } - if obj_flags & NON_EXTENSIBLE != 0 { - return; - } - o.props.push_new(key.0, val, DEFAULT_FLAGS); - if i >= cur_len { - o.props.insert(lk, Value::Num((i + 1) as f64), 0); - } - } - self.vm.charge_heap(crate::heap::PROPERTY_BYTES); - return; - } - } - - let mut added = false; - if let Some(o) = self.vm.live_obj_mut(id) { - if let Some(pos) = o.props.find(key.0) { - let pf = o.props.items[pos].flags; - if pf & ACCESSOR != 0 { - if pf & FIXED != 0 { - return; - } - o.props.items[pos].set_value(val); - o.props.items[pos].flags = DEFAULT_FLAGS; - } else { - if pf & WRITABLE == 0 { - return; - } - o.props.items[pos].set_value(val); - o.props.items[pos].flags = pf & !PENDING_STACK; - } - } else { - if o.flags & NON_EXTENSIBLE != 0 { - return; - } - o.props.push_new(key.0, val, DEFAULT_FLAGS); - added = true; - } - } - if added { - self.vm.charge_heap(crate::heap::PROPERTY_BYTES); - } - } - - /// Sets a property on an object by string name without permanently rooting the key atom in - /// `Vm::host_atoms`. - #[inline] - pub fn obj_set_str(&mut self, obj: Val, name: &str, val: Val) { - let key = self.intern_key(name); - self.obj_set(obj, key, val); - } - - /// Reads an own data property on an object by pre-interned [`Key`]. - #[inline(always)] - pub fn obj_get(&self, obj: Val, key: Key) -> Option { - let Value::Obj(id) = obj.0 else { - return None; - }; - let o = self.vm.live_obj(id)?; - let prop = o.props.prop(key.0)?; - if prop.flags & ACCESSOR != 0 { - return None; - } - Some(Val(prop.value())) - } - - /// Reads an own numeric property on an object by pre-interned [`Key`]. - #[inline(always)] - pub fn obj_get_f64(&self, obj: Val, key: Key) -> Option { - self.obj_get(obj, key).and_then(Val::as_f64) - } - - /// Reads an own string property on an object by pre-interned [`Key`]. - #[inline(always)] - pub fn obj_get_str(&self, obj: Val, key: Key) -> Option<&str> { - let v = self.obj_get(obj, key)?; - self.as_str(v) - } - - /// Visits every own enumerable string-keyed data property of `obj` in insertion order - /// (skipping symbol keys and accessor properties). - #[inline] - pub fn obj_for_each(&self, obj: Val, mut f: impl FnMut(&str, Val)) -> bool { - let Value::Obj(id) = obj.0 else { - return false; - }; - let Some(o) = self.vm.live_obj(id) else { - return false; - }; - for prop in o.props.items.iter() { - if prop.key <= SYM_LAST || prop.flags & ENUMERABLE == 0 || prop.flags & ACCESSOR != 0 { - continue; - } - let Some(raw) = self.vm.atoms.text_opt(prop.key) else { - continue; - }; - if !crate::strings::has_mark(raw) { - f(raw, Val(prop.value())); - } else { - let decoded = crate::strings::host_text(raw); - f(&decoded, Val(prop.value())); - } + /// A string's text, borrowed from the run; an unpaired surrogate reads as U+FFFD. + pub fn text(&self, v: Val<'a>) -> Option> { + match v.v { + Value::Str(s) => Some(crate::strings::host_text(self.vm.text(s))), + _ => None, } - true } - /// Visits every own enumerable string-keyed data property of `obj` in insertion order, - /// passing `Some(Key)` when the property key is permanently rooted via [`HostCtx::key`] and - /// `None` for unrooted dynamic keys (so an unrooted `Key` can never escape). - #[inline] - pub fn obj_for_each_key(&self, obj: Val, mut f: impl FnMut(Option, &str, Val)) -> bool { - let Value::Obj(id) = obj.0 else { - return false; - }; - let Some(o) = self.vm.live_obj(id) else { - return false; - }; - for prop in o.props.items.iter() { - if prop.key <= SYM_LAST || prop.flags & ENUMERABLE == 0 || prop.flags & ACCESSOR != 0 { - continue; - } - let Some(raw) = self.vm.atoms.text_opt(prop.key) else { - continue; - }; - let rooted_key = self - .vm - .host_roots - .as_deref() - .is_some_and(|r| r.host_atom_set.contains(&prop.key)) - .then_some(Key(prop.key)); - if !crate::strings::has_mark(raw) { - f(rooted_key, raw, Val(prop.value())); - } else { - let decoded = crate::strings::host_text(raw); - f(rooted_key, &decoded, Val(prop.value())); - } + /// The bytes of a typed array, an `ArrayBuffer` or a `DataView`, in place. + pub fn bytes(&self, v: Val<'a>) -> Option<&[u8]> { + match v.v { + Value::Obj(id) => match &self.vm.heap[id as usize].kind { + Kind::Bytes(b) => Some(b.data(self.vm)), + _ => None, + }, + _ => None, } - true } - /// Creates a dense JS array pre-allocated for `capacity` elements. - #[inline] - pub fn new_array(&mut self, capacity: usize) -> Val { - Val(self.vm.new_array(Vec::with_capacity(capacity))) - } - - /// Appends an element to a JS array (handles both dense and sparse arrays, guards frozen / - /// non-extensible / max JS array length, and charges the heap meter). - #[inline] - pub fn array_push(&mut self, arr: Val, val: Val) { - let Value::Obj(id) = arr.0 else { - return; - }; - let Some(obj) = self.vm.live_obj(id) else { - return; - }; - if !matches!(obj.kind, Kind::Array(_)) || obj.flags & (FROZEN | NON_EXTENSIBLE) != 0 { - return; - } - let len = self.vm.array_len(id); - if len >= u32::MAX as usize { - return; - } - let is_sparse = obj.flags & SPARSE != 0; - let val = self.vm.sanitize_val(val.0); - self.vm.gc_shade(val); - if !is_sparse { - if len < MAX_ARRAY_LEN { - if let Some(o) = self.vm.live_obj_mut(id) - && let Kind::Array(items) = &mut o.kind - { - items.push(val); + /// [`HostCtx::bytes`], to write. + pub fn bytes_mut(&mut self, v: Val<'a>) -> Option<&mut [u8]> { + match v.v { + Value::Obj(id) => match &self.vm.heap[id as usize].kind { + Kind::Bytes(b) => { + let b = **b; + Some(b.data_mut(self.vm)) } - self.vm.charge_heap(crate::heap::ELEMENT_BYTES); - return; - } - let key = self.intern_key(&len.to_string()).0; - let lk = self.vm.names.length; - if let Some(o) = self.vm.live_obj_mut(id) { - o.flags |= SPARSE; - o.props.insert(key, val, DEFAULT_FLAGS); - o.props.insert(lk, Value::Num((len + 1) as f64), 0); - } - self.vm.charge_heap(crate::heap::PROPERTY_BYTES); - return; - } - let key = self.intern_key(&len.to_string()).0; - let lk = self.vm.names.length; - if let Some(o) = self.vm.live_obj_mut(id) { - o.props.insert(key, val, DEFAULT_FLAGS); - o.props.insert(lk, Value::Num((len + 1) as f64), 0); - } - self.vm.charge_heap(crate::heap::PROPERTY_BYTES); - } - - /// Returns the logical length of a JS array (handles both dense and sparse arrays). - #[inline(always)] - pub fn array_len(&self, arr: Val) -> Option { - let Value::Obj(id) = arr.0 else { - return None; - }; - let obj = self.vm.live_obj(id)?; - if !matches!(obj.kind, Kind::Array(_)) { - return None; - } - Some(self.vm.array_len(id)) - } - - /// Reads an element from a JS array without copying the array (handles both dense and sparse arrays). - /// Holes within `0..len` read as [`Val::UNDEFINED`]; out-of-range indices return `None`. - #[inline] - pub fn array_get(&self, arr: Val, index: usize) -> Option { - let Value::Obj(id) = arr.0 else { - return None; - }; - let obj = self.vm.live_obj(id)?; - let Kind::Array(items) = &obj.kind else { - return None; - }; - if obj.flags & SPARSE == 0 { - return items.get(index).copied().map(normalize_hole); - } - let len = self.vm.array_len(id); - if index >= len { - return None; - } - if let Some(&v) = items.get(index) - && !matches!(v, Value::Uninit) - { - return Some(Val(v)); - } - let key_str = index.to_string(); - if let Some(atom) = self.vm.atoms.lookup(&key_str) - && let Some(prop) = obj.props.prop(atom) - && prop.flags & ACCESSOR == 0 - { - return Some(normalize_hole(prop.value())); - } - Some(Val::UNDEFINED) - } - - /// Calls `f` with each element of a JS array. - /// - /// For dense arrays, visits every slot `0..len` without allocating (holes yield - /// [`Val::UNDEFINED`]). For sparse arrays, visits every populated data element in ascending - /// index order (dense prefix + sparse tail, skipping accessor properties) in O(populated) time. - #[inline] - pub fn array_for_each(&self, arr: Val, mut f: impl FnMut(Val)) -> bool { - let Value::Obj(id) = arr.0 else { - return false; - }; - let Some(obj) = self.vm.live_obj(id) else { - return false; - }; - let Kind::Array(items) = &obj.kind else { - return false; - }; - if obj.flags & SPARSE == 0 { - for &item in items { - f(normalize_hole(item)); - } - return true; - } - for &item in items { - if !matches!(item, Value::Uninit) { - f(Val(item)); - } - } - let mut tail: Vec<(usize, Value)> = obj - .props - .items - .iter() - .filter(|p| p.flags & ACCESSOR == 0) - .filter_map(|p| Some((self.vm.atoms.index(p.key)? as usize, p.value()))) - .collect(); - tail.sort_unstable_by_key(|(i, _)| *i); - for (_, item) in tail { - if !matches!(item, Value::Uninit) { - f(Val(item)); - } - } - true - } - - /// Borrows the raw bytes of a `Uint8Array`, `Buffer`, `ArrayBuffer`, or other typed array. - #[inline] - pub fn as_bytes(&self, v: Val) -> Option<&[u8]> { - let Value::Obj(id) = v.0 else { - return None; - }; - let obj = self.vm.live_obj(id)?; - match &obj.kind { - Kind::Bytes(b) => Some(b.data(self.vm)), + _ => None, + }, _ => None, } } - /// Creates a new `Uint8Array` holding a copy of `bytes`. - #[inline] - pub fn new_bytes(&mut self, bytes: &[u8]) -> Val { - Val(crate::builtins::bytes::new_bytes( - self.vm, - bytes.to_vec(), - false, - )) - } - - /// Wraps a synchronous direct [`HostFunction`] into a callable JS function value inside this VM. - #[inline] - pub fn new_direct_fn(&mut self, f: HostFunction) -> Val { - Val(crate::host::wrap_direct(self.vm, f)) - } - - /// Wraps a thread-local (`!Send`) direct callback into a callable JS function owned by this [`Session`]. - /// Reclaimed automatically when the returned JS function becomes unreachable and is swept by GC. - pub fn new_local_fn(&mut self, name: &str, f: F) -> Val - where - F: Fn(&mut HostCtx<'_>, DirectArgs<'_>) -> Result + 'static, - { - let session_id = self.vm.session_id; - let slot_info = store_local_fn(session_id, Rc::new(f)); - let local_slot = slot_info.map(|(i, g)| (session_id, i, g)); - let hf = HostFunction::direct(move |ctx, args| { - let Some((i, generation)) = slot_info else { - return Err(ctx.error("local host function requires an active Session")); - }; - if ctx.vm.session_id != session_id { - return Err(ctx.error("session local host function called from wrong Session")); - } - let Some(func) = get_local_fn(session_id, i, generation) else { - return Err(ctx.error("session local host function is no longer alive")); - }; - func(ctx, args) + pub fn string(&mut self, s: &str) -> Val<'a> { + Val::of(match crate::strings::has_mark(s) { + false => self.vm.string_of_str(s), + true => self + .vm + .string_val(crate::strings::external_text(s.to_owned())), }) - .named(name); - Val(crate::host::wrap_direct_with_local(self.vm, hf, local_slot)) } - /// Calls a JS function value synchronously from inside a direct host function (re-entrant). - #[inline] - pub fn call_fn_val(&mut self, f: Val, this: Val, args: &[Val]) -> Result { - let mut cached = self.vm.native_proto.clone(); - self.vm - .call_direct(&f.0, this.0, args, &mut cached) - .map(|s| Val(s.get())) - .map_err(|e| Val(e.get())) + /// A new empty object. + pub fn object(&mut self) -> Val<'a> { + Val::of(Value::Obj(self.vm.new_object())) } - fn alloc_pin(&mut self, v: Value) -> (u32, u32) { - let v = self.vm.sanitize_val(v); - // Write barrier: incremental GC has no atomic remark pass, so a white value newly stored - // into `HostRoots::pinned` while marking is in progress must be shaded immediately. - self.vm.gc_shade(v); - let roots = self.vm.host_roots_mut(); - if let Some(idx) = roots.pinned_free.pop() { - let slot = &mut roots.pinned[idx as usize]; - slot.value = Some(v); - (idx, slot.generation) - } else { - let idx = roots.pinned.len() as u32; - roots.pinned.push(crate::vm::PinSlot { - value: Some(v), - generation: 1, - }); - (idx, 1) - } + /// A new array of `items`. + pub fn array(&mut self, items: &[Val<'a>]) -> Val<'a> { + Val::of(self.vm.new_array(items.iter().map(|v| v.v).collect())) } - fn free_pin(&mut self, idx: u32, generation: u32) { - if generation == 0 { - return; - } - let Some(roots) = self.vm.host_roots.as_deref_mut() else { - return; - }; - if let Some(slot) = roots.pinned.get_mut(idx as usize) - && slot.value.is_some() - && slot.generation == generation - { - slot.value = None; - slot.generation = next_generation(slot.generation); - roots.pinned_free.push(idx); - } - } - - /// Pins a callable guest value so it stays rooted across GC cycles and can be invoked via [`Session::call_fn`]. - pub fn pin_fn(&mut self, v: Val) -> Option { - let Value::Obj(id) = v.0 else { - return None; - }; - if !self.vm.live_obj(id).is_some_and(|o| o.is_callable()) { - return None; - } - let (idx, generation) = self.alloc_pin(v.0); - Some(FnHandle { - session_id: self.vm.session_id, - idx, - generation, - }) + /// `o[name]`, as the program reads it: a getter runs, and a failure is what it throws. + pub fn get(&mut self, o: Val<'a>, name: &str) -> Result, Val<'a>> { + let key = self.key(name); + let read = self.vm.op_read(&o.v, key).map_err(Val::of)?; + self.read(o, read) } - /// Reads the value of a pinned function handle, or `Val::UNDEFINED` if freed, stale, or from another session. - #[inline(always)] - pub fn get_fn(&self, handle: FnHandle) -> Val { - if handle.session_id != self.vm.session_id { - return Val::UNDEFINED; - } - Val(self.vm.get_pinned(handle.idx, handle.generation)) - } - - /// Releases a previously pinned function handle so the GC can reclaim it. - pub fn unpin_fn(&mut self, handle: FnHandle) { - if handle.session_id != self.vm.session_id { - return; - } - self.free_pin(handle.idx, handle.generation); + /// `o[name] = v`, as the program writes it: a setter runs, a frozen object or a read-only property refuses it. + pub fn set(&mut self, o: Val<'a>, name: &str, v: Val<'a>) -> Result<(), Val<'a>> { + let key = self.key(name); + self.vm + .check_assignment_at(&o.v, key, &v.v) + .map_err(Val::of)?; + let setter = self.vm.op_write(&o.v, key, v.v).map_err(Val::of)?; + self.write(o, setter, v) } - /// Pins an arbitrary JS value so it stays rooted across GC cycles. - pub fn pin_val(&mut self, v: Val) -> ValHandle { - let (idx, generation) = self.alloc_pin(v.0); - ValHandle { - session_id: self.vm.session_id, - idx, - generation, - } + /// `o[index]`, as [`HostCtx::get`]. + pub fn get_index(&mut self, o: Val<'a>, index: u32) -> Result, Val<'a>> { + let key = Value::Num(index as f64); + let read = self.vm.op_read_elem(&o.v, &key).map_err(Val::of)?; + self.read(o, read) } - /// Reads a previously pinned JS value, or `Val::UNDEFINED` if freed, stale, or from another session. - #[inline(always)] - pub fn get_val(&self, handle: ValHandle) -> Val { - if handle.session_id != self.vm.session_id { - return Val::UNDEFINED; - } - Val(self.vm.get_pinned(handle.idx, handle.generation)) + /// `o[index] = v`, as [`HostCtx::set`]: a typed array converts and stores the number, an array grows. + pub fn set_index(&mut self, o: Val<'a>, index: u32, v: Val<'a>) -> Result<(), Val<'a>> { + let key = Value::Num(index as f64); + self.vm.check_assignment(&o.v, &v.v).map_err(Val::of)?; + let setter = self.vm.op_write_elem(&o.v, &key, v.v).map_err(Val::of)?; + self.write(o, setter, v) } - /// Releases a previously pinned value handle so the GC can reclaim it. - pub fn unpin_val(&mut self, handle: ValHandle) { - if handle.session_id != self.vm.session_id { - return; + fn read(&mut self, o: Val<'a>, read: Read) -> Result, Val<'a>> { + match read { + Read::Value(v) => Ok(Val::of(v)), + Read::Getter(g) => self.call(Val::of(g), o, &[]), } - self.free_pin(handle.idx, handle.generation); } - /// Sets or updates a global variable in this live VM. - pub fn set_global(&mut self, name: &str, v: Val) { - let v = self.vm.sanitize_val(v.0); - // Write barrier: shade `v` if GC is mid-mark since globals were already scanned at cycle start. - self.vm.gc_shade(v); - let atom = self.intern_key(name).0; - self.vm.global_map.insert(atom, v); - for (i, &a) in self.vm.global_names.iter().enumerate() { - if a == atom { - self.vm.globals[i] = v; - } + fn write(&mut self, o: Val<'a>, setter: Option, v: Val<'a>) -> Result<(), Val<'a>> { + match setter { + Some(s) => self.call(Val::of(s), o, &[v]).map(|_| ()), + None => Ok(()), } } - /// Looks up a global variable by name without interning or permanently rooting the key. - pub fn get_global(&self, name: &str) -> Option { - lookup_global(self.vm, name) - } - - /// Looks up a global variable by pre-interned [`Key`]. - #[inline] - pub fn get_global_by_key(&self, key: Key) -> Option { - lookup_global_by_key(self.vm, key) - } - - /// Creates a JS `TypeError` value suitable for returning as `Err(ctx.type_error(...))`. - #[cold] - pub fn type_error(&mut self, msg: &str) -> Val { - Val(self.vm.type_error(msg)) - } - - /// Creates a JS `Error` value suitable for returning as `Err(ctx.error(...))`. - #[cold] - pub fn error(&mut self, msg: &str) -> Val { - let proto = self.vm.realm.error_proto; - Val(self.vm.make_error(proto, msg)) - } - - /// Attaches typed per-session user data (accessible from both [`Session`] and [`HostCtx`]). - pub fn set_user_data(&mut self, val: T) { - store_set_user_data(self.vm.session_id, val); - } - - /// Reads typed per-session user data. - pub fn with_user_data(&self, f: impl FnOnce(&T) -> R) -> Option { - let cell = store_get_cell::(self.vm.session_id)?; - let borrow = cell.borrow(); - borrow.downcast_ref::().map(f) - } - - /// Mutates typed per-session user data. - pub fn with_user_data_mut(&self, f: impl FnOnce(&mut T) -> R) -> Option { - let cell = store_get_cell::(self.vm.session_id)?; - let mut borrow = cell.borrow_mut(); - borrow.downcast_mut::().map(f) - } - - /// Clones typed per-session user data (ideal for `Rc` state handles). - pub fn get_user_data(&self) -> Option { - self.with_user_data(Clone::clone) - } -} - -/// A persistent live VM instance initialized from a program, ready for repeated low-latency calls. -/// Thread-affine (`!Send + !Sync`) so per-session local host callbacks and user data are cleanly owned. -pub struct Session { - vm: Vm, - code: Arc, - cached_func: Arc, - _local: PhantomData<*const ()>, -} - -impl Drop for Session { - fn drop(&mut self) { - drop_session_store(self.vm.session_id); - } -} - -impl Session { - pub(crate) fn start( - rt: &Runtime, - code: Code<'_>, - options: &ProgramOptions, - ) -> Result> { - let mut running = run::start(rt, code, options)?; - let session_id = running.vm.session_id; - alloc_session_store(session_id); - let mut guard = SessionInitGuard::new(session_id); - let probe = 0u8; - running.vm.stack_base = &probe as *const u8 as usize; - running.vm.stack_budget = run::RUN_STACK_BUDGET; - running.vm.start = crate::time::Instant::now(); - if let Some(c) = running.vm.cpu.as_deref_mut() { - c.enter(); - } - running.vm.slice_restart(); - run::call_main(&mut running.vm); - let _ = running.vm.drive(); - if let Some(c) = running.vm.cpu.as_deref_mut() { - c.leave(false); - } - // Clear any init-time slice stretch so a Runtime `slice_ms` does not immediately trip on - // the first post-init `call_fn` outside `arm_slice`. - running.vm.slice = None; - if running.vm.fatal.is_some() - || matches!(running.vm.outcome, Some(Err(_))) - || running.vm.outcome.is_none() - { - return Err(Box::new(run::finish(*running))); - } - let exports = match running.vm.outcome.take() { - Some(Ok(v)) => v, - _ => unreachable!("checked above"), + /// `Object.keys(o)`: its own enumerable string keys, in order. + pub fn keys(&mut self, o: Val<'a>) -> Vec> { + let Value::Obj(id) = o.v else { + return Vec::new(); }; - // Root exports on the VM outside `HostRoots::pinned` so user unpin calls can never unroot it. - running.vm.gc_shade(exports); - running.vm.host_roots_mut().session_exports = exports; - let cached_func = running.vm.native_proto.clone(); - guard.disarm(); - Ok(Session { - vm: running.vm, - code: running.code, - cached_func, - _local: PhantomData, - }) - } - - /// The value returned by the top-level program (e.g. an object of exported functions). - #[inline(always)] - pub fn exports(&self) -> Val { - Val(self - .vm - .host_roots - .as_deref() - .map_or(Value::Undef, |r| r.session_exports)) - } - - /// Looks up a named function on [`Session::exports`] (or global scope) and pins it for [`Session::call_fn`]. - pub fn export_fn(&mut self, name: &str) -> Option { - let exports = self.exports(); - if let Some(atom) = lookup_atom(&self.vm, name) - && let Some(v) = self.ctx().obj_get(exports, Key(atom)) - && let Some(h) = self.ctx().pin_fn(v) - { - return Some(h); - } - self.global_fn(name) - } - - /// Borrows the VM context for building/reading values and interning keys. - #[inline(always)] - pub fn ctx(&mut self) -> HostCtx<'_> { - HostCtx { vm: &mut self.vm } - } - - /// Pre-interns and permanently roots a property name for zero-allocation reads and writes. - #[inline] - pub fn key(&mut self, name: &str) -> Key { - self.ctx().key(name) - } - - /// Looks up a global variable by name without interning or permanently rooting the key. - pub fn global(&self, name: &str) -> Option { - lookup_global(&self.vm, name) + let keys = self.vm.own_keys(id); + keys.into_iter() + .map(|k| Val::of(self.vm.atom_val(k))) + .collect() } - /// Looks up a global variable by pre-interned [`Key`]. - #[inline] - pub fn global_by_key(&self, key: Key) -> Option { - lookup_global_by_key(&self.vm, key) - } - - /// Sets or updates a global variable in this live VM. - pub fn set_global(&mut self, name: &str, v: Val) { - self.ctx().set_global(name, v); - } - - /// Looks up a global function by name and pins it for repeated invocation via [`Session::call_fn`]. - pub fn global_fn(&mut self, name: &str) -> Option { - let v = self.global(name)?; - self.ctx().pin_fn(v) - } - - /// Arms a recoverable per-entry slice budget of `ms` milliseconds (on `Limits::clock`, e.g. `ThreadCpu`). - /// Call [`Session::disarm_slice`] when the entry finishes so idle time is not charged. - /// - /// Clears a prior recoverable [`DiagnosticKind::SliceExceeded`] fatal state, while preserving - /// non-recoverable fatals such as memory limits. - pub fn arm_slice(&mut self, ms: u64) { - if matches!(self.vm.fatal, Some((DiagnosticKind::SliceExceeded, _))) { - self.vm.fatal = None; - } - self.vm.limits.slice_ms = Some(ms); - if self.vm.cpu.is_none() && self.vm.limits.clock == crate::Clock::ThreadCpu { - self.vm.start_cpu_meter(); - } - if let Some(c) = self.vm.cpu.as_deref_mut() { - c.enter(); - } - self.vm.slice_restart(); - self.vm.rebudget(); - } - - /// Ends the current entry's CPU-time stretch and clears the active slice limit so calls outside - /// a timed entry do not measure against a stale slice. - pub fn disarm_slice(&mut self) { - self.vm.limits.slice_ms = None; - self.vm.slice = None; - if let Some(c) = self.vm.cpu.as_deref_mut() { - c.leave(false); - } - self.vm.rebudget(); - } - - /// Invokes a pinned guest function synchronously with zero heap allocations on the hot path. - #[inline] - pub fn call_fn(&mut self, f: FnHandle, args: &[Val]) -> Result { - self.call_fn_with_this(f, Val::UNDEFINED, args) - } - - /// Invokes a pinned guest function synchronously with an explicit `this` receiver. - #[inline] - pub fn call_fn_with_this( + /// Calls a program function, as the program would call it. The time it takes is the program's. + pub fn call( &mut self, - f: FnHandle, - this: Val, - args: &[Val], - ) -> Result { - if f.session_id != self.vm.session_id { - return self.call_val(Val::UNDEFINED, this, args); - } - let func = self.vm.get_pinned(f.idx, f.generation); - self.call_val(Val(func), this, args) - } - - /// Invokes a callable JS value directly with an explicit `this` receiver. - #[inline] - pub fn call_val(&mut self, f: Val, this: Val, args: &[Val]) -> Result { - match self - .vm - .call_direct(&f.0, this.0, args, &mut self.cached_func) - { - Ok(slot) => { - if self.vm.fatal.is_some() { - Err(self.format_error(Value::Undef)) - } else { - Ok(Val(slot.get())) - } - } - Err(err) => Err(self.format_error(err.get())), - } - } - - /// Runs up to `max_jobs` queued Promise / microtask jobs without clearing remaining jobs when - /// the budget is reached. Returns `Ok(true)` if more jobs remain, or `Ok(false)` when drained. - /// Remaining jobs are cleared only on a fatal VM limit (such as slice timeout or OOM). - pub fn drain_jobs_budget(&mut self, max_jobs: usize) -> Result { - if self.vm.fatal.is_some() { - self.vm.jobs.clear(); - return Err(self.format_error(Value::Undef)); - } - let probe = 0u8; - if self.vm.native_depth == 0 { - self.vm.stack_base = &probe as *const u8 as usize; - self.vm.stack_budget = run::RUN_STACK_BUDGET; - } - let mut ran = 0usize; - while ran < max_jobs { - let Some(job) = self.vm.jobs.pop_front() else { - break; - }; - ran += 1; - if let Err(err) = self.vm.tick() { - if self.vm.fatal.is_some() { - self.vm.jobs.clear(); - } - return Err(self.format_error(err)); - } - if let Err(err) = self.vm.run_job(job) { - if self.vm.fatal.is_some() { - self.vm.jobs.clear(); - } - return Err(self.format_error(err)); - } - if self.vm.fatal.is_some() { - self.vm.jobs.clear(); - return Err(self.format_error(Value::Undef)); - } - if self.vm.suspended { - break; - } - } - Ok(!self.vm.jobs.is_empty()) - } - - /// Runs queued Promise / microtask jobs in this session without failing on externally pending Promises. - /// Runs up to 4096 jobs per call (returning `SliceExceeded` if jobs still remain without - /// destructively clearing the queue; only fatal errors clear remaining jobs). - pub fn drain_jobs(&mut self) -> Result<(), Diagnostic> { - let more = self.drain_jobs_budget(DEFAULT_DRAIN_JOBS_BUDGET)?; - if more && !self.vm.suspended { - return Err(Diagnostic { - kind: DiagnosticKind::SliceExceeded, - message: format!( - "Microtask queue exceeded {DEFAULT_DRAIN_JOBS_BUDGET} jobs in a single drain." - ) - .into(), - location: None, - suggestions: Vec::new(), - }); - } - Ok(()) - } - - /// Drains any unhandled Promise rejections recorded in this session, formatting each rejection - /// reason directly from heap state (never invoking arbitrary user JS `toString()` or - /// `[Symbol.toPrimitive]`) and clearing the VM's root list so rejected Promises do not accumulate. - pub fn take_unhandled_rejections(&mut self) -> Vec { - let drained = std::mem::take(&mut self.vm.host.unhandled); - if drained.is_empty() { - return Vec::new(); - } - let mut out = Vec::with_capacity(drained.len()); - let ctx = self.ctx(); - for (_, reason) in drained { - out.push(ctx.format_val_safe(reason)); - } - out - } - - /// Whether any Promise / microtask jobs are waiting to run. - #[inline(always)] - pub fn has_pending_jobs(&self) -> bool { - !self.vm.jobs.is_empty() - } - - /// Reachable heap bytes held by this session's VM. - pub fn memory_bytes(&self) -> usize { - crate::heap::measure(&self.vm) as usize - } - - /// Runs one bounded incremental GC step between UI frames. - pub fn gc_step(&mut self) { - self.vm.gc_step_once(); - } - - /// Runs a full garbage collection cycle and releases empty trailing heap chunks back to the OS. - pub fn collect_garbage(&mut self) { - self.vm.gc_collect_full(); - } - - /// The limits configured on this session. - pub fn limits(&self) -> &Limits { - &self.vm.limits - } - - /// Pins a callable value. - pub fn pin_fn(&mut self, v: Val) -> Option { - self.ctx().pin_fn(v) - } - - /// Reads a pinned function value, or `Val::UNDEFINED` if freed, stale, or from another session. - #[inline(always)] - pub fn get_fn(&self, handle: FnHandle) -> Val { - if handle.session_id != self.vm.session_id { - return Val::UNDEFINED; - } - Val(self.vm.get_pinned(handle.idx, handle.generation)) - } - - /// Releases a pinned function handle. - pub fn unpin_fn(&mut self, handle: FnHandle) { - self.ctx().unpin_fn(handle); - } - - /// Pins an arbitrary JS value. - pub fn pin_val(&mut self, v: Val) -> ValHandle { - self.ctx().pin_val(v) - } - - /// Reads a pinned JS value, or `Val::UNDEFINED` if freed, stale, or from another session. - #[inline(always)] - pub fn get_val(&self, handle: ValHandle) -> Val { - if handle.session_id != self.vm.session_id { - return Val::UNDEFINED; - } - Val(self.vm.get_pinned(handle.idx, handle.generation)) - } - - /// Releases a pinned value handle. - pub fn unpin_val(&mut self, handle: ValHandle) { - self.ctx().unpin_val(handle); - } - - /// Attaches typed per-session user data. - pub fn set_user_data(&mut self, val: T) { - store_set_user_data(self.vm.session_id, val); - } - - /// Reads typed per-session user data. - pub fn with_user_data(&self, f: impl FnOnce(&T) -> R) -> Option { - let cell = store_get_cell::(self.vm.session_id)?; - let borrow = cell.borrow(); - borrow.downcast_ref::().map(f) - } - - /// Mutates typed per-session user data. - pub fn with_user_data_mut(&self, f: impl FnOnce(&mut T) -> R) -> Option { - let cell = store_get_cell::(self.vm.session_id)?; - let mut borrow = cell.borrow_mut(); - borrow.downcast_mut::().map(f) - } - - /// Clones typed per-session user data. - pub fn get_user_data(&self) -> Option { - self.with_user_data(Clone::clone) + f: Val<'a>, + this: Val<'a>, + args: &[Val<'a>], + ) -> Result, Val<'a>> { + let args: Vec = args.iter().map(|v| v.v).collect(); + self.vm.end_host_span(self.span.take()); + let r = self.vm.call(&f.v, this.v, &args); + self.span = self.vm.host_span(); + r.map(Val::of).map_err(Val::of) + } + + /// A new `Error`, to throw: the function's `Err`. + pub fn error(&mut self, message: &str) -> Val<'a> { + let proto = self.vm.realm.error_proto; + let message = crate::strings::external_text(message.to_owned()); + Val::of(self.vm.make_error(proto, &message)) } - #[cold] - #[inline(never)] - fn format_error(&mut self, err: Value) -> Diagnostic { - if let Some((kind, msg)) = self.vm.fatal.take() { - return Diagnostic { - kind, - message: msg.into(), - location: None, - suggestions: Vec::new(), - }; - } - let message = self.ctx().format_val_safe(err); - let (kind, location, suggestions) = if let Value::Obj(id) = err - && let Some(obj) = self.vm.live_obj(id) - && let Kind::Error(Some(f)) = &obj.kind - { - ( - f.kind.clone(), - f.offset.map(|o| run::line_col(&self.code, o)), - self.vm - .host - .suggestions - .get(&id) - .cloned() - .unwrap_or_default(), - ) - } else { - (DiagnosticKind::ExecutionFailure, None, Vec::new()) - }; - Diagnostic { - kind, - message: message.into(), - location, - suggestions, - } + /// A new `TypeError`, to throw. + pub fn type_error(&mut self, message: &str) -> Val<'a> { + let message = crate::strings::external_text(message.to_owned()); + Val::of(self.vm.type_error(&message)) } } diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index 8812edf3..ddbfd17d 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -504,7 +504,7 @@ impl Enc<'_> { global_map.sort_by_key(|(a, _)| **a); let host = self.host(c)?; let std = &vm.realm.std; - Ok(json!({ + let mut state = json!({ "strings": texts.iter().map(|(t, b)| json!([t, b])).collect::>(), "atoms": atoms, "cells": vm.cells[base.cells.min(vm.cells.len())..].iter().map(slot).collect::>(), @@ -533,7 +533,12 @@ impl Enc<'_> { std.weak_map, std.weak_set, std.iterator_helper, std.uri_error, std.url, std.params, std.headers, std.loaded, std.array_buffer, std.typed, std.bigint, std.data_view], "host": host, - })) + }); + // Only a session's state has one (`session.rs`). + if let Some(s) = &vm.session { + state["session"] = json!({ "exports": s.exports.as_ref().map(val) }); + } + Ok(state) } fn host(&mut self, _c: &Capture) -> R { @@ -555,23 +560,20 @@ impl Enc<'_> { } let functions: Vec = h.functions[base.functions.min(h.functions.len())..] .iter() - .map(|slot| match slot { - Some(f) => { - let (name, length, own) = match &f.f { - Callee::Fn(hf) => (hf.name(), hf.length, hf.own_name), - Callee::Durable(_) => ("", 0, false), - }; - json!([ - f.label, - f.path.as_deref().map(texts), - f.owner, - f.installed, - name, - length, - own - ]) - } - None => J::Null, + .map(|f| { + let (name, length, own) = match &f.f { + Callee::Fn(hf) => (hf.name(), hf.length, hf.own_name), + Callee::Durable(_) => ("", 0, false), + }; + json!([ + f.label, + f.path.as_deref().map(texts), + f.owner, + f.installed, + name, + length, + own + ]) }) .collect(); let mut suggestions: Vec<(&Id, &Vec)> = h.suggestions.iter().collect(); @@ -2521,6 +2523,15 @@ pub fn restore(vm: &mut Vm, snapshot: &Snapshot, program_hash: &str) -> R<()> { })) } }; + vm.session = match st.get("session") { + None => None, + Some(s) => Some(Box::new(crate::session::SessionState { + exports: match field(s, "exports")? { + J::Null => None, + j => Some(dec.val(j)?), + }, + })), + }; vm.rng = field(st, "rng")? .as_str() .and_then(|r| r.parse().ok()) @@ -2660,16 +2671,8 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { }); } vm.host.functions.truncate(base.functions); - vm.host - .free_functions - .retain(|&idx| (idx as usize) < base.functions); for (i, f) in field_list(j, "functions")?.iter().enumerate() { let index = base.functions + i; - if f.is_null() { - vm.host.functions.push(None); - vm.host.free_functions.push(index as u32); - continue; - } let label = string(at(f, 0)?)?; let path = opt_path(at(f, 1)?)?; let owner = opt_string(at(f, 2)?)?; @@ -2683,31 +2686,13 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { Some(path) => vm.host.resolve(path), None => from_root.map(Callee::Fn), }; - vm.host.functions.push(Some(FnEntry { + vm.host.functions.push(FnEntry { f: found.unwrap_or_else(|| Callee::Fn(host::lost_function(&name))), label, path, owner, installed, - reclaimable: false, - local_slot: None, - })); - } - for o in vm.heap.iter() { - if let Kind::Native { f, data, .. } = &o.kind - && std::ptr::fn_addr_eq(*f, crate::host::host_native as crate::vm::NativeFn) - { - let valid = matches!( - data, - Value::Num(n) - if *n >= 0.0 - && n.fract() == 0.0 - && vm.host.functions.get(*n as usize).is_some_and(Option::is_some) - ); - if !valid { - return Err(invalid("a host function slot is missing.")); - } - } + }); } vm.host.suggestions.clear(); for s in field_list(j, "suggestions")? { diff --git a/rust/crates/psychoscript/src/strings.rs b/rust/crates/psychoscript/src/strings.rs index 795f1837..518e32e3 100644 --- a/rust/crates/psychoscript/src/strings.rs +++ b/rust/crates/psychoscript/src/strings.rs @@ -701,34 +701,6 @@ impl Strings { self.get(self.atom_str[a as usize]) } - /// Bounds- and liveness-checked string lookup returning `None` for out-of-range, freed, or - /// unswept dead (`WHITE` during `Phase::Sweep`) string ids. - #[inline] - pub(crate) fn get_opt(&self, id: StrId) -> Option<&str> { - let idx = id as usize; - let b = self.bufs.get(idx)?; - if !self.gc.is_live(idx) { - return None; - } - if b.grow == NO_GROW { - return Some(&b.s); - } - let off = b.aux as usize; - self.grow - .get(b.grow as usize)? - .get(off..off + b.len as usize) - } - - /// Bounds-checked atom lookup returning `None` for invalid or freed (`NO_ATOM`) atoms. - #[inline] - pub(crate) fn text_opt(&self, a: Atom) -> Option<&str> { - let &sid = self.atom_str.get(a as usize)?; - if sid == NO_ATOM { - return None; - } - self.get_opt(sid) - } - /// The array index an atom names, if it is canonical. #[inline] pub fn index(&self, a: Atom) -> Option { diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 80e07c52..95090ab2 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -5,14 +5,14 @@ use std::collections::VecDeque; use std::sync::Arc; use std::time::Duration; -use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_hash::FxHashMap; use crate::accessors::Read; use crate::bytecode::{Arith, Capture, FuncProto, Op, Program, TemplateSite}; use crate::compiler::{DELEGATE_ASYNC, DELEGATE_NO_ARG}; use crate::conversion::code; use crate::object::*; -use crate::strings::{Atom, StrId, Strings}; +use crate::strings::{StrId, Strings}; use crate::value::{Id, Slot, Value}; use crate::{DiagnosticKind, Limits}; @@ -25,7 +25,7 @@ pub type NativeFn = fn(&mut Vm, Value, &[Value], Id) -> Res; pub const MAX_DEPTH: usize = 10_000; pub(crate) const MAX_OBJECTS: usize = 2_000_000; pub(crate) const MAX_STRINGS: usize = 4_000_000; -pub(crate) const MAX_NATIVE_DEPTH: usize = 400; +const MAX_NATIVE_DEPTH: usize = 400; pub(crate) const FUEL: i32 = 20_000; /// The reference's fuel: it starts the host calls a program queued whenever this runs out, so streaming responses /// count it the same way. A loop back-edge, a function call or a job costs one, a call of a native function fifty. @@ -282,7 +282,7 @@ pub struct Vm { /// A host call waiting for promises in its arguments parks its frames (see `park_frames`) with this coroutine. pub(crate) park: bool, pub(crate) park_coroutine: u32, - pub(crate) native_depth: usize, + native_depth: usize, /// Address near the bottom of the native stack this run started on, and how much of it calls may use. pub stack_base: usize, pub stack_budget: usize, @@ -366,36 +366,8 @@ pub struct Vm { pub(crate) slice: Option>, /// What `console.count`, `group` and `time` remember, once one is called. Saved with the run. pub(crate) console: Option>, - /// Lazily boxed host/session GC roots (pinned handles, rooted host atoms, session exports), - /// keeping `Vm` compact and `Vm::stack` near the top of the struct. - pub(crate) host_roots: Option>, - /// Unique non-zero VM instance id used to scope pinned handles and per-`Session` TLS state. - pub(crate) session_id: u64, - /// Explicitly `true` ONLY while executing a top-level `Session::call_val` JS frame with no - /// unrooted Rust locals on the call stack, permitting back-edge `gc_point()` steps. - pub(crate) session_gc_safe: bool, -} - -/// Host- and session-owned GC roots boxed out of `Vm` so standalone runs pay zero overhead. -#[derive(Default)] -pub(crate) struct HostRoots { - /// Guest values pinned by an embedder (`Session` / `HostCtx::pin_fn` / `HostCtx::pin_val`). - pub(crate) pinned: Vec, - /// Free slot indices in `pinned` available for reuse. - pub(crate) pinned_free: Vec, - /// Property key atoms interned by the host (`HostCtx::key` / `Session::key`), traced as permanent GC roots. - pub(crate) host_atoms: Vec, - /// Deduplication set for `host_atoms`. - pub(crate) host_atom_set: FxHashSet, - /// Top-level export value kept rooted for a persistent `Session` (separate from user `pinned` slots). - pub(crate) session_exports: Value, -} - -/// One generation-tagged slot in `HostRoots::pinned`, preventing ABA reuse bugs and `undefined` pin leaks. -#[derive(Clone, Copy, Debug)] -pub(crate) struct PinSlot { - pub(crate) value: Option, - pub(crate) generation: u32, + /// A session's state (`session.rs`): what its top level returned, which its calls call. Saved with the run. + pub(crate) session: Option>, } impl Vm { @@ -543,9 +515,7 @@ impl Vm { cpu: None, slice: None, console: None, - host_roots: None, - session_id: crate::session::next_session_id(), - session_gc_safe: false, + session: None, } } @@ -856,7 +826,7 @@ impl Vm { /// A back-edge, a function call or a job. #[inline] - pub(crate) fn tick(&mut self) -> Result<(), Value> { + fn tick(&mut self) -> Result<(), Value> { self.budget -= 1; if self.budget <= 0 { return self.budget_out(true); @@ -924,7 +894,7 @@ impl Vm { self.host.meter.start = self.budget; } - pub(crate) fn rebudget(&mut self) { + fn rebudget(&mut self) { let b = self.host.meter.handover.min(self.host.meter.fuel).max(1); self.budget = b; self.host.meter.start = b; @@ -1001,8 +971,6 @@ impl Vm { if self.native_depth >= MAX_NATIVE_DEPTH { return Err(self.range_error("Maximum call stack size exceeded")); } - let prev_gc_safe = self.session_gc_safe; - self.session_gc_safe = false; self.native_depth += 1; self.host.meter.counted = true; self.reads.fault = None; @@ -1011,11 +979,9 @@ impl Vm { if self.entered { let r = self.drive_entered(true); self.native_depth -= 1; - self.session_gc_safe = prev_gc_safe; return r; } self.native_depth -= 1; - self.session_gc_safe = prev_gc_safe; let r = r?; self.native_spent(); return Ok(r); @@ -1363,165 +1329,6 @@ impl Vm { } } - /// Lazily allocates and returns mutable access to the VM's boxed host/session GC roots. - #[inline] - pub(crate) fn host_roots_mut(&mut self) -> &mut HostRoots { - self.host_roots.get_or_insert_with(Box::default) - } - - /// Reads a generation-checked pinned value, or `Value::Undef` if freed or stale. - #[inline(always)] - pub(crate) fn get_pinned(&self, idx: u32, generation: u32) -> Value { - self.host_roots - .as_deref() - .and_then(|r| r.pinned.get(idx as usize)) - .filter(|slot| slot.generation == generation) - .and_then(|slot| slot.value) - .unwrap_or(Value::Undef) - } - - /// Validates that a host-supplied `Value` still points to a live heap object, string, or BigInt, - /// returning `Value::Undef` for stale or `Uninit` values so post-GC writes cannot poison the VM. - #[inline] - pub(crate) fn sanitize_val(&self, v: Value) -> Value { - match v { - Value::Obj(id) => { - if self.is_live_obj(id) { - v - } else { - Value::Undef - } - } - Value::Str(id) => { - if self.atoms.get_opt(id).is_some() { - v - } else { - Value::Undef - } - } - Value::Big(id) if crate::builtins::bigint::on_heap(id) => { - if self.is_live_obj(id) { - v - } else { - Value::Undef - } - } - Value::Uninit => Value::Undef, - _ => v, - } - } - - /// Calls a guest function synchronously from a [`Session`](crate::Session) without copying `args` or cloning `func`. - #[inline] - pub(crate) fn call_direct( - &mut self, - f: &Value, - this: Value, - args: &[crate::session::Val], - cached: &mut Arc, - ) -> Result { - if self.fatal.is_some() { - return Err(Slot::UNDEF); - } - let f = self.sanitize_val(*f); - let this = self.sanitize_val(this); - // Write barrier: if incremental GC is mid-mark, shade the callee, receiver, and arguments - // before pushing them onto the VM stack so an unrooted WHITE Val cannot be stored into an - // already-BLACK container and swept. - if self.gc_is_marking() { - self.gc_shade(f); - self.gc_shade(this); - for arg in args { - let v = self.sanitize_val(arg.0); - self.gc_shade(v); - } - } - let probe = 0u8; - if self.native_depth == 0 { - self.stack_base = &probe as *const u8 as usize; - self.stack_budget = crate::run::RUN_STACK_BUDGET; - } - if let Value::Obj(id) = f - && let Some(obj) = self.live_obj(id) - && matches!(obj.kind, Kind::Closure(_)) - && self.native_depth < MAX_NATIVE_DEPTH - && self.stack_base.abs_diff(&probe as *const u8 as usize) <= self.stack_budget - { - let fpos = self.stack.len(); - self.push(f); - self.push(this); - for arg in args { - let v = self.sanitize_val(arg.0); - self.stack.push(Slot::pack(v)); - } - self.push_simple_or_full(id, fpos, args.len(), true) - .map_err(Slot::pack)?; - let prev_gc_safe = self.session_gc_safe; - self.session_gc_safe = self.run_depth == 0 && self.native_depth == 0; - self.native_depth += 1; - let r = self.run_callback_with(cached); - self.native_depth -= 1; - self.session_gc_safe = prev_gc_safe; - return match r { - Ok(Exit::Return(v)) | Ok(Exit::Yield(v)) => Ok(v), - Ok(Exit::Suspend) => Ok(Slot::UNDEF), - Err(e) => Err(Slot::pack(e)), - }; - } - let raw: Vec = args.iter().map(|v| self.sanitize_val(v.0)).collect(); - self.call_slow(&f, this, &raw) - .map(Slot::pack) - .map_err(Slot::pack) - } - - /// Fast inline closure frame push for plain sync non-class closures with a spare frame and budget left. - #[inline(always)] - fn push_simple_or_full( - &mut self, - id: Id, - fpos: usize, - argc: usize, - is_base: bool, - ) -> Result<(), Value> { - if self.budget > 1 - && self.frames.len() <= MAX_DEPTH - && let Kind::Closure(c) = &self.heap[id as usize].kind - && c.proto.class == 0 - && !c.proto.is_async - && !c.proto.is_generator - && !c.proto.needs_extra - && argc <= c.proto.nparams as usize - && let Some(mut spare) = self.spare_frames.pop() - { - self.budget -= 1; - if c.proto.is_arrow { - self.stack[fpos + 1] = Slot::pack(c.this); - } - let base = fpos + 2; - let nlocals = c.proto.nlocals as usize; - if nlocals > argc { - self.stack.resize(base + nlocals, Slot::UNDEF); - } - if !Arc::ptr_eq(&spare.func, &c.proto) { - spare.func = c.proto.clone(); - } - if !Arc::ptr_eq(&spare.upvals, &c.upvals) { - spare.upvals = c.upvals.clone(); - } - spare.pc = 0; - spare.base = base; - spare.hbase = self.handlers.len() as u32; - spare.extra = Box::default(); - spare.argc = argc as u32; - spare.kind = FrameKind::Normal; - spare.is_base = is_base; - spare.yield_pc = NO_YIELD; - self.push_frame(spare); - return Ok(()); - } - self.push_closure_frame(id, fpos, argc, is_base) - } - /// `call` with each outcome packed in one word, so it comes back in registers: a two-word `Value` returned /// through memory stalls the caller's reload on store forwarding, measurably on short callbacks. #[inline(never)] @@ -1560,14 +1367,6 @@ impl Vm { } fn call_slow(&mut self, f: &Value, this: Value, args: &[Value]) -> Res { - let prev_gc_safe = self.session_gc_safe; - self.session_gc_safe = false; - let r = self.call_slow_inner(f, this, args); - self.session_gc_safe = prev_gc_safe; - r - } - - fn call_slow_inner(&mut self, f: &Value, this: Value, args: &[Value]) -> Res { if self.stack_spent() { return Err(self.range_error("Maximum call stack size exceeded")); } @@ -1575,10 +1374,7 @@ impl Vm { return Err(self.type_error("The called value is not a function.")); }; let id = *id; - let Some(obj) = self.live_obj(id) else { - return Err(self.type_error("The called value is not a function.")); - }; - match &obj.kind { + match &self.heap[id as usize].kind { Kind::Closure(_) => { if self.native_depth >= MAX_NATIVE_DEPTH { return Err(self.range_error("Maximum call stack size exceeded")); @@ -1833,10 +1629,7 @@ impl Vm { self.stack.truncate(fpos); return Err(self.range_error("Maximum call stack size exceeded")); } - if let Err(err) = self.tick() { - self.stack.truncate(fpos); - return Err(err); - } + self.tick()?; let Kind::Closure(c) = &self.heap[id as usize].kind else { return Ok(()); }; @@ -1921,62 +1714,8 @@ impl Vm { self.push_closure_frame(id, fpos, argc, false)?; Ok(true) } - Kind::Native { f, data, .. } => { + Kind::Native { f, .. } => { let f = *f; - if std::ptr::fn_addr_eq(f, crate::host::host_native as NativeFn) - && let Value::Num(index) = *data - && let Some(Some(entry)) = self.host.functions.get(index as usize) - && let crate::host::Callee::Fn(hf) = &entry.f - && let crate::host_function::Body::Direct(d) = &hf.body - { - if self.native_depth >= MAX_NATIVE_DEPTH || self.stack_spent() { - self.stack.truncate(fpos); - return Err(self.range_error("Maximum call stack size exceeded")); - } - let d = d.clone(); - let this = self.stack[fpos + 1].get(); - let prev_gc_safe = self.session_gc_safe; - self.session_gc_safe = false; - let r = if argc <= 8 { - let mut stack_args = [Value::Undef; 8]; - for (dst, slot) in stack_args.iter_mut().zip(&self.stack[fpos + 2..]) { - *dst = slot.get(); - } - self.stack.truncate(fpos); - self.native_depth += 1; - let mut ctx = crate::session::HostCtx::new(self); - let r = d( - &mut ctx, - crate::session::DirectArgs::with_this(this, &stack_args[..argc]), - ); - self.native_depth -= 1; - r - } else { - let mut args = self.arg_pool.pop().unwrap_or_default(); - args.extend(self.stack.drain(fpos + 2..).map(Slot::get)); - self.stack.truncate(fpos); - self.native_depth += 1; - let mut ctx = crate::session::HostCtx::new(self); - let r = d(&mut ctx, crate::session::DirectArgs::with_this(this, &args)); - self.native_depth -= 1; - args.clear(); - self.arg_pool.push(args); - r - }; - self.session_gc_safe = prev_gc_safe; - if self.fatal.is_some() { - return Err(Value::Undef); - } - match r { - Ok(v) => { - let v = self.sanitize_val(v.0); - self.push(v); - self.native_spent(); - return Ok(false); - } - Err(e) => return Err(self.sanitize_val(e.0)), - } - } if id == self.realm.generator_next && let Some(g) = self.suspended_generator(self.stack[fpos + 1]) { @@ -2578,30 +2317,23 @@ impl Vm { self.handlers.truncate(frame.hbase as usize); self.stack.truncate(frame.base - 2); match frame.kind { - FrameKind::Async(c) => { - if fatal { - self.free_coroutine(c); - if frame.is_base { - return Err(Err(e)); + FrameKind::Async(c) if !fatal => { + let result = match self.coroutines[c as usize].promise { + Some(p) => { + self.free_coroutine(c); + self.reject(p, e); + Value::Obj(p) } - } else { - let result = match self.coroutines[c as usize].promise { - Some(p) => { - self.free_coroutine(c); - self.reject(p, e); - Value::Obj(p) - } - None => { - self.outcome = Some(Err(e)); - Value::Undef - } - }; - if frame.is_base { - return Err(Ok(Exit::Return(Slot::pack(result)))); + None => { + self.outcome = Some(Err(e)); + Value::Undef } - self.push(result); - return Ok(()); + }; + if frame.is_base { + return Err(Ok(Exit::Return(Slot::pack(result)))); } + self.push(result); + return Ok(()); } FrameKind::Generator(g, _) => { self.leave_generator(g, None); @@ -3407,17 +3139,6 @@ impl Vm { r } - #[inline(always)] - fn run_callback_with(&mut self, cached: &mut Arc) -> Result { - if self.resumable_run { - return self.run(); - } - self.run_depth += 1; - let r = self.run_frames_with(false, cached); - self.run_depth -= 1; - r - } - /// Continues frames a suspend left on the job stack, as the entry point that started them would have. pub fn continue_frames(&mut self) -> Result<(), Value> { if self.frames.is_empty() { @@ -3431,15 +3152,6 @@ impl Vm { /// The dispatch loop. `resumable` lets a suspend stop it at a back-edge, leaving its frames for later. fn run_frames(&mut self, resumable: bool) -> Result { - let mut cached = self.frames.last().expect("frame").func.clone(); - self.run_frames_with(resumable, &mut cached) - } - - fn run_frames_with( - &mut self, - resumable: bool, - func: &mut Arc, - ) -> Result { 'outer: loop { let fi = self.frames.len() - 1; if let FrameKind::Native(op, sub) = self.frames[fi].kind { @@ -3457,9 +3169,7 @@ impl Vm { } } } - if !Arc::ptr_eq(func, &self.frames[fi].func) { - *func = self.frames[fi].func.clone(); - } + let func = self.frames[fi].func.clone(); let code: &[Op] = &func.code; let base = self.frames[fi].base; let mut pc = self.frames[fi].pc; @@ -4470,19 +4180,10 @@ impl Vm { Op::Jump(t) => { if (t as usize) < pc { tri!(self.tick()); - if self.suspend_wanted { - if resumable { - if !self.gc_point() { - self.frames[fi].pc = t as usize; - self.suspended = true; - return Ok(Exit::Suspend); - } - } else if self.session_gc_safe - && self.run_depth == 1 - && self.gc.owns_suspend() - { - self.gc_point(); - } + if self.suspend_wanted && resumable && !self.gc_point() { + self.frames[fi].pc = t as usize; + self.suspended = true; + return Ok(Exit::Suspend); } } pc = t as usize; @@ -4530,19 +4231,10 @@ impl Vm { if self.truthy(&v) { if (t as usize) < pc { tri!(self.tick()); - if self.suspend_wanted { - if resumable { - if !self.gc_point() { - self.frames[fi].pc = t as usize; - self.suspended = true; - return Ok(Exit::Suspend); - } - } else if self.session_gc_safe - && self.run_depth == 1 - && self.gc.owns_suspend() - { - self.gc_point(); - } + if self.suspend_wanted && resumable && !self.gc_point() { + self.frames[fi].pc = t as usize; + self.suspended = true; + return Ok(Exit::Suspend); } } pc = t as usize; diff --git a/rust/crates/psychoscript/tests/session.rs b/rust/crates/psychoscript/tests/session.rs index e9f177d6..c07134e6 100644 --- a/rust/crates/psychoscript/tests/session.rs +++ b/rust/crates/psychoscript/tests/session.rs @@ -1,1509 +1,500 @@ -use std::cell::Cell; -use std::rc::Rc; +//! Sessions (`Runtime::session`) and direct host functions (`HostFunction::direct`): Rust-only, so their expected +//! results are written here. + use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use psychoscript::{ - Clock, DiagnosticKind, HostFunction, HostValue, Limits, Namespace, ProgramOptions, Resolved, - Runtime, Session, Val, + Data, DiagnosticKind, HostFunction, HostValue, Json, Limits, Namespace, Outcome, + ProgramOptions, Resolved, Runtime, Val, from_bytes, to_bytes, }; +use serde_json::json; -#[test] -fn session_calls_stateful_exports_and_direct_host_functions_with_this() { - let log = Arc::new(Mutex::new(Vec::::new())); - let rt = Runtime::make().globals({ - let log = log.clone(); - move |_| { - let log = log.clone(); - vec![ - ( - "record", - HostValue::Function(HostFunction::direct(move |ctx, args| { - let msg = ctx.as_str(args.get(0)).unwrap_or(""); - let n = args.get(1).as_f64().unwrap_or(0.0); - log.lock().unwrap().push(format!("{msg}:{n}")); - Ok(Val::num(n * 2.0)) - })), - ), - ( - "sumArray", - HostValue::Function(HostFunction::direct(|ctx, args| { - let mut sum = 0.0; - ctx.array_for_each(args.get(0), |v| { - if let Some(x) = v.as_f64() { - sum += x; - } - }); - Ok(Val::num(sum)) - })), - ), - ( - "readThisAndMany", - HostValue::Function(HostFunction::direct(|ctx, args| { - let k_tag = ctx.key("tag"); - let tag = ctx.obj_get_str(args.this(), k_tag).unwrap_or("none"); - let mut sum = 0.0; - for i in 0..args.len() { - sum += args.get(i).as_f64().unwrap_or(0.0); - } - Ok(ctx.new_str(&format!("{tag}:{sum}"))) - })), - ), - ] - } - }); - - let mut sess = rt - .session_with( - r#" - let count = 0; - function click(delta) { - count += delta; - return count; - } - function render(label) { - const doubled = record(label, count); - return sumArray([doubled, 10, 20]); - } - function callMethod() { - const host = { tag: "btn", fn: readThisAndMany }; - // 10 args exercises >8 args direct dispatch path too. - return host.fn(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - } - function readReceiver() { - return this.value; - } - function triple(x) { - return x * 3; - } - return { click, render, callMethod, readReceiver, triple }; - "#, - &ProgramOptions::default(), - ) - .expect("session init"); - - let exports = sess.exports(); - assert!(sess.ctx().is_plain_object(exports)); - let click = sess.export_fn("click").expect("click export"); - let render = sess.export_fn("render").expect("render export"); - let call_method = sess.export_fn("callMethod").expect("callMethod export"); - let read_receiver = sess.export_fn("readReceiver").expect("readReceiver export"); - let k_triple = sess.key("triple"); - let triple_val = sess.ctx().obj_get(exports, k_triple).expect("triple val"); - sess.set_global("globalMultiplier", triple_val); - let global_mul = sess.global_fn("globalMultiplier").expect("global fn"); - - assert_eq!( - sess.call_fn(click, &[Val::num(3.0)]).unwrap().as_f64(), - Some(3.0) - ); - assert_eq!( - sess.call_fn(click, &[Val::num(4.0)]).unwrap().as_f64(), - Some(7.0) - ); - - let label = sess.ctx().new_str("panel"); - let out = sess.call_fn(render, &[label]).unwrap(); - assert_eq!(out.as_f64(), Some(44.0)); - assert_eq!(*log.lock().unwrap(), vec!["panel:7".to_owned()]); - - let method_out = sess.call_fn(call_method, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(method_out), Some("btn:55")); - - let receiver = { - let mut ctx = sess.ctx(); - let k_val = ctx.key("value"); - ctx.new_object_with(&[(k_val, Val::num(99.0))]) - }; - assert_eq!( - sess.call_fn_with_this(read_receiver, receiver, &[]) - .unwrap() - .as_f64(), - Some(99.0) - ); - assert_eq!( - sess.call_fn(global_mul, &[Val::num(6.0)]).unwrap().as_f64(), - Some(18.0) - ); - let global_fn_val = sess.global("globalMultiplier").expect("global val"); - assert_eq!( - sess.call_val(global_fn_val, Val::UNDEFINED, &[Val::num(5.0)]) - .unwrap() - .as_f64(), - Some(15.0) - ); +fn ok(o: &Outcome) -> Json { + match &o.result { + Ok(v) => v.to_json(), + Err(e) => panic!("expected success, got {}: {}", e.kind, e.message), + } } -#[test] -fn direct_host_function_inside_namespace_works_without_panicking() { - let rt = Runtime::make().globals(|_| { - vec![( - "api", - HostValue::Namespace(Namespace::new( - |_| Ok(Vec::new()), - |path| { - let name = path.last().and_then(|s| s.as_str()).unwrap_or(""); - match name { - "add" => Resolved::Function(HostFunction::direct(|_ctx, args| { - let a = args.get(0).as_f64().unwrap_or(0.0); - let b = args.get(1).as_f64().unwrap_or(0.0); - Ok(Val::num(a + b)) - })), - "fail" => Resolved::Function(HostFunction::direct(|ctx, _| { - Err(ctx.type_error("ns boom")) - })), - _ => Resolved::Function(HostFunction::direct(|_ctx, _| Ok(Val::UNDEFINED))), - } - }, - )), - )] - }); - - let mut sess = rt - .session( - r#" - function run() { - const sum = api.math.add(19, 23); - let msg = ""; - try { - api.fail(); - } catch (e) { - msg = e.message; - } - return sum + ":" + msg; - } - return { run }; - "#, - ) - .expect("session init"); +fn failed(o: &Outcome) -> &psychoscript::Diagnostic { + match &o.result { + Ok(v) => panic!("expected a failure, got {v}"), + Err(e) => e, + } +} - let run = sess.export_fn("run").unwrap(); - let out = sess.call_fn(run, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(out), Some("42:ns boom")); +fn args(items: &[Json]) -> Vec { + items.iter().cloned().map(Data::from).collect() } +const COUNTER: &str = r#" +let count = 0; +return { + add(n) { count += n; return count; }, + async later(n) { await null; count += n; return { count, logged: console.log("at", count) } }, + fail() { throw new TypeError("no"); }, +}; +"#; + #[test] -fn pinned_callbacks_and_objects_survive_full_gc() { +fn a_session_keeps_its_state_from_call_to_call() { let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - let total = 0; - function makeHandler(step) { - return (x) => { - total += x * step; - return total; - }; - } - function churn() { - let acc = 0; - for (let i = 0; i < 5000; i++) { - const o = { a: i, b: "item-" + i }; - acc += o.a; - } - return acc; - } - return { makeHandler, churn }; - "#, - ) - .expect("session init"); - - let make_handler = sess.export_fn("makeHandler").unwrap(); - let churn = sess.export_fn("churn").unwrap(); - let cb_val = sess.call_fn(make_handler, &[Val::num(10.0)]).unwrap(); - let cb = sess.pin_fn(cb_val).expect("pin closure"); - - assert_eq!( - sess.call_fn(cb, &[Val::num(2.0)]).unwrap().as_f64(), - Some(20.0) + let (mut s, started) = rt.session(COUNTER, &ProgramOptions::new()); + assert_eq!(ok(&started), Json::Null); + assert_eq!(ok(&s.call("add", &args(&[json!(3)]))), json!(3)); + assert_eq!(ok(&s.call("add", &args(&[json!(4)]))), json!(7)); + let later = s.call("later", &args(&[json!(1)])); + assert_eq!(ok(&later), json!({ "count": 8 })); + assert_eq!(later.log_lines(), vec!["at 8"]); + // A thrown error fails that call only, located as a run's is. + let e = failed(&s.call("fail", &[])).clone(); + assert_eq!(e.kind, DiagnosticKind::ExecutionFailure); + assert!( + e.message.to_string_lossy().starts_with("TypeError: no"), + "{e:?}" ); - let _ = sess.call_fn(churn, &[]).unwrap(); - sess.collect_garbage(); - assert_eq!( - sess.call_fn(cb, &[Val::num(5.0)]).unwrap().as_f64(), - Some(70.0) + assert_eq!(e.location, Some((6, 18))); + assert_eq!(ok(&s.call("add", &args(&[json!(1)]))), json!(9)); + let missing = failed(&s.call("nope", &[])).clone(); + assert!( + missing + .message + .to_string_lossy() + .contains("no function nope"), + "{missing:?}" ); } #[test] -fn gc_write_barrier_protects_white_objects_pinned_or_globalized_mid_mark() { +fn a_top_level_that_fails_fails_every_call() { let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function makeEphemeral(tag) { - return { tag, nested: { payload: "alive-" + tag, n: 42 } }; - } - function allocatePressure() { - const keep = []; - for (let i = 0; i < 6000; i++) { - keep.push({ i, text: "fill-" + i }); - } - return keep.length; - } - function readGlobalPayload() { - return midMarkGlobal.nested.payload; - } - return { makeEphemeral, allocatePressure, readGlobalPayload }; - "#, - ) - .expect("session init"); - - let make_ephemeral = sess.export_fn("makeEphemeral").unwrap(); - let allocate_pressure = sess.export_fn("allocatePressure").unwrap(); - let read_global_payload = sess.export_fn("readGlobalPayload").unwrap(); - - // Ensure GC starts cleanly from Phase::Idle. - sess.collect_garbage(); - - // Create two unrooted objects while GC is idle (both start WHITE on next mark cycle). - let tag_a = sess.ctx().new_str("pin"); - let tag_b = sess.ctx().new_str("global"); - let white_for_pin = sess.call_fn(make_ephemeral, &[tag_a]).unwrap(); - let white_for_global = sess.call_fn(make_ephemeral, &[tag_b]).unwrap(); - - // Allocate >64K slots directly from Rust so heap crosses gc.trigger while still in Phase::Idle, - // then run a single gc_step() to transition deterministically into Phase::Mark while both - // unrooted objects are WHITE. - { - let mut ctx = sess.ctx(); - for _ in 0..75_000 { - let _ = ctx.new_object(0); - } - } - sess.gc_step(); - - // Root both WHITE objects mid-mark via pin_val and set_global. - let pinned_handle = sess.pin_val(white_for_pin); - sess.set_global("midMarkGlobal", white_for_global); - - // Finish the mark/sweep cycle and allocate over any freed slots. - sess.collect_garbage(); - let _ = sess.call_fn(allocate_pressure, &[]).unwrap(); - sess.collect_garbage(); - - let k_nested = sess.key("nested"); - let k_payload = sess.key("payload"); - let k_n = sess.key("n"); - - { - let ctx = sess.ctx(); - let val = ctx.get_val(pinned_handle); - let nested = ctx.obj_get(val, k_nested).expect("nested survived GC"); - assert_eq!(ctx.obj_get_str(nested, k_payload), Some("alive-pin")); - assert_eq!(ctx.obj_get_f64(nested, k_n), Some(42.0)); - } - - let global_payload = sess.call_fn(read_global_payload, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(global_payload), Some("alive-global")); + let (mut s, started) = rt.session("throw new Error('setup')", &ProgramOptions::new()); + let first = failed(&started).message.to_string_lossy().into_owned(); + assert!(first.starts_with("Error: setup"), "{first}"); + let again = failed(&s.call("anything", &[])) + .message + .to_string_lossy() + .into_owned(); + assert_eq!(again, first); + let (mut s, started) = rt.session("return {", &ProgramOptions::new()); + assert_eq!(failed(&started).kind, DiagnosticKind::ParseError); + assert_eq!(failed(&s.call("f", &[])).kind, DiagnosticKind::ParseError); } #[test] -fn call_direct_mid_mark_write_barrier_protects_white_argument_stored_in_black_container() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - let blackBox = null; - function makeEphemeral() { - return { inner: { secret: "survived-call-direct" } }; - } - function allocBlackAndStore(v) { - // Allocated during Phase::Mark => immediately BLACK; storing v into it relies on - // call_direct having shaded v on entry! - blackBox = { held: v }; - } - function readSecret() { - return blackBox.held.inner.secret; - } - return { makeEphemeral, allocBlackAndStore, readSecret }; - "#, - ) - .expect("session init"); - - let make_ephemeral = sess.export_fn("makeEphemeral").unwrap(); - let alloc_and_store = sess.export_fn("allocBlackAndStore").unwrap(); - let read_secret = sess.export_fn("readSecret").unwrap(); - - sess.collect_garbage(); - let white_arg = sess.call_fn(make_ephemeral, &[]).unwrap(); - - // Enter Phase::Mark while white_arg is unrooted (WHITE). - { - let mut ctx = sess.ctx(); - for _ in 0..75_000 { - let _ = ctx.new_object(0); - } - } - sess.gc_step(); - - // Pass WHITE arg into JS via call_fn; JS stores it into a freshly allocated BLACK object. - let _ = sess.call_fn(alloc_and_store, &[white_arg]).unwrap(); - - // Sweep and churn heap. - sess.collect_garbage(); - { - let mut ctx = sess.ctx(); - for _ in 0..5_000 { - let _ = ctx.new_object(0); - } - } - sess.collect_garbage(); - - let out = sess.call_fn(read_secret, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(out), Some("survived-call-direct")); +fn each_call_gets_the_whole_timeout() { + let rt = Runtime::make().limits(Limits { + timeout_ms: Some(200), + ..Default::default() + }); + let (mut s, started) = rt.session("return { f: () => 1 }", &ProgramOptions::new()); + ok(&started); + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(ok(&s.call("f", &[])), json!(1)); + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(ok(&s.call("f", &[])), json!(1)); } #[test] -fn exports_stay_rooted_independently_of_user_pin_slot_zero() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - return { - ping() { return "still-alive"; }, - }; - "#, - ) - .expect("session init"); - - // First user pin takes pinned slot 0; unpinning it must never affect Session::exports. - let first_pin = sess.pin_val(Val::num(123.0)); - assert_eq!(first_pin.raw() as u32, 0); - sess.unpin_val(first_pin); - sess.collect_garbage(); - { - let mut ctx = sess.ctx(); - for _ in 0..5_000 { - let _ = ctx.new_object(0); - } - } - sess.collect_garbage(); +fn a_limit_a_call_passes_leaves_the_session_failed() { + let rt = Runtime::make().limits(Limits { + timeout_ms: Some(100), + ..Default::default() + }); + let (mut s, _) = rt.session( + "let n = 0; return { spin() { while (true) n++; }, n: () => n }", + &ProgramOptions::new(), + ); + assert_eq!( + failed(&s.call("spin", &[])).kind, + DiagnosticKind::TimeoutExceeded + ); + assert_eq!( + failed(&s.call("n", &[])).kind, + DiagnosticKind::TimeoutExceeded + ); + assert!(s.save().is_err()); - let ping = sess.export_fn("ping").expect("exports still rooted"); - let out = sess.call_fn(ping, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(out), Some("still-alive")); + let rt = Runtime::make().limits(Limits { + max_heap_bytes: Some(1 << 20), + ..Default::default() + }); + let (mut s, _) = rt.session( + "const kept = []; return { grow() { for (;;) kept.push('x'.repeat(100) + kept.length); }, size: () => kept.length }", + &ProgramOptions::new(), + ); + let e = failed(&s.call("grow", &[])).clone(); + assert_eq!(e.kind, DiagnosticKind::MemoryLimitExceeded); + let again = failed(&s.call("size", &[])).clone(); + assert_eq!(again.kind, DiagnosticKind::MemoryLimitExceeded); + assert_eq!(again.message, e.message); } #[test] -fn pin_handles_reject_aba_reuse_and_reuse_undefined_slots() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function fnA() { return 1; } - function fnB() { return 2; } - return { fnA, fnB }; - "#, - ) - .expect("session init"); - - let k_fn_a = sess.key("fnA"); - let k_fn_b = sess.key("fnB"); - let exports = sess.exports(); - let fn_a_val = sess.ctx().obj_get(exports, k_fn_a).unwrap(); - let fn_b_val = sess.ctx().obj_get(exports, k_fn_b).unwrap(); - - let h_a = sess.pin_fn(fn_a_val).unwrap(); - let slot_a = h_a.raw() as u32; - let gen_a = (h_a.raw() >> 32) as u32; - assert_eq!(gen_a, 1); - sess.unpin_fn(h_a); - - // Next pin must reuse the same slot with an incremented generation. - let h_b = sess.pin_fn(fn_b_val).unwrap(); - let slot_b = h_b.raw() as u32; - let gen_b = (h_b.raw() >> 32) as u32; - assert_eq!(slot_a, slot_b); - assert_eq!(gen_b, gen_a + 1); - - // Stale handle h_a must read as undefined and fail to call (never invoking fnB!). - assert!(sess.get_fn(h_a).is_undefined()); - assert!(sess.call_fn(h_a, &[]).is_err()); - - // Unpinning stale h_a must NOT free h_b. - sess.unpin_fn(h_a); - assert_eq!(sess.call_fn(h_b, &[]).unwrap().as_f64(), Some(2.0)); - - // Pinning and unpinning Val::UNDEFINED repeatedly must reuse the same slot without leaking. - let first_undef = sess.pin_val(Val::UNDEFINED); - let first_idx = first_undef.raw() as u32; - sess.unpin_val(first_undef); - for _ in 0..200 { - let h = sess.pin_val(Val::UNDEFINED); - assert_eq!(h.raw() as u32, first_idx); - sess.unpin_val(h); - } +fn a_call_collects_its_garbage_as_a_run_does() { + let rt = Runtime::make().limits(Limits { + max_heap_bytes: Some(4 << 20), + ..Default::default() + }); + let (mut s, started) = rt.session( + "return { churn(n) { let last; for (let i = 0; i < n; i++) last = { i, s: 'x'.repeat(64) + i }; return last.i } }", + &ProgramOptions::new(), + ); + ok(&started); + assert_eq!( + ok(&s.call("churn", &args(&[json!(200_000)]))), + json!(199_999) + ); } #[test] -fn local_host_functions_are_reclaimed_by_gc_and_stale_vals_are_bounds_checked() { - struct DropCounter(Rc>); - impl Drop for DropCounter { - fn drop(&mut self) { - self.0.set(self.0.get() + 1); - } - } - - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - let current = null; - function setHandler(fn) { current = fn; } - function invoke(x) { return current(x); } - return { setHandler, invoke }; - "#, - ) - .expect("session init"); - - let set_handler = sess.export_fn("setHandler").unwrap(); - let invoke = sess.export_fn("invoke").unwrap(); - let drops = Rc::new(Cell::new(0usize)); - let mut last_stale_fn = Val::UNDEFINED; - - for i in 0..32usize { - let guard = DropCounter(drops.clone()); - let local_fn = sess.ctx().new_local_fn("handler", move |_ctx, args| { - let _keep = &guard; - let x = args.get(0).as_f64().unwrap_or(0.0); - Ok(Val::num(x + i as f64)) - }); - last_stale_fn = local_fn; - let _ = sess.call_fn(set_handler, &[local_fn]).unwrap(); - let out = sess.call_fn(invoke, &[Val::num(10.0)]).unwrap(); - assert_eq!(out.as_f64(), Some(10.0 + i as f64)); - } - - // Clear the final reference and collect garbage; all 32 local closures must be dropped - // and trailing heap chunks truncated. - let _ = sess.call_fn(set_handler, &[Val::NULL]).unwrap(); - let stale_obj = sess.ctx().new_object(1); - sess.collect_garbage(); - assert_eq!(drops.get(), 32); - - // Accessing swept / truncated stale Vals via HostCtx must return None/false cleanly, never panic! - let k_x = sess.key("x"); - { - let mut ctx = sess.ctx(); - assert!(!ctx.is_fn(last_stale_fn)); - assert!(!ctx.is_object(stale_obj)); - assert!(!ctx.is_plain_object(stale_obj)); - assert!(!ctx.is_array(stale_obj)); - assert!(!ctx.is_bytes(stale_obj)); - assert!(!ctx.obj_is_frozen(stale_obj)); - assert_eq!(ctx.obj_id(stale_obj), None); - assert!(ctx.obj_get(stale_obj, k_x).is_none()); - assert!(!ctx.obj_for_each(stale_obj, |_, _| {})); - assert!(!ctx.array_for_each(stale_obj, |_| {})); - assert_eq!(ctx.array_len(stale_obj), None); - assert!(ctx.array_get(stale_obj, 0).is_none()); - assert_eq!(ctx.as_bytes(stale_obj), None); - assert_eq!(ctx.pin_fn(last_stale_fn), None); - ctx.obj_set(stale_obj, k_x, Val::num(1.0)); - ctx.array_push(stale_obj, Val::num(1.0)); - } - assert!(sess.call_val(last_stale_fn, Val::UNDEFINED, &[]).is_err()); +fn async_host_functions_settle_in_a_call() { + let rt = Runtime::make().globals(|_| { + [( + "later", + HostFunction::new_async(|args, _| async move { + Ok(HostValue::from(args[0].as_f64().unwrap_or(0.0) * 2.0)) + }), + )] + }); + let (mut s, started) = rt.session( + "return { async twice(n) { return await later(n) + await later(n) }, drop() { Promise.reject(new Error('lost')); return 1 } }", + &ProgramOptions::new(), + ); + ok(&started); + assert_eq!(ok(&s.call("twice", &args(&[json!(5)]))), json!(20)); + let dropped = s.call("drop", &[]); + assert_eq!(ok(&dropped), json!(1)); + assert_eq!(dropped.warnings.len(), 1); + assert!( + dropped.warnings[0] + .message + .to_string_lossy() + .contains("lost") + ); } #[test] -fn pinned_keys_vs_dynamic_unrooted_keys() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function readKey(obj, name) { return obj[name]; } - return { readKey }; - "#, - ) - .expect("session init"); - - let read_key = sess.export_fn("readKey").unwrap(); - let fixed_k = sess.key("fixedProp"); - - // Warm up and measure baseline memory. - sess.collect_garbage(); - let baseline = sess.memory_bytes(); +fn exports_and_values_with_accessors_work() { + let rt = Runtime::make().globals(|_| { + [( + "readX", + HostFunction::direct(|ctx, args| ctx.get(args.get(0), "x")), + )] + }); + let (mut s, started) = rt.session( + "let calls = 0; const o = { get x() { calls++; return 41 } }; return { o, get f() { return () => readX(o) + 1 }, calls: () => calls }", + &ProgramOptions::new(), + ); + ok(&started); + assert_eq!(ok(&s.call("f", &[])), json!(42)); + assert_eq!(ok(&s.call("calls", &[])), json!(1)); +} - // Create many transient objects using dynamic unrooted keys via obj_set_str. - for round in 0..4 { - { - let mut ctx = sess.ctx(); - for i in 0..500 { - let obj = ctx.new_object(2); - ctx.obj_set_str( - obj, - &format!("dynamic_ephemeral_key_{round}_{i}_payload_padding"), - Val::num(i as f64), - ); - ctx.obj_set_str( - obj, - &format!("other_dynamic_key_{round}_{i}"), - Val::bool(true), - ); +/// A direct host function that writes `args[2]` to `args[0][args[1]]` (an index when it is a number). +fn writer() -> HostFunction { + HostFunction::direct(|ctx, args| { + let (o, k, v) = (args.get(0), args.get(1), args.get(2)); + match k.as_f64() { + Some(i) => ctx.set_index(o, i as u32, v)?, + None => { + let k = ctx.text(k).unwrap_or_default().into_owned(); + ctx.set(o, &k, v)? } } - sess.collect_garbage(); - } + Ok(Val::undefined()) + }) +} - let after_dynamic = sess.memory_bytes(); - // Dynamic keys were not permanently rooted in host_atoms, so heap stays close to baseline. +#[test] +fn a_direct_write_is_a_programs_write() { + let rt = Runtime::make().globals(|_| [("write", writer())]); + let run = |code: &str| ok(&rt.execute(code)); + // An own setter and an inherited one run, and stay. + assert_eq!( + run( + "let seen = []; const o = { set v(x) { seen.push(x) } }; write(o, 'v', 1); write(o, 'v', 2); return [seen, Object.getOwnPropertyDescriptor(o, 'v').set !== undefined]" + ), + json!([[1, 2], true]) + ); + assert_eq!( + run( + "let seen; class A { set v(x) { seen = x } }; const a = new A(); write(a, 'v', 3); return [seen, Object.keys(a)]" + ), + json!([3, []]) + ); + // A frozen object and a read-only property refuse it, as the program's write would. + let frozen = + rt.execute("'use strict'; const o = Object.freeze({ a: 1 }); write(o, 'a', 2); return o.a"); assert!( - after_dynamic < baseline + 64 * 1024, - "dynamic keys leaked memory: baseline={baseline}, after={after_dynamic}" + failed(&frozen) + .message + .to_string_lossy() + .contains("TypeError"), + "{frozen:?}" ); - - // Pinned key still works cleanly after repeated full GCs. - let obj = { - let mut ctx = sess.ctx(); - ctx.new_object_with(&[(fixed_k, Val::num(777.0))]) - }; - let name_val = sess.ctx().new_str("fixedProp"); + let frozen_program = rt.execute("const o = Object.freeze({ a: 1 }); o.a = 2; return o.a"); + let frozen_direct = + rt.execute("const o = Object.freeze({ a: 1 }); write(o, 'a', 2); return o.a"); assert_eq!( - sess.call_fn(read_key, &[obj, name_val]).unwrap().as_f64(), - Some(777.0) + frozen_direct + .result + .map(|d| d.to_json()) + .map_err(|e| e.message), + frozen_program + .result + .map(|d| d.to_json()) + .map_err(|e| e.message) + ); + let readonly_program = rt + .execute("const o = {}; Object.defineProperty(o, 'a', { value: 1 }); o.a = 2; return o.a"); + let readonly_direct = rt.execute( + "const o = {}; Object.defineProperty(o, 'a', { value: 1 }); write(o, 'a', 2); return o.a", ); - assert_eq!(sess.ctx().key_name(fixed_k), "fixedProp"); -} - -#[test] -fn host_ctx_inspects_dense_and_sparse_arrays_and_sliced_bytes_and_object_invariants() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function makeDenseWithHole() { - const a = [1, , 3]; - return a; - } - function makeSparseWithAccessor() { - const a = [10, 20]; - a[10000005] = 30; - Object.defineProperty(a, "extra", { - get() { return 999; }, - enumerable: true, - configurable: true, - }); - return a; - } - function makeFrozen() { - return Object.freeze({ x: 1, y: "hi" }); - } - function makeWithAccessorAndSymbol() { - const o = { a: 1, [Symbol.toStringTag]: "Custom" }; - Object.defineProperty(o, "acc", { - get() { return 123; }, - enumerable: true, - configurable: true, - }); - return o; - } - function objectKeys(o) { - return Object.keys(o).join(","); - } - function makeByteViews() { - const ab = new ArrayBuffer(12); - const full = new Uint8Array(ab); - for (let i = 0; i < 12; i++) full[i] = i + 1; - const sub = full.subarray(3, 7); - const offsetView = new Uint8Array(ab, 4, 4); - const i32 = new Int32Array(ab, 0, 2); - return { ab, sub, offsetView, i32 }; - } - function echoBytes(u8) { - const out = new Uint8Array(u8.length); - for (let i = 0; i < u8.length; i++) out[i] = u8[i] ^ 0xFF; - return out; - } - return { - makeDenseWithHole, - makeSparseWithAccessor, - makeFrozen, - makeWithAccessorAndSymbol, - objectKeys, - makeByteViews, - echoBytes, - }; - "#, - ) - .expect("session init"); - - let make_dense = sess.export_fn("makeDenseWithHole").unwrap(); - let make_sparse = sess.export_fn("makeSparseWithAccessor").unwrap(); - let make_frozen = sess.export_fn("makeFrozen").unwrap(); - let make_acc_sym = sess.export_fn("makeWithAccessorAndSymbol").unwrap(); - let object_keys = sess.export_fn("objectKeys").unwrap(); - let make_byte_views = sess.export_fn("makeByteViews").unwrap(); - let echo_bytes = sess.export_fn("echoBytes").unwrap(); - - // Dense array with hole - let dense = sess.call_fn(make_dense, &[]).unwrap(); - { - let ctx = sess.ctx(); - assert!(ctx.is_array(dense)); - assert_eq!(ctx.type_name(dense), "array"); - assert_eq!(ctx.array_len(dense), Some(3)); - assert_eq!(ctx.array_get(dense, 0).and_then(Val::as_i64), Some(1)); - assert!(ctx.array_get(dense, 1).unwrap().is_undefined()); - assert_eq!(ctx.array_get(dense, 2).and_then(Val::as_i64), Some(3)); - assert!(ctx.array_get(dense, 3).is_none()); - - let mut seen = Vec::new(); - assert!(ctx.array_for_each(dense, |v| seen.push(v.as_i64()))); - assert_eq!(seen, vec![Some(1), None, Some(3)]); - } - - // Sparse array with an accessor at 10_000_004: must NOT leak internal Kind::Accessor! - let sparse = sess.call_fn(make_sparse, &[]).unwrap(); - { - let ctx = sess.ctx(); - assert!(ctx.is_array(sparse)); - assert_eq!(ctx.array_len(sparse), Some(10_000_006)); - assert_eq!(ctx.array_get(sparse, 0).and_then(Val::as_i64), Some(10)); - assert_eq!(ctx.array_get(sparse, 1).and_then(Val::as_i64), Some(20)); - assert!(ctx.array_get(sparse, 500_000).unwrap().is_undefined()); - assert!(ctx.array_get(sparse, 10_000_004).unwrap().is_undefined()); - assert_eq!( - ctx.array_get(sparse, 10_000_005).and_then(Val::as_i64), - Some(30) - ); - assert!(ctx.array_get(sparse, 10_000_006).is_none()); - - let mut seen = Vec::new(); - assert!(ctx.array_for_each(sparse, |v| { - // None of the yielded items may be an internal accessor object. - assert!(!v.is_obj_ref()); - seen.push(v.as_i64()); - })); - assert_eq!(seen, vec![Some(10), Some(20), Some(30)]); - } - - // Pushing to sparse array extends length cleanly. - sess.ctx().array_push(sparse, Val::num(40.0)); - assert_eq!(sess.ctx().array_len(sparse), Some(10_000_007)); assert_eq!( - sess.ctx() - .array_get(sparse, 10_000_006) - .and_then(Val::as_i64), - Some(40) + readonly_direct + .result + .map(|d| d.to_json()) + .map_err(|e| e.message), + readonly_program + .result + .map(|d| d.to_json()) + .map_err(|e| e.message) ); - - // Bytes views: subarray, byteOffset, ArrayBuffer, Int32Array, and type_name - let views = sess.call_fn(make_byte_views, &[]).unwrap(); - let k_ab = sess.key("ab"); - let k_sub = sess.key("sub"); - let k_off = sess.key("offsetView"); - let k_i32 = sess.key("i32"); - { - let ctx = sess.ctx(); - let ab = ctx.obj_get(views, k_ab).unwrap(); - let sub = ctx.obj_get(views, k_sub).unwrap(); - let off = ctx.obj_get(views, k_off).unwrap(); - let i32_v = ctx.obj_get(views, k_i32).unwrap(); - - assert_eq!(ctx.type_name(ab), "ArrayBuffer"); - assert_eq!( - ctx.as_bytes(ab), - Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12][..]) - ); - assert_eq!(ctx.type_name(sub), "Uint8Array"); - assert_eq!(ctx.as_bytes(sub), Some(&[4, 5, 6, 7][..])); - assert_eq!(ctx.as_bytes(off), Some(&[5, 6, 7, 8][..])); - assert_eq!(ctx.type_name(i32_v), "Int32Array"); - assert_eq!(ctx.as_bytes(i32_v), Some(&[1, 2, 3, 4, 5, 6, 7, 8][..])); - } - - let input_bytes = sess.ctx().new_bytes(&[0x00, 0x0F, 0xAA, 0xFF]); - assert!(sess.ctx().is_bytes(input_bytes)); - assert_eq!(sess.ctx().type_name(input_bytes), "Uint8Array"); + // A typed array converts and stores the number; an array's length follows its elements. assert_eq!( - sess.ctx().as_bytes(input_bytes), - Some(&[0x00, 0x0F, 0xAA, 0xFF][..]) + run( + "const t = new Uint8Array(2); write(t, 1, 257); write(t, 5, 1); return [t[1], t.length]" + ), + json!([1, 2]) ); - let echoed = sess.call_fn(echo_bytes, &[input_bytes]).unwrap(); assert_eq!( - sess.ctx().as_bytes(echoed), - Some(&[0xFF, 0xF0, 0x55, 0x00][..]) + run("const a = [1]; write(a, 3, 4); write(a, 'length', 2); return [a.length, a[3]]"), + json!([2, null]) ); +} - // Frozen object must refuse obj_set mutations cleanly. - let frozen = sess.call_fn(make_frozen, &[]).unwrap(); - let k_x = sess.key("x"); - let k_z = sess.key("z"); - sess.ctx().obj_set(frozen, k_x, Val::num(999.0)); - sess.ctx().obj_set(frozen, k_z, Val::num(123.0)); - { - let ctx = sess.ctx(); - assert!(ctx.is_object(frozen)); - assert!(ctx.is_plain_object(frozen)); - assert!(ctx.obj_is_frozen(frozen)); - assert!(ctx.obj_id(frozen).is_some()); - assert!(!ctx.is_fn(frozen)); - assert_eq!(ctx.obj_get_f64(frozen, k_x), Some(1.0)); - assert!(ctx.obj_get(frozen, k_z).is_none()); - - let mut pairs = Vec::new(); - assert!(ctx.obj_for_each(frozen, |k, v| { - pairs.push((k.to_owned(), v.as_i64(), ctx.to_string_lossy(v))); - })); - assert_eq!( - pairs, - vec![ - ("x".to_owned(), Some(1), None), - ("y".to_owned(), None, Some("hi".to_owned())), - ] - ); - - let mut keys = Vec::new(); - assert!(ctx.obj_for_each_key(frozen, |k, name, _| { - if name == "x" { - // "x" was rooted above via sess.key("x"), so obj_for_each_key yields Some(Key). - let k = k.expect("rooted key x"); - assert_eq!(ctx.key_name(k), "x"); - } else { - // "y" was never rooted via ctx.key(...), so no unrooted Key escapes. - assert_eq!(k, None); - } - keys.push(name.to_owned()); - })); - assert_eq!(keys, vec!["x".to_owned(), "y".to_owned()]); - } - - // Symbol keys (like Symbol.toStringTag) must be skipped by obj_for_each/obj_for_each_key, - // and overwriting a configurable accessor via obj_set resets flags to a normal data property. - let sym_obj = sess.call_fn(make_acc_sym, &[]).unwrap(); - let k_acc = sess.key("acc"); - { - let ctx = sess.ctx(); - let mut names = Vec::new(); - assert!(ctx.obj_for_each(sym_obj, |k, _| names.push(k.to_owned()))); - assert_eq!(names, vec!["a".to_owned()]); - assert!(ctx.obj_get(sym_obj, k_acc).is_none()); - } - sess.ctx().obj_set(sym_obj, k_acc, Val::num(555.0)); - assert_eq!(sess.ctx().obj_get_f64(sym_obj, k_acc), Some(555.0)); - - // Duplicate keys in new_object_with must deduplicate (last wins) so Object.keys has no dupes. - let k_a = sess.key("a"); - let k_b = sess.key("b"); - let dedup_obj = sess.ctx().new_object_with(&[ - (k_a, Val::num(1.0)), - (k_b, Val::num(2.0)), - (k_a, Val::num(3.0)), - ]); - assert_eq!(sess.ctx().obj_get_f64(dedup_obj, k_a), Some(3.0)); - let keys_str = sess.call_fn(object_keys, &[dedup_obj]).unwrap(); - assert_eq!(sess.ctx().as_str(keys_str), Some("a,b")); - - // Val predicates & strict integer conversions - assert!(Val::UNDEFINED.is_nullish()); - assert!(Val::NULL.is_nullish()); - assert!(Val::bool(true).is_bool()); - assert_eq!(Val::bool(true).as_bool(), Some(true)); - assert!(Val::num(42.0).is_num()); - assert_eq!(Val::num(42.0).as_i64(), Some(42)); - assert_eq!(Val::num(42.5).as_i64(), None); - assert_eq!(Val::num(42.0).as_u32(), Some(42)); - assert_eq!(Val::num(-5.0).as_u32(), None); - assert_eq!(Val::num(f64::NAN).as_u32(), None); - assert_eq!(Val::num(f64::INFINITY).as_u32(), None); - assert_eq!(Val::num(1.5).as_u32(), None); - assert_eq!(Val::num(-5.0).as_i32(), Some(-5)); - assert_eq!(Val::num(f64::NAN).as_i32(), None); - assert_eq!(Val::num(1e20).as_i32(), None); - let s = sess.ctx().new_str("hello"); - assert!(s.is_str()); - assert!(frozen.is_obj_ref()); +#[test] +fn direct_writes_count_against_the_heap() { + let rt = Runtime::make() + .globals(|_| [("write", writer())]) + .limits(Limits { + max_heap_bytes: Some(1 << 20), + ..Default::default() + }); + let o = + rt.execute("const a = []; for (let i = 0; i < 1e6; i++) write(a, i, i); return a.length"); + assert_eq!(failed(&o).kind, DiagnosticKind::MemoryLimitExceeded); } #[test] -fn direct_host_errors_and_reentrant_call_fn_val_and_recursion_limit() { +fn direct_functions_read_and_make_values_in_place() { let rt = Runtime::make().globals(|_| { - vec![ + [ ( - "boom", - HostValue::Function(HostFunction::direct(|ctx, _| { - Err(ctx.type_error("bad direct arg")) - })), + "describe", + HostFunction::direct(|ctx, args| { + let o = args.get(0); + let mut fields = Vec::new(); + for k in ctx.keys(o) { + let name = ctx.text(k).unwrap_or_default().into_owned(); + let v = ctx.get(o, &name)?; + let text = match ctx.type_of(v) { + "string" => ctx.text(v).unwrap_or_default().into_owned(), + t => t.to_owned(), + }; + let pair = format!("{name}={text}"); + fields.push(ctx.string(&pair)); + } + let tag = ctx.get(args.this(), "tag")?; + fields.push(tag); + Ok(ctx.array(&fields)) + }), ), ( - "callBack", - HostValue::Function(HostFunction::direct(|ctx, args| { - let f = args.get(0); - let arg = args.get(1); - ctx.call_fn_val(f, Val::UNDEFINED, &[arg]) - })), + "fill", + HostFunction::direct(|ctx, args| { + let Some(bytes) = ctx.bytes_mut(args.get(0)) else { + return Err(ctx.type_error("not bytes")); + }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = i as u8 + 1; + } + let sum: u32 = ctx + .bytes(args.get(0)) + .unwrap_or(&[]) + .iter() + .map(|b| *b as u32) + .sum(); + let out = ctx.object(); + ctx.set(out, "sum", Val::num(sum as f64))?; + Ok(out) + }), ), ] }); - - let mut sess = rt - .session( - r#" - function catchBoom() { - try { - boom(); - return "ok"; - } catch (e) { - return e.message; - } - } - function roundTrip(x) { - return callBack((v) => v * 7, x); - } - function mutualRecurse() { - function ping(n) { - return callBack(ping, n + 1); - } - try { - ping(0); - return "no error"; - } catch (e) { - return e.name + ":" + e.message; - } - } - return { catchBoom, roundTrip, mutualRecurse }; - "#, - ) - .expect("session init"); - - let catch_boom = sess.export_fn("catchBoom").unwrap(); - let round_trip = sess.export_fn("roundTrip").unwrap(); - let mutual_recurse = sess.export_fn("mutualRecurse").unwrap(); - - let out = sess.call_fn(catch_boom, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(out), Some("bad direct arg")); - - let rt_out = sess.call_fn(round_trip, &[Val::num(6.0)]).unwrap(); - assert_eq!(rt_out.as_f64(), Some(42.0)); - - let rec_out = sess.call_fn(mutual_recurse, &[]).unwrap(); - let ctx = sess.ctx(); - let rec_msg = ctx.as_str(rec_out).unwrap_or(""); - assert!( - rec_msg.contains("RangeError") && rec_msg.contains("Maximum call stack size exceeded"), - "expected RangeError stack overflow, got: {rec_msg}" + assert_eq!( + ok(&rt.execute( + "const h = { tag: 't', describe }; return h.describe({ b: 'x', 1: 2, a: undefined })" + )), + json!(["1=number", "b=x", "a=undefined", "t"]) ); -} - -#[test] -fn drain_jobs_supports_300_awaits_budgeted_draining_and_fatal_loop_cutoff() { - let rt = Runtime::make().limits(Limits { - clock: Clock::Wall, - ..Limits::default() - }); - let mut sess = rt - .session( - r#" - let total = 0; - async function awaitMany() { - let sum = 0; - for (let i = 0; i < 300; i++) { - sum += await i; - } - total = sum; - } - function getTotal() { - return total; - } - function startInfiniteMicrotasks() { - function loop() { - Promise.resolve().then(loop); - } - loop(); - } - return { awaitMany, getTotal, startInfiniteMicrotasks }; - "#, - ) - .expect("session init"); - - let await_many = sess.export_fn("awaitMany").unwrap(); - let get_total = sess.export_fn("getTotal").unwrap(); - let start_loop = sess.export_fn("startInfiniteMicrotasks").unwrap(); - - // Budgeted draining is non-destructive: drain 10 jobs, verify more remain, then finish all 300 awaits! - let _ = sess.call_fn(await_many, &[]).unwrap(); - assert!(sess.has_pending_jobs()); - assert!(sess.drain_jobs_budget(10).expect("partial drain")); - assert!(sess.has_pending_jobs()); - sess.drain_jobs().expect("finish 300 awaits"); - assert!(!sess.has_pending_jobs()); - // sum(0..300) = 299 * 300 / 2 = 44850 assert_eq!( - sess.call_fn(get_total, &[]).unwrap().as_f64(), - Some(44_850.0) + ok(&rt.execute("const f = new Float32Array([0]); const u = new Uint8Array(f.buffer, 1, 2); const r = fill(u); return [r.sum, Array.from(new Uint8Array(f.buffer))]")), + json!([3, [0, 1, 2, 0]]) ); - - // Infinite microtask loop trips drain_jobs() cap; arm_slice trips fatal SliceExceeded and clears jobs. - let _ = sess.call_fn(start_loop, &[]).unwrap(); - let cap_err = sess.drain_jobs().expect_err("must cap infinite microtasks"); - assert_eq!(cap_err.kind, DiagnosticKind::SliceExceeded); - assert!(sess.has_pending_jobs()); - - sess.arm_slice(20); - let fatal_err = sess - .drain_jobs_budget(usize::MAX) - .expect_err("slice must cut off runaway microtasks"); - sess.disarm_slice(); - assert_eq!(fatal_err.kind, DiagnosticKind::SliceExceeded); - assert!(!sess.has_pending_jobs()); -} - -#[test] -fn take_unhandled_rejections_never_executes_user_to_string_or_getters() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function triggerRejections() { - Promise.reject(new TypeError("invalid input")); - Promise.reject("plain rejection"); - Promise.reject({ toString() { while (true) {} } }); - Promise.reject({ - [Symbol.toPrimitive]() { while (true) {} }, - get message() { while (true) {} } - }); - } - return { triggerRejections }; - "#, - ) - .expect("session init"); - - let trigger = sess.export_fn("triggerRejections").unwrap(); - let _ = sess.call_fn(trigger, &[]).unwrap(); - sess.drain_jobs().expect("drain rejections"); - - let started = Instant::now(); - let rejections = sess.take_unhandled_rejections(); + let e = rt.execute("fill({})"); assert!( - started.elapsed() < Duration::from_secs(2), - "take_unhandled_rejections took too long" + failed(&e) + .message + .to_string_lossy() + .starts_with("TypeError: not bytes"), + "{e:?}" ); - assert_eq!(rejections.len(), 4); - assert_eq!(rejections[0], "TypeError: invalid input"); - assert_eq!(rejections[1], "plain rejection"); - assert_eq!(rejections[2], "[object]"); - assert_eq!(rejections[3], "[object]"); - assert!(sess.take_unhandled_rejections().is_empty()); } #[test] -fn session_start_enforces_thread_cpu_timeout_and_rejects_incomplete_init() { - let rt_cpu = Runtime::make().limits(Limits { - clock: Clock::ThreadCpu, - timeout_ms: Some(40), - ..Limits::default() +fn direct_functions_are_host_calls() { + let slept = HostFunction::direct(|_, _| { + std::thread::sleep(Duration::from_millis(60)); + Ok(Val::undefined()) }); - let outcome = match rt_cpu.session("while (true) {}") { - Ok(_) => panic!("infinite loop under ThreadCpu must time out"), - Err(err) => err, - }; - let diag = outcome.result.expect_err("expected TimeoutExceeded"); - assert_eq!(diag.kind, DiagnosticKind::TimeoutExceeded); - - // Top-level init that awaits an unresolved promise never completes -> rejected cleanly. - let rt_pending = Runtime::make(); - let pending_outcome = match rt_pending.session("await new Promise(() => {});") { - Ok(_) => panic!("incomplete top-level init must fail"), - Err(err) => err, - }; - assert!(pending_outcome.result.is_err()); -} - -#[test] -fn arm_and_disarm_slice_recovers_from_infinite_loops() { - let rt = Runtime::make().limits(Limits { - clock: Clock::Wall, - ..Limits::default() - }); - let mut sess = rt - .session( - r#" - function spin() { - while (true) {} - } - async function asyncSpin() { - while (true) {} - } - function add(a, b) { - return a + b; - } - return { spin, asyncSpin, add }; - "#, - ) - .expect("session init"); - - let spin = sess.export_fn("spin").unwrap(); - let async_spin = sess.export_fn("asyncSpin").unwrap(); - let add = sess.export_fn("add").unwrap(); - - // Sync infinite loop hits SliceExceeded and recovers. - sess.arm_slice(20); - let err = sess.call_fn(spin, &[]).expect_err("spin must time out"); - sess.disarm_slice(); - assert_eq!(err.kind, DiagnosticKind::SliceExceeded); - - // After disarm_slice, normal calls work cleanly. + let calls_back = HostFunction::direct(|ctx, args| ctx.call(args.get(0), Val::undefined(), &[])); + let rt = Runtime::make() + .globals(move |_| [("slept", slept.clone()), ("callsBack", calls_back.clone())]) + .limits(Limits { + slice_ms: Some(40), + ..Default::default() + }); + // The host's time is not the program's; the program's time in a call the host makes is. + assert_eq!(ok(&rt.execute("slept(); slept(); return 1")), json!(1)); + let spin = rt.execute("callsBack(() => { for (;;) {} })"); + assert_eq!(failed(&spin).kind, DiagnosticKind::SliceExceeded); + // A host function and the program calling each other run out of stack as a program does. + let deep = rt + .execute("function f() { return callsBack(f) } try { f() } catch (e) { return String(e) }"); assert_eq!( - sess.call_fn(add, &[Val::num(2.0), Val::num(3.0)]) - .unwrap() - .as_f64(), - Some(5.0) + ok(&deep), + json!("RangeError: Maximum call stack size exceeded") ); - - // Async infinite loop also unwinds cleanly (freeing its coroutine) and recovers. - sess.arm_slice(20); - let err = sess - .call_fn(async_spin, &[]) - .expect_err("asyncSpin must time out"); - sess.disarm_slice(); - assert_eq!(err.kind, DiagnosticKind::SliceExceeded); - - sess.arm_slice(200); - let sum = sess - .call_fn(add, &[Val::num(10.0), Val::num(25.0)]) - .unwrap(); - sess.disarm_slice(); - assert_eq!(sum.as_f64(), Some(35.0)); } #[test] -fn collect_garbage_mid_mark_collects_newly_unpinned_objects() { - struct DropGuard(Rc>); - impl Drop for DropGuard { - fn drop(&mut self) { - self.0.set(self.0.get() + 1); - } - } - - let rt = Runtime::make(); - let mut sess = rt.session("return {};").expect("session init"); - - sess.collect_garbage(); - let drops = Rc::new(Cell::new(0usize)); - let guard = DropGuard(drops.clone()); - let local_fn = sess.ctx().new_local_fn("ephemeral", move |_, _| { - let _keep = &guard; - Ok(Val::UNDEFINED) +fn a_direct_call_refuses_a_suspend_while_it_runs() { + let entered = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let gate = entered.clone(); + let rt = Runtime::make().globals(move |_| { + let gate = gate.clone(); + [( + "busy", + HostFunction::direct(move |_, _| { + let (m, c) = &*gate; + *m.lock().unwrap() = true; + c.notify_all(); + std::thread::sleep(Duration::from_millis(100)); + Ok(Val::num(1.0)) + }), + )] }); - let h = sess.pin_val(local_fn); - assert_eq!(drops.get(), 0); - - // Cross GC trigger and enter Phase::Mark while h is still pinned (so local_fn is marked live - // in the in-progress cycle). - { - let mut ctx = sess.ctx(); - for _ in 0..75_000 { - let _ = ctx.new_object(0); + let program = rt.program("return busy()", &ProgramOptions::new()); + let suspender = program.suspender(); + std::thread::scope(|scope| { + let run = scope.spawn(move || program.run_resumable()); + let (m, c) = &*entered; + let mut on = m.lock().unwrap(); + while !*on { + on = c.wait(on).unwrap(); } - } - sess.gc_step(); - assert_eq!(drops.get(), 0); - - // Unpin h mid-mark, then call collect_garbage() ONCE. It must finish the in-progress cycle - // and run a fresh full cycle so the newly unpinned closure is actually swept and dropped! - sess.unpin_val(h); - sess.collect_garbage(); - assert_eq!( - drops.get(), - 1, - "expected unpinned mid-mark closure to be actually swept and dropped" - ); + drop(on); + let refused = suspender.suspend(None).unwrap_err(); + assert_eq!(refused.running.len(), 1); + assert_eq!(refused.running[0].path, "busy"); + assert!(run.join().unwrap().is_ok()); + }); } #[test] -fn single_call_fn_with_many_transient_allocations_runs_incremental_gc_without_oom() { - let rt = Runtime::make().limits(Limits { - max_heap_bytes: Some(8 * 1024 * 1024), - ..Limits::default() - }); - let mut sess = rt - .session( - r#" - function allocateTransient() { - let sum = 0; - for (let i = 0; i < 260000; i++) { - const tmp = { x: i, y: i + 1 }; - sum += tmp.x & 1; - } - return sum; - } - return { allocateTransient }; - "#, - ) - .expect("session init"); - - let alloc_fn = sess.export_fn("allocateTransient").unwrap(); - let out = sess - .call_fn(alloc_fn, &[]) - .expect("incremental GC must prevent OOM on 260k transient objects"); - assert_eq!(out.as_f64(), Some(130_000.0)); +fn direct_functions_work_in_a_namespace() { + let ns = Namespace::new( + |_| Ok(vec!["sum".into()]), + |path| match path { + [name] if name.to_string_lossy() == "sum" => { + Resolved::Function(HostFunction::direct(|ctx, args| { + let a = ctx.get_index(args.get(0), 0)?.as_f64().unwrap_or(0.0); + let b = ctx.get_index(args.get(0), 1)?.as_f64().unwrap_or(0.0); + Ok(Val::num(a + b)) + })) + } + _ => Resolved::Missing(psychoscript::Failure::missing("no such function")), + }, + ); + let rt = Runtime::make().globals(move |_| [("math", ns.clone())]); + assert_eq!(ok(&rt.execute("return math.sum([2, 3])")), json!(5)); } #[test] -fn per_session_user_data_and_nested_session_drop_safety() { - #[derive(Clone)] - struct AppState { - hits: Rc>, - } - +fn a_session_saves_between_calls_and_continues_from_its_state() { let rt = Runtime::make().globals(|_| { - vec![( - "bump", - HostValue::Function(HostFunction::direct(|ctx, _| { - let next = ctx - .with_user_data::(|s| { - let v = s.hits.get() + 1; - s.hits.set(v); - v - }) - .unwrap_or(0); - Ok(Val::num(next as f64)) - })), + [( + "double", + HostFunction::direct(|_, args| Ok(Val::num(args.get(0).as_f64().unwrap_or(0.0) * 2.0))), )] }); - - let mut outer = rt - .session("return { go: () => bump() };") - .expect("outer session"); - let state = AppState { - hits: Rc::new(Cell::new(0)), + let (mut s, _) = rt.session(COUNTER, &ProgramOptions::new()); + assert_eq!(ok(&s.call("add", &args(&[json!(2)]))), json!(2)); + let bytes = to_bytes(&s.save().unwrap()); + assert_eq!(ok(&s.call("add", &args(&[json!(100)]))), json!(102)); + let state = from_bytes(&bytes).unwrap(); + let mut again = rt.restore_session(&state).unwrap(); + assert_eq!(ok(&again.call("add", &args(&[json!(1)]))), json!(3)); + assert_eq!( + ok(&again.call("later", &args(&[json!(1)]))), + json!({ "count": 4 }) + ); + // A session's state is not a run's, nor a run's a session's. + assert!(rt.resume(&state).is_err()); + let program = rt.program("for (;;) {}", &ProgramOptions::new()); + let suspender = program.suspender(); + let suspended = std::thread::scope(|scope| { + let run = scope.spawn(move || program.run_resumable()); + let suspended = suspender.suspend(None).unwrap(); + assert!(run.join().unwrap().is_ok()); + suspended + }); + let psychoscript::RunOutcome::Suspended(run_state) = suspended else { + panic!("not suspended") }; - outer.set_user_data(state.clone()); - - let go = outer.export_fn("go").unwrap(); - assert_eq!(outer.call_fn(go, &[]).unwrap().as_f64(), Some(1.0)); - assert_eq!(outer.call_fn(go, &[]).unwrap().as_f64(), Some(2.0)); - assert_eq!(outer.get_user_data::().unwrap().hits.get(), 2); - - outer.with_user_data_mut::(|s| s.hits.set(10)); - assert_eq!(outer.call_fn(go, &[]).unwrap().as_f64(), Some(11.0)); - - // Store a nested Session inside user_data to ensure dropping outer does not re-entrantly - // borrow SESSION_STORES while removing the outer store. - struct NestedSession(#[allow(dead_code)] Session); - let inner = rt.session("return {};").expect("inner session"); - outer.set_user_data(NestedSession(inner)); - drop(outer); + assert!(rt.restore_session(&run_state.state).is_err()); } +/// The state this test's session saves goes to a new process of this test binary, which restores and calls it. #[test] -fn direct_callback_reentering_js_cannot_bypass_arm_slice() { - let rt = Runtime::make() - .limits(Limits { - clock: Clock::Wall, - ..Limits::default() - }) - .globals(|_| { - vec![( - "callBack", - HostValue::Function(HostFunction::direct(|ctx, args| { - ctx.call_fn_val(args.get(0), Val::UNDEFINED, &[]) - })), - )] - }); - - let mut sess = rt - .session( - r#" - function spinViaDirect() { - for (;;) { - callBack(() => { - let x = 0; - for (let i = 0; i < 500; i++) x += i; - return x; - }); - } - } - return { spinViaDirect }; - "#, - ) - .expect("session init"); - - let spin = sess.export_fn("spinViaDirect").unwrap(); - sess.arm_slice(25); - let err = sess - .call_fn(spin, &[]) - .expect_err("direct re-entry must still trip arm_slice"); - sess.disarm_slice(); - assert_eq!(err.kind, DiagnosticKind::SliceExceeded); -} - -#[test] -fn obj_set_preserves_existing_data_property_descriptor_flags() { +fn a_session_continues_in_another_process() { let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function makeObj() { - const o = {}; - Object.defineProperty(o, "hidden", { - value: 1, - writable: true, - enumerable: false, - configurable: false, - }); - return o; - } - function inspect(o) { - const d = Object.getOwnPropertyDescriptor(o, "hidden"); - return [d.value, d.writable, d.enumerable, d.configurable].join(":"); - } - return { makeObj, inspect }; - "#, - ) - .expect("session init"); - - let make_obj = sess.export_fn("makeObj").unwrap(); - let inspect = sess.export_fn("inspect").unwrap(); - - let obj = sess.call_fn(make_obj, &[]).unwrap(); - let k_hidden = sess.key("hidden"); - sess.ctx().obj_set(obj, k_hidden, Val::num(42.0)); - - let out = sess.call_fn(inspect, &[obj]).unwrap(); - assert_eq!(sess.ctx().as_str(out), Some("42:true:false:false")); -} - -#[test] -fn writing_stale_post_gc_val_sanitizes_to_undefined_without_panicking() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function inspectProp(o, arg) { - return typeof o.stale + ":" + typeof arg; - } - return { inspectProp }; - "#, - ) - .expect("session init"); - - let inspect_prop = sess.export_fn("inspectProp").unwrap(); - - // Allocate an unrooted object and sweep + truncate trailing heap chunks so its Id is OOB. - let stale_obj = sess.ctx().new_object(1); - sess.collect_garbage(); - - let holder = sess.ctx().new_object(1); - let k_stale = sess.key("stale"); - sess.ctx().obj_set(holder, k_stale, stale_obj); - - let out = sess.call_fn(inspect_prop, &[holder, stale_obj]).unwrap(); - assert_eq!(sess.ctx().as_str(out), Some("undefined:undefined")); -} - -#[test] -fn cross_session_handles_are_rejected_for_read_call_and_unpin() { - let rt = Runtime::make(); - let mut sess_a = rt - .session("function a() { return 111; } return { a, val: { x: 1 } };") - .expect("session a"); - let mut sess_b = rt - .session("function b() { return 222; } return { b, val: { x: 2 } };") - .expect("session b"); - - let fn_a = sess_a.export_fn("a").unwrap(); - let fn_b = sess_b.export_fn("b").unwrap(); - - let k_val_a = sess_a.key("val"); - let k_val_b = sess_b.key("val"); - let exp_a = sess_a.exports(); - let exp_b = sess_b.exports(); - let v_a = sess_a.ctx().obj_get(exp_a, k_val_a).unwrap(); - let v_b = sess_b.ctx().obj_get(exp_b, k_val_b).unwrap(); - let h_a = sess_a.pin_val(v_a); - let h_b = sess_b.pin_val(v_b); - - // Handle from Session A must NEVER read, call, or unpin Session B's matching slot. - assert!(sess_b.get_fn(fn_a).is_undefined()); - assert!(sess_b.get_val(h_a).is_undefined()); - assert!(sess_b.call_fn(fn_a, &[]).is_err()); - sess_b.unpin_fn(fn_a); - sess_b.unpin_val(h_a); - - // Session B's own handles remain completely intact! - assert_eq!(sess_b.call_fn(fn_b, &[]).unwrap().as_f64(), Some(222.0)); - let k_x_b = sess_b.key("x"); - let b_val = sess_b.get_val(h_b); - assert_eq!(sess_b.ctx().obj_get_f64(b_val, k_x_b), Some(2.0)); -} - -#[test] -fn std_bigint_prototype_stays_rooted_after_replacing_bigint_global() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function touchBigInt() { - return BigInt(1).toString(); - } - function formatLiteral() { - return (12345678901234567890n).toString(); - } - return { touchBigInt, formatLiteral }; - "#, - ) - .expect("session init"); - - let touch = sess.export_fn("touchBigInt").unwrap(); - let format_lit = sess.export_fn("formatLiteral").unwrap(); - - let s1 = sess.call_fn(touch, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(s1), Some("1")); - - // Overwrite BigInt global and force full GC + churn; std.bigint must remain rooted! - sess.set_global("BigInt", Val::UNDEFINED); - sess.collect_garbage(); - { - let mut ctx = sess.ctx(); - for _ in 0..5_000 { - let _ = ctx.new_object(0); - } - } - sess.collect_garbage(); - - let s2 = sess.call_fn(format_lit, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(s2), Some("12345678901234567890")); -} - -#[test] -fn array_from_async_and_iter_close_run_cleanly_under_session_and_gc_stress() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - let out = null; - async function run() { - let closed = 0; - const iter = { - i: 0, - [Symbol.iterator]() { return this; }, - next() { - if (this.i++ < 5) { - return { value: Promise.reject("stop-" + this.i), done: false }; - } - return { value: undefined, done: true }; - }, - return() { - closed += 1; - // Allocate inside iter_close to exercise GC under stress! - for (let j = 0; j < 200; j++) { - const o = { j, s: "close-" + j }; - if (o.j < 0) break; - } - return { value: undefined, done: true }; - }, - }; - try { - await Array.fromAsync(iter); - out = "unexpected-ok"; - } catch (e) { - out = e + ":closed=" + closed; - } - } - function getOut() { return out; } - return { run, getOut }; - "#, - ) - .expect("session init"); - - let run_fn = sess.export_fn("run").unwrap(); - let get_out = sess.export_fn("getOut").unwrap(); - - let _ = sess.call_fn(run_fn, &[]).unwrap(); - sess.drain_jobs().expect("drain Array.fromAsync"); - let out = sess.call_fn(get_out, &[]).unwrap(); - assert_eq!(sess.ctx().as_str(out), Some("stop-1:closed=1")); -} - -#[test] -fn stale_raw_val_during_phase_sweep_is_sanitized_to_undefined() { - let rt = Runtime::make(); - let mut sess = rt - .session( - r#" - function makeEphemeral() { - return { tag: "doomed-in-sweep" }; - } - return { makeEphemeral }; - "#, - ) - .expect("session init"); - - let make_ephemeral = sess.export_fn("makeEphemeral").unwrap(); - sess.collect_garbage(); - - // Allocate many unrooted objects so sweeping takes multiple incremental gc_step() calls, - // and keep a raw unpinned Val to the last doomed object (high heap id, near end of sweep range). - { - let mut ctx = sess.ctx(); - for _ in 0..80_000 { - let _ = ctx.new_object(0); - } - } - let doomed_obj = sess.call_fn(make_ephemeral, &[]).unwrap(); - let doomed_str = sess.ctx().new_str("doomed-sweep-string"); - - // Advance incremental GC steps until Mark finishes and Phase::Sweep begins (works under both - // normal mode and PSYCHOSCRIPT_GC_STRESS=1). Once Phase::Sweep starts, live_obj rejects the - // doomed WHITE slot even before the sweep cursor reaches it. - let mut entered_sweep = false; - for _ in 0..500 { - sess.gc_step(); - if !sess.ctx().is_object(doomed_obj) { - entered_sweep = true; - break; - } + if let Some(path) = std::env::var_os("PSYCHOSCRIPT_SESSION_STATE") { + let bytes = std::fs::read(&path).unwrap(); + let mut s = rt.restore_session(&from_bytes(&bytes).unwrap()).unwrap(); + let out = s.call("add", &args(&[json!(10)])); + std::fs::write(path, ok(&out).to_string()).unwrap(); + return; } - assert!( - entered_sweep, - "GC must reject doomed WHITE object upon entering Phase::Sweep" - ); - - // Even if we're mid-Sweep before doomed_obj's slot is reached, sanitize_val / pin_val / live_obj - // must treat the unswept WHITE slot as dead (undefined) rather than pinning a doomed id! - let pinned_obj = sess.pin_val(doomed_obj); - let pinned_str = sess.pin_val(doomed_str); - assert!(sess.get_val(pinned_obj).is_undefined()); - assert!(sess.get_val(pinned_str).is_undefined()); - assert!(!sess.ctx().is_object(doomed_obj)); - assert_eq!(sess.ctx().as_str(doomed_str), None); - - // Finish sweep cleanly; pinned handles stay safely undefined. - sess.collect_garbage(); - assert!(sess.get_val(pinned_obj).is_undefined()); - assert!(sess.get_val(pinned_str).is_undefined()); -} - -#[test] -fn standalone_execute_runs_have_distinct_handle_session_ids() { - let saved = Arc::new(Mutex::new(None::)); - let rt = Runtime::make().globals({ - let saved = saved.clone(); - move |_| { - let saved = saved.clone(); - vec![( - "pinOrRead", - HostValue::Function(HostFunction::direct(move |ctx, args| { - let mut guard = saved.lock().unwrap(); - if let Some(prev_handle) = *guard { - // Must reject handle created in an earlier Runtime::execute VM! - let v = ctx.get_val(prev_handle); - return Ok(Val::bool(v.is_undefined())); - } - let h = ctx.pin_val(args.get(0)); - *guard = Some(h); - Ok(Val::bool(true)) - })), - )] - } - }); - - let r1 = rt.execute("return pinOrRead({ a: 1 });").result.unwrap(); - assert_eq!(r1, psychoscript::Data::Bool(true)); - - // In a second standalone execute() VM, reading the handle from run 1 must return undefined. - let r2 = rt.execute("return pinOrRead({ a: 2 });").result.unwrap(); - assert_eq!(r2, psychoscript::Data::Bool(true)); + let (mut s, _) = rt.session(COUNTER, &ProgramOptions::new()); + ok(&s.call("add", &args(&[json!(5)]))); + let path = + std::env::temp_dir().join(format!("psychoscript-session-{}.json", std::process::id())); + std::fs::write(&path, to_bytes(&s.save().unwrap())).unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "a_session_continues_in_another_process", + "--nocapture", + ]) + .env("PSYCHOSCRIPT_SESSION_STATE", &path) + .status() + .unwrap(); + assert!(status.success()); + let answer = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(answer, "15"); } From 8fa8b86261023316fe8e978dbc9f5577e6eac444 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 16:58:39 +0000 Subject: [PATCH 3/6] fix(rust): a session collects while it waits for its next call --- rust/crates/psychoscript/src/program.rs | 7 ++++++- rust/crates/psychoscript/tests/session.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index baf60a25..6a9f8658 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -351,14 +351,19 @@ impl<'a> Program<'a> { }; // The top level ran: what runs next comes from the calls. r.mark_resumed(); - match ended { + let outcome = match ended { Some(Ok(RunOutcome::Done(outcome))) => outcome, Some(_) => unreachable!("a session's run is neither suspended nor dropped"), None => { r.vm.fatal = Some((crate::DiagnosticKind::ExecutionFailure, CANNOT_WAIT.into())); run::outcome(&mut r.vm, &r.code) } + }; + // The run now waits for its next call: where a run that waits collects. + if r.vm.fatal.is_none() { + r.vm.gc_idle(); } + outcome } /// A session's state between its calls, which [`Program::restore_session`] continues. diff --git a/rust/crates/psychoscript/tests/session.rs b/rust/crates/psychoscript/tests/session.rs index c07134e6..448eb2f8 100644 --- a/rust/crates/psychoscript/tests/session.rs +++ b/rust/crates/psychoscript/tests/session.rs @@ -148,6 +148,18 @@ fn a_call_collects_its_garbage_as_a_run_does() { ); } +#[test] +fn a_session_collects_between_calls() { + let rt = Runtime::make(); + let (mut s, _) = rt.session(COUNTER, &ProgramOptions::new()); + for _ in 0..20_000 { + ok(&s.call("add", &args(&[json!(1)]))); + } + // What its calls left behind is collected while it waits for the next, as a waiting run's is. + let saved = to_bytes(&s.save().unwrap()).len(); + assert!(saved < 400_000, "{saved} bytes"); +} + #[test] fn async_host_functions_settle_in_a_call() { let rt = Runtime::make().globals(|_| { From bb41376d55fb9070de331c7d426e374c63391e42 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 17:02:24 +0000 Subject: [PATCH 4/6] test(rust): session timeouts and direct host time with loops that check the clock --- rust/crates/psychoscript/tests/session.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rust/crates/psychoscript/tests/session.rs b/rust/crates/psychoscript/tests/session.rs index 448eb2f8..fe7e93dc 100644 --- a/rust/crates/psychoscript/tests/session.rs +++ b/rust/crates/psychoscript/tests/session.rs @@ -88,7 +88,10 @@ fn each_call_gets_the_whole_timeout() { timeout_ms: Some(200), ..Default::default() }); - let (mut s, started) = rt.session("return { f: () => 1 }", &ProgramOptions::new()); + let (mut s, started) = rt.session( + "return { f() { let n = 0; for (let i = 0; i < 100000; i++) n++; return 1 } }", + &ProgramOptions::new(), + ); ok(&started); std::thread::sleep(Duration::from_millis(300)); assert_eq!(ok(&s.call("f", &[])), json!(1)); @@ -380,7 +383,12 @@ fn direct_functions_are_host_calls() { ..Default::default() }); // The host's time is not the program's; the program's time in a call the host makes is. - assert_eq!(ok(&rt.execute("slept(); slept(); return 1")), json!(1)); + assert_eq!( + ok(&rt.execute( + "slept(); slept(); let n = 0; for (let i = 0; i < 100000; i++) n++; return 1" + )), + json!(1) + ); let spin = rt.execute("callsBack(() => { for (;;) {} })"); assert_eq!(failed(&spin).kind, DiagnosticKind::SliceExceeded); // A host function and the program calling each other run out of stack as a program does. From 8b4957091d0f74d2bd8deee3fd8574c65b3deabb Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 17:23:43 +0000 Subject: [PATCH 5/6] test(rust): session timing tests with room under GC stress --- rust/crates/psychoscript/tests/session.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/rust/crates/psychoscript/tests/session.rs b/rust/crates/psychoscript/tests/session.rs index fe7e93dc..510d8e92 100644 --- a/rust/crates/psychoscript/tests/session.rs +++ b/rust/crates/psychoscript/tests/session.rs @@ -85,17 +85,17 @@ fn a_top_level_that_fails_fails_every_call() { #[test] fn each_call_gets_the_whole_timeout() { let rt = Runtime::make().limits(Limits { - timeout_ms: Some(200), + timeout_ms: Some(500), ..Default::default() }); let (mut s, started) = rt.session( - "return { f() { let n = 0; for (let i = 0; i < 100000; i++) n++; return 1 } }", + "return { f() { let n = 0; for (let i = 0; i < 25000; i++) n++; return 1 } }", &ProgramOptions::new(), ); ok(&started); - std::thread::sleep(Duration::from_millis(300)); + std::thread::sleep(Duration::from_millis(600)); assert_eq!(ok(&s.call("f", &[])), json!(1)); - std::thread::sleep(Duration::from_millis(300)); + std::thread::sleep(Duration::from_millis(600)); assert_eq!(ok(&s.call("f", &[])), json!(1)); } @@ -372,21 +372,20 @@ fn direct_functions_read_and_make_values_in_place() { #[test] fn direct_functions_are_host_calls() { let slept = HostFunction::direct(|_, _| { - std::thread::sleep(Duration::from_millis(60)); + std::thread::sleep(Duration::from_millis(200)); Ok(Val::undefined()) }); let calls_back = HostFunction::direct(|ctx, args| ctx.call(args.get(0), Val::undefined(), &[])); let rt = Runtime::make() .globals(move |_| [("slept", slept.clone()), ("callsBack", calls_back.clone())]) .limits(Limits { - slice_ms: Some(40), + slice_ms: Some(150), ..Default::default() }); // The host's time is not the program's; the program's time in a call the host makes is. assert_eq!( - ok(&rt.execute( - "slept(); slept(); let n = 0; for (let i = 0; i < 100000; i++) n++; return 1" - )), + ok(&rt + .execute("slept(); slept(); let n = 0; for (let i = 0; i < 25000; i++) n++; return 1")), json!(1) ); let spin = rt.execute("callsBack(() => { for (;;) {} })"); From 89164174730c19d2e184acee51f21779d5fe481e Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Thu, 3 Dec 2026 01:13:35 +0100 Subject: [PATCH 6/6] fix(rust): session getters, carried budget reset, top-level promise exports, and arg depth limit --- rust/crates/psychoscript/src/convert.rs | 62 ++++++ rust/crates/psychoscript/src/cross.rs | 23 ++- rust/crates/psychoscript/src/program.rs | 2 + rust/crates/psychoscript/src/promise.rs | 32 ++- rust/crates/psychoscript/src/session.rs | 77 +++++--- rust/crates/psychoscript/src/vm.rs | 4 +- rust/crates/psychoscript/tests/session.rs | 230 +++++++++++++++++++++- 7 files changed, 386 insertions(+), 44 deletions(-) diff --git a/rust/crates/psychoscript/src/convert.rs b/rust/crates/psychoscript/src/convert.rs index 57541a6a..6a5a0bd3 100644 --- a/rust/crates/psychoscript/src/convert.rs +++ b/rust/crates/psychoscript/src/convert.rs @@ -39,6 +39,68 @@ pub(crate) fn host_string(vm: &Vm, s: crate::strings::StrId) -> String { vm.text(s).to_owned() } +/// Host data as a fresh program value, bounded by `vm.value_depth()`, failing with a `TypeError` past it. +pub fn from_data_bounded(vm: &mut Vm, d: &crate::Data) -> Res { + from_data_at(vm, d, 0) +} + +#[allow(clippy::question_mark)] +fn from_data_at(vm: &mut Vm, d: &crate::Data, depth: usize) -> Res { + use crate::Data; + if depth > vm.value_depth() { + let msg = format!( + "Value exceeds the maximum value depth of {}.", + vm.value_depth() + ); + return Err(vm.type_error(&msg)); + } + match d { + Data::Array(items) => array_from_data(vm, items, depth), + Data::Object(fields) => object_from_data(vm, fields, depth), + _ => Ok(leaf_from_data(vm, d)), + } +} + +#[allow(clippy::question_mark)] +fn array_from_data(vm: &mut Vm, items: &[crate::Data], depth: usize) -> Res { + let mut vals = Vec::with_capacity(items.len()); + for item in items { + match from_data_at(vm, item, depth + 1) { + Ok(v) => vals.push(v), + Err(e) => return Err(e), + } + } + Ok(vm.new_array(vals)) +} + +#[allow(clippy::question_mark)] +fn object_from_data(vm: &mut Vm, fields: &[(crate::HostString, crate::Data)], depth: usize) -> Res { + let id = vm.new_object(); + for (k, v) in fields { + match from_data_at(vm, v, depth + 1) { + Ok(val) => { + let a = vm.atoms.intern(&k.to_run_text()); + vm.define(id, a, val); + } + Err(e) => return Err(e), + } + } + Ok(Value::Obj(id)) +} + +#[cfg_attr(debug_assertions, inline(never))] +fn leaf_from_data(vm: &mut Vm, d: &crate::Data) -> Value { + use crate::Data; + match d { + Data::Null => Value::Null, + Data::FunctionMarker => Value::Undef, + Data::Bool(b) => Value::Bool(*b), + Data::Number(n) => Value::Num(n.as_f64().unwrap_or(f64::NAN)), + Data::String(s) => vm.string_val(s.to_run_text()), + Data::Array(_) | Data::Object(_) => Value::Undef, + } +} + /// Host data as a fresh program value, its strings exactly as the host gave them. pub fn from_data(vm: &mut Vm, d: &crate::Data) -> Value { use crate::Data; diff --git a/rust/crates/psychoscript/src/cross.rs b/rust/crates/psychoscript/src/cross.rs index e7c78def..5d390cab 100644 --- a/rust/crates/psychoscript/src/cross.rs +++ b/rust/crates/psychoscript/src/cross.rs @@ -408,15 +408,15 @@ fn plain_scalar(vm: &Vm, v: &Value) -> Option { /// The program returned `v`: its result once it has crossed. pub fn program_result(vm: &mut Vm, v: Value) -> Result<(), Value> { - // A session's top level returns what its calls call, which stays in the run uncrossed (`session.rs`). - if let Some(s) = vm.session.as_deref_mut() - && s.exports.is_none() - { - s.exports = Some(v); - vm.outcome = Some(Ok(Value::Undef)); - return Ok(()); - } if !thenable(vm, &v) { + // A session's top level returns what its calls call, which stays in the run uncrossed (`session.rs`). + if let Some(s) = vm.session.as_deref_mut() + && s.exports.is_none() + { + s.exports = Some(v); + vm.outcome = Some(Ok(Value::Undef)); + return Ok(()); + } match fast(vm, &v) { Ok(Fast::Json(j)) => { vm.result_json = Some(j.unwrap_or(Json::Null)); @@ -720,6 +720,13 @@ fn run(vm: &mut Vm, c: &mut Cross, mut act: Act, mut root_awaited: bool) -> Resu c.waiting = Waiting::Root; return Ok(Pause::Await(root)); } + if let Some(s) = vm.session.as_deref_mut() + && s.exports.is_none() + { + s.exports = Some(root); + c.crossed.push(Value::Undef); + return Ok(Pause::Done); + } root_awaited = false; // `$vmJsonVisitor(...)`, the root `visit` generator, and the first `next`. vm.fuel(1); diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index ad39d3ea..096c3983 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -336,8 +336,10 @@ impl Program { r.started = false; r.timer_armed = false; r.active_before = Duration::ZERO; + r.carried = Default::default(); r.vm.start = Instant::now(); r.vm.start_cpu_meter(); + r.vm.slice = None; r.vm.stack_base = &probe as *const u8 as usize; r.vm.stack_budget = run::RUN_STACK_BUDGET; if r.vm.fatal.is_none() { diff --git a/rust/crates/psychoscript/src/promise.rs b/rust/crates/psychoscript/src/promise.rs index 04282dfa..cd562665 100644 --- a/rust/crates/psychoscript/src/promise.rs +++ b/rust/crates/psychoscript/src/promise.rs @@ -14,6 +14,8 @@ pub(crate) const TRY: usize = 4; /// A thenable whose `then` is a program getter: the getter runs in this job, then `then` as a `THENABLE` would, /// as the reference's `$vmThenableGet`. pub(crate) const THENABLE_GET: usize = 5; +/// A session call whose export is a getter: the getter runs first in this frame, then what it returns as a `TRY` would. +pub(crate) const SESSION_GET: usize = 6; // The slots of a `Settle` frame: its kind; the promise it settles (for a thenable job, the resolve function); for a // thenable job or an executor the reject function, for a `finally` the outcome it restores (its kind, then its value), @@ -73,9 +75,33 @@ pub(crate) fn settle_step(vm: &mut Vm, fr: Frame, input: Input) -> Result = vm.stack[at..at + argc].to_vec(); + let args: Vec<_> = if kind == SESSION_GET { + Vec::new() + } else { + vm.stack[at..at + argc].to_vec() + }; return Ok(fr.catching_list(vm, f, this, &args, Step::CallSettling)); } + Input::Returned(r) if kind == SESSION_GET => { + let f = r.get(); + if vm.is_callable(&f) { + fr.set_index(vm, SETTLE_KIND, TRY); + let (this, argc) = (fr.slot(vm, SETTLE_THIS), fr.index(vm, SETTLE_ARGC)); + let at = fr.base() + SETTLE_ARGS; + let args: Vec<_> = vm.stack[at..at + argc].to_vec(); + return Ok(fr.catching_list(vm, Slot::pack(f), this, &args, Step::CallSettling)); + } + let name = match fr.get(vm, SETTLE_A) { + Value::Str(s) => vm.text(s).to_owned(), + _ => String::new(), + }; + let message = format!("The session has no function {name}."); + let e = vm.type_error(&message); + if let Some(p) = target.as_obj() { + vm.reject(p, e); + } + return Ok(Step::Done(Value::Undef)); + } Input::Returned(r) if kind == THENABLE_GET => { let then = r.get(); let res = target; @@ -104,7 +130,9 @@ pub(crate) fn settle_step(vm: &mut Vm, fr: Frame, input: Input) -> Result vm.resolve_promise(p, r), - (THEN, Err(e)) | (TRY, Err(e)) | (FINALLY, Err(e)) => vm.reject(p, e), + (THEN, Err(e)) | (TRY, Err(e)) | (FINALLY, Err(e)) | (SESSION_GET, Err(e)) => { + vm.reject(p, e) + } (FINALLY, Ok(r)) => { // As the spec chains `then(valueThunk)` onto the cleanup's promise, the reference passes its outcome // through one more promise, a job later. diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs index 92178328..35c7ead7 100644 --- a/rust/crates/psychoscript/src/session.rs +++ b/rust/crates/psychoscript/src/session.rs @@ -69,49 +69,66 @@ fn call(vm: &mut Vm, name: &str, args: &[Data]) { let key = vm .atoms .intern(&crate::strings::external_text(name.to_owned())); - let f = match exports { - Value::Obj(_) => match vm.op_read(&exports, key) { - Ok(Read::Value(f)) => Ok(f), - Ok(Read::Getter(g)) => vm.call(&g, exports, &[]), - Err(e) => Err(e), - }, - _ => Ok(Value::Undef), + let read = match exports { + Value::Obj(_) => vm.op_read(&exports, key), + _ => Ok(Read::Value(Value::Undef)), }; - let f = match f { - Ok(f) if vm.is_callable(&f) => Ok(f), - Ok(_) => { + let target = match read { + Ok(Read::Value(f)) if vm.is_callable(&f) => Ok(f), + Ok(Read::Value(_)) => { let message = format!("The session has no function {name}."); - Err(vm.type_error(&message)) + let e = vm.type_error(&message); + vm.outcome.get_or_insert(Err(e)); + return; } - e => e, - }; - let f = match f { - Ok(f) => f, + Ok(Read::Getter(g)) => Err(g), Err(e) => { vm.outcome.get_or_insert(Err(e)); return; } }; - let args: Vec = args - .iter() - .map(|a| crate::convert::from_data(vm, a)) - .collect(); + let mut vals = Vec::with_capacity(args.len()); + for a in args { + match crate::convert::from_data_bounded(vm, a) { + Ok(v) => vals.push(v), + Err(e) => { + vm.outcome.get_or_insert(Err(e)); + return; + } + } + } let p = vm.new_promise(); if crate::cross::program_result(vm, Value::Obj(p)).is_err() { return; } let (u, z) = (Value::Undef, Value::Num(0.0)); - let entered = crate::promise::enter_settle( - vm, - u, - crate::promise::TRY, - Value::Obj(p), - u, - z, - f, - exports, - &args, - ); + let entered = match target { + Ok(f) => crate::promise::enter_settle( + vm, + u, + crate::promise::TRY, + Value::Obj(p), + u, + z, + f, + exports, + &vals, + ), + Err(g) => { + let name_val = vm.atom_val(key); + crate::promise::enter_settle( + vm, + u, + crate::promise::SESSION_GET, + Value::Obj(p), + name_val, + z, + g, + exports, + &vals, + ) + } + }; match entered { Ok(_) => vm.take_entered(), Err(e) => vm.reject(p, e), diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 1be6ff8a..da8f790b 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -3258,9 +3258,9 @@ impl Vm { if self.resumable_run { return self.run(); } - self.run_depth += 1; + self.run_depth += 2; let r = self.run_frames(false); - self.run_depth -= 1; + self.run_depth -= 2; r } diff --git a/rust/crates/psychoscript/tests/session.rs b/rust/crates/psychoscript/tests/session.rs index 510d8e92..cb155815 100644 --- a/rust/crates/psychoscript/tests/session.rs +++ b/rust/crates/psychoscript/tests/session.rs @@ -5,8 +5,8 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use psychoscript::{ - Data, DiagnosticKind, HostFunction, HostValue, Json, Limits, Namespace, Outcome, - ProgramOptions, Resolved, Runtime, Val, from_bytes, to_bytes, + Clock, Data, DiagnosticKind, HostFunction, HostValue, Json, Limits, Namespace, Outcome, + ProgramOptions, Resolved, Runtime, Session, Val, from_bytes, to_bytes, }; use serde_json::json; @@ -517,3 +517,229 @@ fn a_session_continues_in_another_process() { std::fs::remove_file(&path).unwrap(); assert_eq!(answer, "15"); } + +#[test] +fn a_session_is_owned_and_static() { + fn assert_owned() {} + assert_owned::(); + + let mut s = { + let rt = Runtime::make(); + let (s, started) = rt.session(COUNTER, &ProgramOptions::new()); + ok(&started); + s + }; + assert_eq!(ok(&s.call("add", &args(&[json!(2)]))), json!(2)); + let bytes = to_bytes(&s.save().unwrap()); + let mut restored = { + let rt = Runtime::make(); + rt.restore_session(&from_bytes(&bytes).unwrap()).unwrap() + }; + assert_eq!(ok(&restored.call("add", &args(&[json!(3)]))), json!(5)); +} + +#[test] +fn export_getter_respects_thread_cpu_timeout_and_slice() { + let rt = Runtime::make().limits(Limits { + clock: Clock::ThreadCpu, + timeout_ms: Some(100), + ..Default::default() + }); + let (mut s, started) = rt.session( + "return { get f() { while (true) {} } }", + &ProgramOptions::new(), + ); + ok(&started); + assert_eq!( + failed(&s.call("f", &[])).kind, + DiagnosticKind::TimeoutExceeded + ); + + let rt = Runtime::make().limits(Limits { + clock: Clock::ThreadCpu, + slice_ms: Some(100), + ..Default::default() + }); + let (mut s, started) = rt.session( + "return { get f() { while (true) {} } }", + &ProgramOptions::new(), + ); + ok(&started); + assert_eq!( + failed(&s.call("f", &[])).kind, + DiagnosticKind::SliceExceeded + ); +} + +#[test] +fn export_getter_after_host_sleep_gets_fresh_wall_slice() { + let rt = Runtime::make().limits(Limits { + clock: Clock::Wall, + slice_ms: Some(50), + ..Default::default() + }); + let (mut s, started) = rt.session( + "return { a() { return 1; }, get b() { return () => 2; } }", + &ProgramOptions::new(), + ); + ok(&started); + assert_eq!(ok(&s.call("a", &[])), json!(1)); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(ok(&s.call("b", &[])), json!(2)); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(ok(&s.call("a", &[])), json!(1)); +} + +#[test] +fn export_getter_with_inner_calls_and_errors_works() { + let rt = Runtime::make(); + let (mut s, started) = rt.session( + r#" + function id(x) { return x; } + let base = 10; + return { + base, + get f() { + let sum = 0; + for (let i = 0; i < 10000; i++) sum += id(i); + return (x) => sum + this.base + x; + }, + get bad() { throw new TypeError("getter boom"); }, + get notFn() { return 123; }, + ok() { return 7; }, + }; + "#, + &ProgramOptions::new(), + ); + ok(&started); + assert_eq!(ok(&s.call("f", &args(&[json!(5)]))), json!(49995015)); + assert_eq!(ok(&s.call("ok", &[])), json!(7)); + + let e = failed(&s.call("bad", &[])).clone(); + assert!( + e.message + .to_string_lossy() + .starts_with("TypeError: getter boom"), + "{e:?}" + ); + let e = failed(&s.call("notFn", &[])).clone(); + assert!( + e.message.to_string_lossy().contains("no function notFn"), + "{e:?}" + ); + assert_eq!(ok(&s.call("ok", &[])), json!(7)); +} + +#[test] +fn top_level_promise_and_async_iife_exports_are_awaited() { + let rt = Runtime::make(); + + let (mut s, started) = rt.session( + "return Promise.resolve({ f() { return 42; } })", + &ProgramOptions::new(), + ); + assert_eq!(ok(&started), Json::Null); + assert_eq!(ok(&s.call("f", &[])), json!(42)); + + let (mut s, started) = rt.session( + "return (async () => { await null; return { f(x) { return x + 40; } }; })()", + &ProgramOptions::new(), + ); + assert_eq!(ok(&started), Json::Null); + assert_eq!(ok(&s.call("f", &args(&[json!(2)]))), json!(42)); + + let (mut s, started) = rt.session( + "return Promise.reject(new Error('top reject'))", + &ProgramOptions::new(), + ); + let msg = failed(&started).message.to_string_lossy().into_owned(); + assert!(msg.starts_with("Error: top reject"), "{msg}"); + assert_eq!(failed(&s.call("f", &[])).message.to_string_lossy(), msg); +} + +#[test] +fn session_call_enforces_max_value_depth_on_args() { + fn deep_data(n: usize) -> Data { + let mut d = Data::Number(1.into()); + for _ in 0..n { + d = Data::Array(vec![d]); + } + d + } + fn discard_deep(mut d: Data) { + while let Data::Array(mut items) = d { + match items.pop() { + Some(inner) => d = inner, + None => break, + } + } + } + + let rt = Runtime::make().limits(Limits { + max_value_depth: Some(32), + ..Default::default() + }); + let (mut s, started) = rt.session( + "return { echo(x) { return x; }, ping() { return 1; } }", + &ProgramOptions::new(), + ); + ok(&started); + + // At the exact limit: succeeds. + let at_limit = deep_data(32); + let res = s.call("echo", &[at_limit]); + assert!(res.result.is_ok(), "{:?}", res.result); + + // Depth 100 past limit 32: fails cleanly with TypeError and does not poison the session. + let d100 = deep_data(100); + let err = failed(&s.call("echo", &[d100])).clone(); + assert_eq!(err.kind, DiagnosticKind::ExecutionFailure); + assert!( + err.message.to_string_lossy().starts_with("TypeError:"), + "{err:?}" + ); + assert_eq!(ok(&s.call("ping", &[])), json!(1)); + + // Depth 50,000: fails cleanly without stack overflow and does not poison the session. + let d50k = deep_data(50_000); + let err = failed(&s.call("echo", std::slice::from_ref(&d50k))).clone(); + discard_deep(d50k); + assert_eq!(err.kind, DiagnosticKind::ExecutionFailure); + assert!( + err.message.to_string_lossy().starts_with("TypeError:"), + "{err:?}" + ); + assert_eq!(ok(&s.call("ping", &[])), json!(1)); +} + +#[test] +fn each_call_starts_with_a_fresh_carried_budget() { + let rt = Runtime::make() + .limits(Limits { + clock: Clock::ThreadCpu, + timeout_ms: Some(50), + ..Default::default() + }) + .globals(|_| { + [( + "spinHost", + HostFunction::new(|_, _| { + let clock = psychoscript::thread_clock::ThreadClock::current(); + let until = clock.now() + Duration::from_millis(150); + while clock.now() < until { + std::hint::spin_loop(); + } + HostValue::Undefined + }), + )] + }); + let (mut s, started) = rt.session( + "return { f() { spinHost(); let n = 0; for (let i = 0; i < 100; i++) n += i; return n; } }", + &ProgramOptions::new(), + ); + ok(&started); + // 4 * 150 ms = 600 ms > 10 * 50 ms backstop: each call must reset carried CPU/slice backstops. + for _ in 0..4 { + assert_eq!(ok(&s.call("f", &[])), json!(4950)); + } +}