diff --git a/rust/README.md b/rust/README.md index 587edd10..291185f2 100644 --- a/rust/README.md +++ b/rust/README.md @@ -70,6 +70,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. @@ -123,7 +125,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/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 5a3840b8..5d390cab 100644 --- a/rust/crates/psychoscript/src/cross.rs +++ b/rust/crates/psychoscript/src/cross.rs @@ -409,6 +409,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> { 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)); @@ -712,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/host.rs b/rust/crates/psychoscript/src/host.rs index 35992caf..8d0c4210 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -849,7 +849,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 @@ -889,7 +889,19 @@ 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 { +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 + { + 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); vm.lends.clear(); @@ -2418,7 +2430,7 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option 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); }; @@ -2451,7 +2463,7 @@ fn host_native(vm: &mut Vm, _this: Value, args: &[Value], callee: Id) -> Res { 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 23fc912b..ae5f1638 100644 --- a/rust/crates/psychoscript/src/host_function.rs +++ b/rust/crates/psychoscript/src/host_function.rs @@ -748,6 +748,8 @@ type AsyncFn = dyn Fn(Vec, Call) -> BoxFuture<'static, HostResult> + pub(crate) enum Body { Sync(Arc), Async(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`). @@ -808,6 +810,23 @@ impl HostFunction { Self::with_body(Body::Sync(Arc::new(move |args, call| f(args, call).into()))) } + /// 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: for<'a> Fn( + &mut crate::HostCtx<'a>, + crate::Args<'a>, + ) -> Result, crate::Val<'a>> + + 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 58cd3d58..1512cdf5 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; @@ -71,6 +72,7 @@ pub use runtime::{ Outcome, ProgramOptions, Run, Runtime, Translate, TranslateFunctions, TranslatePromises, }; pub use serde_json::Value as Json; +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 42a3b4b0..096c3983 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -250,6 +250,8 @@ pub struct Program { 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 Program { @@ -275,15 +277,118 @@ impl Program { offload: false, worker: None, move_away: false, + session: false, } } /// A program continuing a suspended run's state, checked against this runtime. pub(crate) fn resume(rt: &Runtime, 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.clone(), State::Running(running))) } + /// A session's run of `code`, whose top level runs on the first [`Program::drive_session`]. + pub(crate) fn session(rt: &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: &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.clone(), 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.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() { + 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(); + 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. + 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, + carried: Default::default(), + }; + 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); @@ -317,12 +422,7 @@ impl Program { 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) @@ -559,6 +659,13 @@ impl Program { } 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!() }; @@ -602,20 +709,7 @@ impl Program { 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 { @@ -714,6 +808,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 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/reach.rs b/rust/crates/psychoscript/src/reach.rs index 8adebae4..1e448ad4 100644 --- a/rust/crates/psychoscript/src/reach.rs +++ b/rust/crates/psychoscript/src/reach.rs @@ -33,6 +33,9 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { t.frame(f); } t.vals(vm.globals.iter()); + if let Some(s) = &vm.session { + t.vals(s.exports.iter()); + } for (k, v) in &vm.global_map { t.atom(*k); t.val(v); diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index 9bfbf288..e740d0ba 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -336,9 +336,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 8ff13843..76fc20fc 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -397,6 +397,24 @@ impl Runtime { Program::new(self, code.into(), options) } + /// 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, + ) -> (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 { + 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 new file mode 100644 index 00000000..35c7ead7 --- /dev/null +++ b/rust/crates/psychoscript/src/session.rs @@ -0,0 +1,430 @@ +//! 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::borrow::Cow; +use std::marker::PhantomData; +use std::sync::Arc; + +use crate::accessors::Read; +use crate::object::Kind; +use crate::program::Program; +use crate::value::Value; +use crate::vm::Vm; +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)] +pub(crate) struct SessionState { + pub exports: Option, +} + +/// 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 { + program: Program, +} + +impl Session { + pub(crate) fn start(rt: &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: &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 read = match exports { + Value::Obj(_) => vm.op_read(&exports, key), + _ => Ok(Read::Value(Value::Undef)), + }; + 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}."); + let e = vm.type_error(&message); + vm.outcome.get_or_insert(Err(e)); + return; + } + Ok(Read::Getter(g)) => Err(g), + Err(e) => { + vm.outcome.get_or_insert(Err(e)); + return; + } + }; + 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 = 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), + } +} + +// ---------- direct host functions ---------- + +/// 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)); +/// ``` +/// +/// ```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<'a> { + pub(crate) v: Value, + /// Invariant in `'a`, so a value of one call can't be kept for another. + scope: PhantomData &'a ()>, +} + +impl<'a> Val<'a> { + pub(crate) fn of(v: Value) -> Self { + Val { + v: match v { + Value::Uninit => Value::Undef, + v => v, + }, + scope: PhantomData, + } + } + + pub fn undefined() -> Self { + Self::of(Value::Undef) + } + + pub fn null() -> Self { + Self::of(Value::Null) + } + + pub fn bool(b: bool) -> Self { + Self::of(Value::Bool(b)) + } + + pub fn num(n: f64) -> Self { + Self::of(Value::Num(n)) + } + + pub fn is_undefined(self) -> bool { + matches!(self.v, Value::Undef) + } + + pub fn is_null(self) -> bool { + matches!(self.v, Value::Null) + } + + pub fn as_bool(self) -> Option { + match self.v { + Value::Bool(b) => Some(b), + _ => None, + } + } + + pub fn as_f64(self) -> Option { + match self.v { + Value::Num(n) => Some(n), + _ => None, + } + } +} + +/// The receiver and arguments of a direct host function's call. +#[derive(Clone, Copy)] +pub struct Args<'a> { + this: Value, + args: &'a [Value], +} + +impl<'a> Args<'a> { + pub fn this(&self) -> Val<'a> { + Val::of(self.this) + } + + pub fn len(&self) -> usize { + self.args.len() + } + + pub fn is_empty(&self) -> bool { + self.args.is_empty() + } + + /// 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)) + } +} + +/// 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, +} + +pub(crate) type DirectFn = + dyn for<'a> Fn(&mut HostCtx<'a>, Args<'a>) -> Result, Val<'a>> + Send + Sync; + +/// 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) +} + +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 + .intern(&crate::strings::external_text(name.to_owned())), + } + } + + /// `typeof v`. + pub fn type_of(&self, v: Val<'a>) -> &'static str { + self.vm.type_of(&v.v) + } + + 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(_))) + } + + /// 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, + } + } + + /// 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, + } + } + + /// [`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)) + } + _ => None, + }, + _ => None, + } + } + + 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())), + }) + } + + /// A new empty object. + pub fn object(&mut self) -> Val<'a> { + Val::of(Value::Obj(self.vm.new_object())) + } + + /// 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())) + } + + /// `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) + } + + /// `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) + } + + /// `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) + } + + /// `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) + } + + 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, &[]), + } + } + + 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(()), + } + } + + /// `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(); + }; + let keys = self.vm.own_keys(id); + keys.into_iter() + .map(|k| Val::of(self.vm.atom_val(k))) + .collect() + } + + /// Calls a program function, as the program would call it. The time it takes is the program's. + pub fn call( + &mut self, + 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)) + } + + /// 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)) + } +} + +const _: () = { + const fn owned() {} + owned::(); +}; diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index 48a7568b..77ae52b8 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -642,7 +642,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(|s| { @@ -680,7 +680,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 { @@ -2767,6 +2772,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()) diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 36153f5f..da8f790b 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -366,6 +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>, + /// 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 { @@ -513,6 +515,7 @@ impl Vm { cpu: None, slice: None, console: None, + session: None, } } @@ -3255,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 new file mode 100644 index 00000000..cb155815 --- /dev/null +++ b/rust/crates/psychoscript/tests/session.rs @@ -0,0 +1,745 @@ +//! 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; + +use psychoscript::{ + Clock, Data, DiagnosticKind, HostFunction, HostValue, Json, Limits, Namespace, Outcome, + ProgramOptions, Resolved, Runtime, Session, Val, from_bytes, to_bytes, +}; +use serde_json::json; + +fn ok(o: &Outcome) -> Json { + match &o.result { + Ok(v) => v.to_json(), + Err(e) => panic!("expected success, got {}: {}", e.kind, e.message), + } +} + +fn failed(o: &Outcome) -> &psychoscript::Diagnostic { + match &o.result { + Ok(v) => panic!("expected a failure, got {v}"), + Err(e) => e, + } +} + +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 a_session_keeps_its_state_from_call_to_call() { + let rt = Runtime::make(); + 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:?}" + ); + 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 a_top_level_that_fails_fails_every_call() { + let rt = Runtime::make(); + 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 each_call_gets_the_whole_timeout() { + let rt = Runtime::make().limits(Limits { + timeout_ms: Some(500), + ..Default::default() + }); + let (mut s, started) = rt.session( + "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(600)); + assert_eq!(ok(&s.call("f", &[])), json!(1)); + std::thread::sleep(Duration::from_millis(600)); + assert_eq!(ok(&s.call("f", &[])), json!(1)); +} + +#[test] +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 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 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 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(|_| { + [( + "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 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)); +} + +/// 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)? + } + } + Ok(Val::undefined()) + }) +} + +#[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!( + failed(&frozen) + .message + .to_string_lossy() + .contains("TypeError"), + "{frozen:?}" + ); + 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!( + 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!( + 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) + ); + // A typed array converts and stores the number; an array's length follows its elements. + assert_eq!( + run( + "const t = new Uint8Array(2); write(t, 1, 257); write(t, 5, 1); return [t[1], t.length]" + ), + json!([1, 2]) + ); + assert_eq!( + run("const a = [1]; write(a, 3, 4); write(a, 'length', 2); return [a.length, a[3]]"), + json!([2, null]) + ); +} + +#[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_functions_read_and_make_values_in_place() { + let rt = Runtime::make().globals(|_| { + [ + ( + "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)) + }), + ), + ( + "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) + }), + ), + ] + }); + 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"]) + ); + assert_eq!( + 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]]) + ); + let e = rt.execute("fill({})"); + assert!( + failed(&e) + .message + .to_string_lossy() + .starts_with("TypeError: not bytes"), + "{e:?}" + ); +} + +#[test] +fn direct_functions_are_host_calls() { + let slept = HostFunction::direct(|_, _| { + 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(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 < 25000; 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. + let deep = rt + .execute("function f() { return callsBack(f) } try { f() } catch (e) { return String(e) }"); + assert_eq!( + ok(&deep), + json!("RangeError: Maximum call stack size exceeded") + ); +} + +#[test] +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 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(); + } + 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 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 a_session_saves_between_calls_and_continues_from_its_state() { + let rt = Runtime::make().globals(|_| { + [( + "double", + HostFunction::direct(|_, args| Ok(Val::num(args.get(0).as_f64().unwrap_or(0.0) * 2.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") + }; + 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 a_session_continues_in_another_process() { + let rt = Runtime::make(); + 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; + } + 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"); +} + +#[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)); + } +}