diff --git a/rust/README.md b/rust/README.md index 291185f2..9da6cfdc 100644 --- a/rust/README.md +++ b/rust/README.md @@ -72,6 +72,7 @@ Only Rust has: - 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. +- Precompiled named modules: [`Runtime::compile_module`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) compiles a synchronous named module once into an immutable, `Send + Sync` [`CompiledModule`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/run.rs) to run in any session via `Session::eval_compiled` / `Session::eval_module` or from a direct host function via `HostCtx::eval_compiled` / `HostCtx::eval_module`. Functions from named modules report per-module `file:line:col` stack traces (and `Call::location`) and `Function.prototype.toString` slices each module's own source. Loaded modules and their source metadata survive `Session::save` / `Runtime::restore_session` and suspend/resume snapshots. - 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. diff --git a/rust/crates/psychoscript/src/builtins/array.rs b/rust/crates/psychoscript/src/builtins/array.rs index 0f3310df..d99fb0be 100644 --- a/rust/crates/psychoscript/src/builtins/array.rs +++ b/rust/crates/psychoscript/src/builtins/array.rs @@ -437,8 +437,9 @@ fn array_from_async(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res let fp = vm.realm.async_function_proto; // Its `fields` hold where the program called it, where its failures point (see `Vm::locate`). let origin = vm - .call_offset() - .map_or(Value::Undef, |o| Value::Num(o as f64)); + .call_location() + .filter(|s| s.is_program()) + .map_or(Value::Undef, |s| Value::Num(s.offset() as f64)); let f = vm.alloc(Obj::new( Some(fp), Kind::Closure(Box::new(Closure { @@ -520,6 +521,7 @@ pub(crate) fn from_async_code(vm: &mut Vm, live: bool) -> Option { vm.global_names.push(a); vm.globals.push(v); } + vm.record_from_async(); at } diff --git a/rust/crates/psychoscript/src/builtins/collections.rs b/rust/crates/psychoscript/src/builtins/collections.rs index b875b7d2..9f03c6f8 100644 --- a/rust/crates/psychoscript/src/builtins/collections.rs +++ b/rust/crates/psychoscript/src/builtins/collections.rs @@ -562,8 +562,10 @@ fn locate_call(vm: &mut Vm, e: &Value) { .find(|f| !matches!(f.kind, crate::vm::FrameKind::Native(..))) && let Kind::Error(Some(f)) = &mut vm.heap[id as usize].kind && f.offset.is_none() + && let Some(offset) = caller.func.pos.get(caller.pc.saturating_sub(1)).copied() { - f.offset = caller.func.pos.get(caller.pc.saturating_sub(1)).copied(); + f.offset = Some(offset); + f.source = caller.func.source(); } } diff --git a/rust/crates/psychoscript/src/builtins/object.rs b/rust/crates/psychoscript/src/builtins/object.rs index 055eb38c..968876d7 100644 --- a/rust/crates/psychoscript/src/builtins/object.rs +++ b/rust/crates/psychoscript/src/builtins/object.rs @@ -1048,11 +1048,13 @@ fn function_to_string(vm: &mut Vm, this: Value, _: &[Value], _: Id) -> Res { let Some(id) = this.as_obj() else { return Err(vm.type_error("Function.prototype.toString called on incompatible receiver.")); }; - let span = match &vm.heap[id as usize].kind { - Kind::Closure(c) => c.proto.text, - _ => None, + let (span, source) = match &vm.heap[id as usize].kind { + Kind::Closure(c) => (c.proto.text, c.proto.source()), + _ => (None, 0), }; - if let Some(text) = span.and_then(|[start, end]| vm.code.get(start as usize..end as usize)) { + if let Some(text) = + span.and_then(|[start, end]| vm.source_code(source).get(start as usize..end as usize)) + { let text = text.to_owned(); return Ok(vm.string_val(text)); } diff --git a/rust/crates/psychoscript/src/bytecode.rs b/rust/crates/psychoscript/src/bytecode.rs index 6dcd6892..56d7d078 100644 --- a/rust/crates/psychoscript/src/bytecode.rs +++ b/rust/crates/psychoscript/src/bytecode.rs @@ -291,6 +291,248 @@ pub enum Capture { pub const CLASS_BASE: u8 = 1; pub const CLASS_DERIVED: u8 = 2; +/// Per-module source metadata attached to [`FuncProto`]s compiled as named modules. +#[derive(Clone, Debug)] +pub struct ModuleSource { + pub name: Arc, + pub code: Arc, +} + +/// Source tag for `Vm::code` (`source == 0`), stored as `1` so `Option` uses niche `0` +/// and stays 8 bytes with `offset` uninitialized on `None` (matching `Option` exactly). +pub(crate) const PROGRAM_SOURCE_TAG: std::num::NonZeroU32 = std::num::NonZeroU32::MIN; + +/// A bytecode source site: `tag = source + 1` (`1` = `Vm::code`, `2..` = loaded named module) and +/// byte `offset`. `Option` is 8 bytes, identical to `Option`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CallSite { + pub(crate) tag: std::num::NonZeroU32, + pub(crate) offset: u32, +} + +impl CallSite { + #[inline(always)] + pub(crate) fn new(offset: u32, source: u32) -> Self { + Self { + tag: std::num::NonZeroU32::new(source.saturating_add(1)).unwrap_or(PROGRAM_SOURCE_TAG), + offset, + } + } + + #[inline(always)] + pub(crate) fn from_tag(tag: std::num::NonZeroU32, offset: u32) -> Self { + Self { tag, offset } + } + + #[inline(always)] + pub(crate) fn is_program(self) -> bool { + self.tag == PROGRAM_SOURCE_TAG + } + + #[inline(always)] + pub(crate) fn offset(self) -> u32 { + self.offset + } + + #[inline(always)] + pub(crate) fn source(self) -> u32 { + self.tag.get() - 1 + } +} + +/// Rebases table indices and remaps interned atoms in a single instruction when merging a +/// precompiled module into a live VM. Returns `false` on `u32` table index overflow. +/// +/// Intentionally exhaustive (no wildcard arm): adding a new [`Op`] variant forces classification +/// here so proto/const/global/template/atom operands can never be silently corrupted. +pub(crate) fn rebase_op( + op: &mut Op, + proto_base: u32, + const_base: u32, + global_base: u32, + template_base: u32, + remap_atom: &mut impl FnMut(Atom) -> Atom, +) -> bool { + match op { + // Proto index + Op::Closure(i) => { + let Some(next) = i.checked_add(proto_base) else { + return false; + }; + *i = next; + } + // Constant pool index + Op::Const(i) + | Op::ThrowType(i) + | Op::ThrowUnsupported(i) + | Op::ThrowSyntax(i) + | Op::ThrowRange(i) + | Op::ThrowReference(i) => { + let Some(next) = i.checked_add(const_base) else { + return false; + }; + *i = next; + } + // Global slot index + Op::GetGlobal(i) | Op::TypeofGlobal(i) => { + let Some(next) = i.checked_add(global_base) else { + return false; + }; + *i = next; + } + // Tagged template site index + Op::Template(i) => { + let Some(next) = i.checked_add(template_base) else { + return false; + }; + *i = next; + } + // Interned property/binding name atoms + Op::GetLocalChk(_, a) + | Op::GetCellChk(_, a) + | Op::GetUpvalChk(_, a) + | Op::ThrowConst(a) + | Op::ThrowRef(a) + | Op::GetProp(a) + | Op::SetProp(a) + | Op::DestructProp(a) + | Op::GetPropW(a) + | Op::GetMethod(a) + | Op::DelProp(a) + | Op::DefineField(a) + | Op::DefineAccessor(a, _) + | Op::DefineMethod(a, _) + | Op::GetSuper(a, _) + | Op::PutSuper(a, _) + | Op::DefineClassField(a, _) => *a = remap_atom(*a), + // Instructions carrying no table indices or atoms + Op::Nop + | Op::Pop + | Op::Dup + | Op::Dup2 + | Op::Swap + | Op::Rot3 + | Op::Rot3Back + | Op::Undef + | Op::Null + | Op::True + | Op::False + | Op::Uninit + | Op::Int(_) + | Op::GetLocal(_) + | Op::GetLocal2(_, _) + | Op::SetLocal(_) + | Op::NewCell(_) + | Op::GetCell(_) + | Op::SetCell(_) + | Op::GetUpval(_) + | Op::SetUpval(_) + | Op::This + | Op::Callee + | Op::Arguments + | Op::Rest(_) + | Op::GetElem + | Op::SetElem + | Op::DestructElem + | Op::WriteKey + | Op::DelElem + | Op::In + | Op::InstanceOf + | Op::DefineElem + | Op::DefineAccessorElem(_) + | Op::NameByKey(_) + | Op::Class(_) + | Op::SetFields + | Op::InitFields + | Op::InitStatic + | Op::SuperCall(_, _) + | Op::SuperBind + | Op::SetHome(_) + | Op::Home + | Op::CtorReturn(_) + | Op::NewObject(_) + | Op::NewArray(_) + | Op::ArrayPush + | Op::ArraySpread + | Op::ObjectSpread + | Op::ObjRest(_) + | Op::RequireCoercible + | Op::ToKey + | Op::Add + | Op::Sub + | Op::Mul + | Op::Div + | Op::Mod + | Op::Pow + | Op::BitAnd + | Op::BitOr + | Op::BitXor + | Op::Shl + | Op::Shr + | Op::UShr + | Op::Eq + | Op::Ne + | Op::StrictEq + | Op::StrictNe + | Op::Lt + | Op::Le + | Op::Gt + | Op::Ge + | Op::ArithI(_, _) + | Op::Neg + | Op::ToNumber + | Op::ToNumeric + | Op::Not + | Op::BitNot + | Op::Typeof + | Op::RegExp + | Op::Inc + | Op::Dec + | Op::ToStr + | Op::Concat(_) + | Op::AddLocal(_) + | Op::IncLocal(_) + | Op::Jump(_) + | Op::JumpIfFalse(_) + | Op::JumpIfTrue(_) + | Op::JumpUnless(_, _) + | Op::JumpUnlessI(_, _, _) + | Op::JumpIfFalseKeep(_) + | Op::JumpIfTrueKeep(_) + | Op::JumpIfNotNullishKeep(_) + | Op::JumpIfNotUndef(_) + | Op::OptChain(_) + | Op::OptCall(_) + | Op::Call(_) + | Op::CallSpread + | Op::New(_) + | Op::NewSpread + | Op::Return + | Op::GeneratorStart + | Op::Await + | Op::Yield(_) + | Op::YieldDrop(_) + | Op::YieldStar(_) + | Op::Throw + | Op::PushCatch(_) + | Op::PushFinally(_) + | Op::PopTry + | Op::GetIter(_, _) + | Op::IterNext(_, _) + | Op::DelegateCall(_, _, _) + | Op::DelegateResult(_, _) + | Op::GetAsyncIter(_, _) + | Op::AsyncClose(_, _) + | Op::CheckObject + | Op::IterStep(_) + | Op::IterRest(_) + | Op::IterClose(_) + | Op::IterCloseQuiet(_) + | Op::ForIn(_) => {} + } + true +} + #[derive(Clone, Debug)] pub struct FuncProto { pub name: Atom, @@ -305,6 +547,8 @@ pub struct FuncProto { pub is_generator: bool, pub is_arrow: bool, pub is_program: bool, + /// Top-level entry prototype of a synchronous [`CompiledModule`](crate::CompiledModule). + pub(crate) is_module_entry: bool, /// A class constructor: `CLASS_BASE` or `CLASS_DERIVED`, else 0. Only `new` may call it. pub class: u8, /// An arrow that reads its method's home object (`super`): it takes it when it is made. @@ -323,9 +567,16 @@ pub struct FuncProto { /// Where the function's source text starts and ends in the program, as `Function.prototype.toString` returns /// it; `None` for built-in or compiler-made code. pub text: Option<[u32; 2]>, + /// Loaded module source tag (`1` = `Vm::code`, `source + 1` for a loaded module). + pub(crate) source_tag: std::num::NonZeroU32, } impl FuncProto { + /// Loaded module source index (`0` = `Vm::code`, `1..` = 1-based index into `Vm::loaded_code`). + #[inline(always)] + pub(crate) fn source(&self) -> u32 { + self.source_tag.get() - 1 + } /// The atoms the function's code names: its own name, and the keys and binding names of its instructions. pub fn atoms(&self) -> impl Iterator + '_ { std::iter::once(self.name).chain(self.code.iter().filter_map(|op| match *op { diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index 749b95ac..1e9be79d 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1157,6 +1157,14 @@ impl Vm { } } + /// Shades an atom stored into VM root tables during an active GC cycle. + #[inline] + pub(crate) fn gc_shade_atom(&mut self, a: Atom) { + if self.gc.phase != Phase::Idle { + self.atoms.shade_atom(a); + } + } + /// A new closure cell at its limit, as `gc_alloc` does for objects. #[cold] #[inline(never)] diff --git a/rust/crates/psychoscript/src/compiler.rs b/rust/crates/psychoscript/src/compiler.rs index 94a4cdc2..382fda14 100644 --- a/rust/crates/psychoscript/src/compiler.rs +++ b/rust/crates/psychoscript/src/compiler.rs @@ -40,14 +40,20 @@ const MAX_NESTING: u32 = 2_000; pub const DEFAULT_MAX_SOURCE_BYTES: usize = 256 * 1024; pub fn compile(source: &str, atoms: &mut Strings) -> R { - compile_as(source, atoms, false) + compile_as(source, atoms, false, false) +} + +/// Compiles a synchronous named module: top-level `return` yields the module value directly and +/// top-level `await` / `for await` are rejected. +pub(crate) fn compile_module(source: &str, atoms: &mut Strings) -> R { + compile_as(source, atoms, false, true) } /// Compiles a built-in the reference writes in its bytecode prelude, from the reference's source: its `$Call(f, /// thisArg, ...args)` is a call of `f` with that receiver and `$ArraySet(array, index, value)` an element write, as /// the reference lowers them; any other `$` helper is a global the caller binds. pub(crate) fn compile_internal(source: &str, atoms: &mut Strings) -> R { - compile_as(source, atoms, true) + compile_as(source, atoms, true, false) } /// The offset of the first token after a class element's leading `static`. @@ -59,7 +65,7 @@ fn skip_static(source: &str, start: u32) -> u32 { /// The most a thread's parse arena keeps between compiles: a larger one, grown by a large program, is let go. const ARENA_KEEP_BYTES: usize = 256 * 1024; -fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R { +fn compile_as(source: &str, atoms: &mut Strings, internal: bool, sync_module: bool) -> R { thread_local! { /// The arena the parser and the analysis allocate in, kept from one compile to the next on the thread: /// a short program's compile then allocates no arena of its own. @@ -67,7 +73,7 @@ fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R { } ARENA.with(|arena| match arena.try_borrow_mut() { Ok(mut arena) => { - let r = compile_in(&arena, source, atoms, internal); + let r = compile_in(&arena, source, atoms, internal, sync_module); match arena.capacity() > ARENA_KEEP_BYTES { true => *arena = Allocator::default(), false => arena.reset(), @@ -75,7 +81,7 @@ fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R { r } // A compile within a compile on one thread: none is, but it would only cost an arena. - Err(_) => compile_in(&Allocator::default(), source, atoms, internal), + Err(_) => compile_in(&Allocator::default(), source, atoms, internal, sync_module), }) } @@ -84,6 +90,7 @@ fn compile_in( source: &str, atoms: &mut Strings, internal: bool, + sync_module: bool, ) -> R { if source.trim().is_empty() { return Err(CompileError { @@ -209,6 +216,7 @@ fn compile_in( let mut c = Compiler::new(scoping, semantic.semantic.nodes(), atoms); c.await_alias = await_alias; c.internal = internal; + c.sync_module = sync_module; c.source = program.source_text; c.find_unbound(program); c.find_field_values(program); @@ -1276,6 +1284,8 @@ struct Compiler<'a, 's> { last_home: bool, /// Compiling a prelude built-in (see `compile_internal`). internal: bool, + /// Compiling a synchronous named module (`is_async = false; is_program = false`). + sync_module: bool, /// The text the program was parsed from, which spans index. source: &'a str, } @@ -1321,6 +1331,7 @@ impl<'a, 's> Compiler<'a, 's> { pseudo: 0, last_home: false, internal: false, + sync_module: false, source: "", } } @@ -2067,7 +2078,7 @@ impl<'a, 's> Compiler<'a, 's> { fn compile_program(&mut self, program: &'a oxc_ast::ast::Program<'a>) -> R<()> { self.fns.push(FnState::new(false)); - self.f().is_async = true; + self.f().is_async = !self.sync_module; let name = self.atom(""); let syms = match program.scope_id.get() { Some(scope) => self.declare_scope(scope), @@ -2108,10 +2119,11 @@ impl<'a, 's> Compiler<'a, 's> { length: 0, nlocals: f.nlocals, captures: Vec::new(), - is_async: true, + is_async: !self.sync_module, is_generator: false, is_arrow: false, - is_program: true, + is_program: !self.sync_module, + is_module_entry: self.sync_module, class: 0, home: false, needs_extra: false, @@ -2119,6 +2131,7 @@ impl<'a, 's> Compiler<'a, 's> { callees: f.callees, sites: f.sites, text: None, + source_tag: crate::bytecode::PROGRAM_SOURCE_TAG, }, ); // Closure instructions index `protos` assuming the program is not in the list; shift them. @@ -2366,6 +2379,7 @@ impl<'a, 's> Compiler<'a, 's> { is_generator: spec.is_generator, is_arrow: spec.is_arrow, is_program: false, + is_module_entry: false, class: spec.class, home: spec.is_arrow && f.home, needs_extra: f.needs_extra, @@ -2374,6 +2388,7 @@ impl<'a, 's> Compiler<'a, 's> { sites: f.sites, // A prelude built-in's offsets are in its own source, not the program's. text: spec.text.filter(|_| !self.internal), + source_tag: crate::bytecode::PROGRAM_SOURCE_TAG, }); Ok(self.protos.len() as u32 - 1) } @@ -2893,6 +2908,15 @@ impl<'a, 's> Compiler<'a, 's> { fn for_of(&mut self, f: &'a ForOfStatement<'a>, labels: Vec<&'a str>) -> R<()> { if f.r#await { + if !self.f().is_async { + return Err(CompileError { + kind: DiagnosticKind::ParseError, + message: + "SyntaxError: Top-level `for await` is not supported in synchronous modules." + .into(), + offset: Some(f.span.start), + }); + } return self.for_await(f, labels); } let syms = match f.scope_id.get() { @@ -3581,6 +3605,15 @@ impl<'a, 's> Compiler<'a, 's> { } } Expression::AwaitExpression(a) => { + if !self.f().is_async { + return Err(CompileError { + kind: DiagnosticKind::ParseError, + message: + "SyntaxError: Top-level `await` is not supported in synchronous modules." + .into(), + offset: Some(a.span.start), + }); + } self.expr(&a.argument)?; self.emit(Op::Await); } diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 457ed7a3..2d3d16f9 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -98,7 +98,7 @@ pub enum Settlement { Host(Box), /// A value a snapshot couldn't keep (a live response, the reference's `Lost`): the call fails with this message /// once the run resumes, at the call's source offset. - Lost(String, Option), + Lost(String, Option), /// The call interrupts the whole run. Interrupted, } @@ -110,8 +110,8 @@ pub struct Settled { pub label: String, /// The global host function whose `snapshot` hooks save functions in the value, by label. pub owner: Option, - /// The source offset of the call, where an error converting its value points. - pub site: Option, + /// The source site of the call, where an error converting its value points. + pub site: Option, } impl Settlement { @@ -119,7 +119,7 @@ impl Settlement { result: HostResult, label: String, owner: Option, - site: Option, + site: Option, ) -> Self { Settlement::Host(Box::new(Settled { result, @@ -204,7 +204,7 @@ pub struct InFlight { /// The arguments as they crossed, for a call that starts again on resume. pub args: Vec, pub owner: Option, - pub site: Option, + pub site: Option, pub kind: CallKind, /// The tag's raw strings (`Call::raw_strings`), saved with a call that starts again on resume. pub raw: Option>, @@ -346,7 +346,7 @@ pub struct Restart { pub path: Option>, pub args: Vec, pub owner: Option, - pub site: Option, + pub site: Option, pub start: Start, /// The tag's raw strings (`Call::raw_strings`). pub raw: Option>, @@ -602,6 +602,11 @@ pub fn install(vm: &mut Vm, referenced: &[Atom]) { } } +/// Defines one host global by name when it exists; returns `false` otherwise. +pub(crate) fn define_host_global_by_name(vm: &mut Vm, name: &str) -> bool { + define_host_global(vm, name) +} + /// Defines one host global by name; false when there is none. fn define_host_global(vm: &mut Vm, name: &str) -> bool { let v = match name { @@ -737,7 +742,7 @@ fn thrown_value( vm: &mut Vm, thrown: &HostValue, label: &str, - site: Option, + site: Option, settled: Option, ) -> Value { match thrown { @@ -762,8 +767,8 @@ fn thrown_value( f.suggestions.clone(), ); // Made at the call: its `stack` is the program's there. - if let (Value::Obj(id), Some(o)) = (e, site) { - vm.host_failure_stack(id, o, settled); + if let (Value::Obj(id), Some(s)) = (e, site) { + vm.host_failure_stack(id, s.offset(), s.source(), settled); } e } @@ -771,22 +776,27 @@ fn thrown_value( } } -/// Points an error the VM made, not yet located, at a host call's source offset. -pub(crate) fn locate_at(vm: &mut Vm, e: &Value, site: Option) { +/// Points an error the VM made, not yet located, at a host call's source site. +pub(crate) fn locate_at(vm: &mut Vm, e: &Value, site: Option) { locate_settled(vm, e, site, None); } /// `locate_at` for a call that settles `settled` while the program is elsewhere (see `Vm::stack_trace_at`). -fn locate_settled(vm: &mut Vm, e: &Value, site: Option, settled: Option) { +fn locate_settled( + vm: &mut Vm, + e: &Value, + site: Option, + settled: Option, +) { if let Value::Obj(id) = e && let Kind::Error(Some(f)) = &mut vm.heap[*id as usize].kind && f.offset.is_none() + && let Some(s) = site { - f.offset = site; - if let Some(o) = site { - let id = *id; - vm.locate_stack_settled(id, o, settled); - } + f.offset = Some(s.offset()); + f.source = s.source(); + let id = *id; + vm.locate_stack_settled(id, s.offset(), s.source(), settled); } } @@ -836,8 +846,8 @@ pub fn call_namespace(vm: &mut Vm, id: Id, args: &[Value], callee: Value) -> Res let f = match resolved { Resolved::Missing(f) => { let e = failure_value(vm, DiagnosticKind::named(&f.kind), f.message, f.suggestions); - if let (Value::Obj(id), Some(o)) = (e, vm.call_offset()) { - vm.host_failure_stack(id, o, None); + if let (Value::Obj(id), Some(s)) = (e, vm.call_location()) { + vm.host_failure_stack(id, s.offset(), s.source(), None); } return Err(e); } @@ -953,14 +963,14 @@ fn call_host( // What the arguments can't cross fails at the call, as the reference locates it. let crossed = match crossed { Err(e) => { - let site = vm.call_offset(); + let site = vm.call_location(); locate_at(vm, &e, site); Err(e) } ok => ok, }; if concurrent { - let site = vm.call_offset(); + let site = vm.call_location(); // The program runs on while the call works: it gets copies of the bytes of the typed arrays it was passed. copy_lends(vm); let host_args = match crossed { @@ -1016,9 +1026,10 @@ fn call_host( }; let call_id = vm.host.next_call(); vm.host.enter_sync(call_id, target.label.clone()); + let call_site = vm.call_location(); let call = vm .host - .call(call_id, vm.call_offset().map(|o| (o, vm.code.clone()))) + .call(call_id, vm.call_site_code(call_site)) .with_raw(raw); // Host work, which neither the CPU time nor the stretch under `Limits::slice_ms` counts. let span = vm.host_span(); @@ -1061,17 +1072,17 @@ fn sync_result( Err(Value::Undef) } Returned::Now(Ok(v)) => { - let site = vm.call_offset(); + let site = vm.call_location(); let v = result_from_host(vm, v, &target.label, target.owner.as_deref()) .inspect_err(|e| locate_at(vm, e, site))?; Ok(if f.thenable { promise_like(vm, v) } else { v }) } Returned::Now(Err(thrown)) => { - let site = vm.call_offset(); + let site = vm.call_location(); Err(thrown_value(vm, &thrown, &target.label, site, None)) } Returned::Pending(work) => { - let site = vm.call_offset(); + let site = vm.call_location(); let p = vm.new_promise(); let (label, owner) = (target.label.clone(), target.owner.clone()); let future: BoxFuture<'_, Settlement> = @@ -1240,7 +1251,7 @@ fn track( fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: bool) { let call = vm .host - .call(r.call, r.site.map(|o| (o, vm.code.clone()))) + .call(r.call, vm.call_site_code(r.site)) .with_raw(r.raw.clone()); let home = home_of(vm); let detached = Arc::new(AtomicBool::new(false)); @@ -2691,7 +2702,7 @@ fn import_native(vm: &mut Vm, _this: Value, args: &[Value], _callee: Id) -> Res Ok(ns) => vm.fulfill(p, ns), // The rejection reports the `import()`, as the reference locates it. Err(e) => { - let site = vm.call_offset(); + let site = vm.call_location(); locate_at(vm, &e, site); vm.reject(p, e) } @@ -2722,7 +2733,7 @@ pub(crate) fn namespace_keys(vm: &mut Vm, id: Id) -> Result, Val }; listed.map_err(|thrown| { let label = vm.ns_label(&ns); - let site = vm.call_offset(); + let site = vm.call_location(); thrown_value(vm, &thrown, &label, site, None) }) } diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index 1512cdf5..9494b619 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -67,7 +67,7 @@ pub use host_function::{ HostString, HostValue, Namespace, Resolved, Returned, SnapshotHooks, TypedArray, TypedKind, }; pub use program::{Program, RunOutcome, RunningCall, SuspendError, Suspended, Suspender}; -pub use run::{Code, Compiled}; +pub use run::{Code, Compiled, CompiledModule}; pub use runtime::{ Outcome, ProgramOptions, Run, Runtime, Translate, TranslateFunctions, TranslatePromises, }; diff --git a/rust/crates/psychoscript/src/native.rs b/rust/crates/psychoscript/src/native.rs index 35ec88de..1aa2f896 100644 --- a/rust/crates/psychoscript/src/native.rs +++ b/rust/crates/psychoscript/src/native.rs @@ -159,6 +159,7 @@ pub fn proto() -> FuncProto { is_generator: false, is_arrow: false, is_program: false, + is_module_entry: false, class: 0, home: false, needs_extra: false, @@ -166,6 +167,7 @@ pub fn proto() -> FuncProto { callees: Vec::new(), sites: Vec::new(), text: None, + source_tag: crate::bytecode::PROGRAM_SOURCE_TAG, } } diff --git a/rust/crates/psychoscript/src/object.rs b/rust/crates/psychoscript/src/object.rs index d7b77c25..f92ef154 100644 --- a/rust/crates/psychoscript/src/object.rs +++ b/rust/crates/psychoscript/src/object.rs @@ -302,6 +302,8 @@ pub struct Failure { pub message: String, /// Source offset of the instruction that raised it, filled in when first thrown. pub offset: Option, + /// Loaded module source index `offset` belongs to (`0` = `Vm::code`). + pub source: u32, /// The part of the raising member expression the offset is taken from when it is filled in. pub site: crate::bytecode::Site, /// A host's failure (`Failure`, the reference's `HostFailure`): whatever its kind's name, uncaught it fails as an @@ -316,6 +318,7 @@ pub struct Failure { #[derive(Clone, Debug, Default)] pub struct Thrown { pub offset: Option, + pub source: u32, pub trace: Option, } @@ -341,7 +344,7 @@ pub struct PromiseData { pub reactions: Vec, /// Where the program made it (the call of the built-in, the `new Promise`): a reason it rejects with, not located /// yet, is thrown there (the reference's `Resolving.site`). - pub site: Option, + pub site: Option, /// Where its rejection reason was thrown, once it is rejected. pub thrown: Option>, } diff --git a/rust/crates/psychoscript/src/promise.rs b/rust/crates/psychoscript/src/promise.rs index cd562665..3ccc2126 100644 --- a/rust/crates/psychoscript/src/promise.rs +++ b/rust/crates/psychoscript/src/promise.rs @@ -178,7 +178,7 @@ pub(crate) fn settle_step(vm: &mut Vm, fr: Frame, input: Input) -> Result Id { let proto = self.realm.promise_proto; - let site = self.call_offset(); + let site = self.call_location(); self.alloc(Obj::new( Some(proto), Kind::Promise(Box::new(PromiseData { diff --git a/rust/crates/psychoscript/src/reach.rs b/rust/crates/psychoscript/src/reach.rs index 915c36ed..3b5d3ce6 100644 --- a/rust/crates/psychoscript/src/reach.rs +++ b/rust/crates/psychoscript/src/reach.rs @@ -44,14 +44,23 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { t.atom(*a); } if !measuring { - // Built-in code compiled during the run (`Array.fromAsync`'s, which has no positions): its atoms were made - // after the permanent ones, so they live by its code, but do not bill the run's heap limit. - for p in vm.protos.iter().filter(|p| p.pos.is_empty()) { + // Built-in code (`Array.fromAsync`, no positions) and dynamically loaded named modules + // (`p.source != 0`): their atoms were made after the permanent ones, so they live by their + // code, without billing the run's heap limit. + for p in vm + .protos + .iter() + .filter(|p| p.pos.is_empty() || p.source() != 0) + { for a in p.atoms() { t.atom(a); } } t.vals(vm.consts.iter()); + for site in vm.templates_ref() { + t.vals(site.cooked.iter().flatten()); + t.vals(site.raw.iter()); + } } let std = &vm.realm.std; for id in [ diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index e740d0ba..dc5f30fc 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -3,7 +3,7 @@ use std::panic::AssertUnwindSafe; use std::sync::Arc; -use crate::bytecode::Program; +use crate::bytecode::{ModuleSource, Program}; use crate::compiler::{self, CompileError}; use crate::convert; use crate::host::{self, RunHost}; @@ -87,11 +87,52 @@ impl<'a> From<&'a Compiled> for Code<'a> { } } +/// A synchronous named module compiled once to be merged and executed in any +/// [`Session`](crate::Session) or [`HostCtx`](crate::HostCtx) without re-parsing or re-compiling. +/// Cheap to clone, immutable, and `Send + Sync`. +#[derive(Clone)] +pub struct CompiledModule(Arc); + +struct CompiledModuleInner { + source: Arc, + program: Program, + atoms: Strings, +} + +impl CompiledModule { + /// The module's name, shown in stack traces (e.g. `"helper.js"`). + pub fn name(&self) -> &str { + &self.0.source.name + } + + /// The module's source text. + pub fn code(&self) -> &str { + &self.0.source.code + } + + pub(crate) fn source_arc(&self) -> Arc { + self.0.source.clone() + } + + pub(crate) fn parts(&self) -> (&Program, &Strings) { + (&self.0.program, &self.0.atoms) + } +} + +impl std::fmt::Debug for CompiledModule { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CompiledModule") + .field("name", &self.0.source.name) + .field("bytes", &self.0.source.code.len()) + .finish() + } +} + /// Parses and compiles a program, or the diagnostic a run of it would fail with before running anything. pub fn compile_program(code: &str, max_source_bytes: usize) -> Result { let mut atoms = Strings::fresh(); - let program = - compile(code, &mut atoms, max_source_bytes).map_err(|e| compile_diagnostic(code, e))?; + let program = compile(code, &mut atoms, max_source_bytes) + .map_err(|e| compile_diagnostic(code, None, e))?; Ok(Compiled(Arc::new(CompiledProgram { code: Arc::from(code), program, @@ -99,9 +140,53 @@ pub fn compile_program(code: &str, max_source_bytes: usize) -> Result Diagnostic { +/// Parses and compiles a synchronous named module once, tagging it with `name` for per-module +/// `file:line:col` stack traces and `Function.prototype.toString`. +pub fn compile_module( + code: &str, + name: &str, + max_source_bytes: usize, +) -> Result { + compile_module_with_budget(code, name, max_source_bytes, RUN_STACK_BUDGET) + .map_err(|e| compile_diagnostic(code, Some(name), e)) +} + +/// Compiles a synchronous named module using `budget` bytes of native stack before moving to a +/// helper thread. +pub(crate) fn compile_module_with_budget( + code: &str, + name: &str, + max_source_bytes: usize, + budget: usize, +) -> Result { + let mut atoms = Strings::fresh(); + let program = compile_with_budget(code, &mut atoms, max_source_bytes, budget, true)?; + let source = Arc::new(ModuleSource { + name: Arc::from(name), + code: Arc::from(code), + }); + Ok(CompiledModule(Arc::new(CompiledModuleInner { + source, + program, + atoms, + }))) +} + +pub(crate) fn compile_module_program( + code: &str, + atoms: &mut Strings, + max_source_bytes: usize, +) -> Result { + compile_with_budget(code, atoms, max_source_bytes, RUN_STACK_BUDGET, true) +} + +fn compile_diagnostic(code: &str, name: Option<&str>, e: CompileError) -> Diagnostic { let location = e.offset.map(|o| line_col(code, o)); - let message = format!("{}{}", e.message, frame_line(location)); + let message = format!( + "{}{}", + e.message, + frame_line_for(name.unwrap_or(""), location) + ); Diagnostic { kind: e.kind, message: message.into(), @@ -120,10 +205,23 @@ pub fn execute(rt: &Runtime, code: Code<'_>, options: &ProgramOptions) -> Outcom /// more native stack for deep syntax, so only compiling moves. On `wasm32`, where spawning a helper thread is /// unsupported, programs exceeding `RUN_STACK_BUDGET` return an error instead of attempting to spawn or overflowing /// the wasm stack. +/// Minimum free native stack required to compile inline when nested inside a running VM. +const COMPILE_NESTED_BASE: usize = 64 << 10; + pub fn compile( code: &str, atoms: &mut Strings, max_source_bytes: usize, +) -> Result { + compile_with_budget(code, atoms, max_source_bytes, RUN_STACK_BUDGET, false) +} + +fn compile_with_budget( + code: &str, + atoms: &mut Strings, + max_source_bytes: usize, + budget: usize, + sync_module: bool, ) -> Result { if code.len() > max_source_bytes { return Err(CompileError { @@ -132,14 +230,27 @@ pub fn compile( offset: None, }); } + let run_compile = |code: &str, atoms: &mut Strings| { + if sync_module { + compiler::compile_module(code, atoms) + } else { + compiler::compile(code, atoms) + } + }; + let headroom = if budget < RUN_STACK_BUDGET { + COMPILE_NESTED_BASE + } else { + 0 + }; + let inline_budget = budget.saturating_sub(headroom); // A program nests no deeper than it has bytes, so a short one needs no scan to know it fits. - let fits = |levels: usize| levels.saturating_mul(COMPILE_STACK_PER_LEVEL) <= RUN_STACK_BUDGET; + let fits = |levels: usize| levels.saturating_mul(COMPILE_STACK_PER_LEVEL) <= inline_budget; let need = match fits(code.len()) { true => 0, false => nesting::bound(code).saturating_mul(COMPILE_STACK_PER_LEVEL), }; - if need <= RUN_STACK_BUDGET { - return compiler::compile(code, atoms); + if budget >= headroom && need <= inline_budget { + return run_compile(code, atoms); } if need > MAX_COMPILE_LEVELS.saturating_mul(COMPILE_STACK_PER_LEVEL) { return Err(CompileError { @@ -159,10 +270,11 @@ pub fn compile( } #[cfg(not(target_arch = "wasm32"))] { + let stack_size = need.max(RUN_STACK_BUDGET).saturating_add(THREAD_STACK_BASE); std::thread::scope(|s| { std::thread::Builder::new() - .stack_size(need.saturating_add(THREAD_STACK_BASE)) - .spawn_scoped(s, || compiler::compile(code, atoms)) + .stack_size(stack_size) + .spawn_scoped(s, || run_compile(code, atoms)) .map_err(|_| CompileError { kind: DiagnosticKind::ExecutionFailure, message: @@ -213,7 +325,7 @@ pub fn start( let mut atoms = Strings::fresh(); match compile(code, &mut atoms, rt.setup().limits.source_limit()) { Ok(p) => (Arc::from(code), p, atoms), - Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))), + Err(e) => return Err(Box::new(failed(compile_diagnostic(code, None, e)))), } } }; @@ -477,8 +589,16 @@ fn diagnose_text(vm: &mut Vm, e: &Value, code: &str) -> Diagnosed { { let id = *id; if let Some(f) = failure.clone() { - let location = f.offset.map(|o| line_col(code, o)); - let trace = f.trace.clone().unwrap_or_else(|| frame_line(location)); + let (file, src_code) = if f.source == 0 { + ("", code) + } else { + vm.source_info(f.source) + }; + let location = f.offset.map(|o| line_col(src_code, o)); + let trace = f + .trace + .clone() + .unwrap_or_else(|| frame_line_for(file, location)); let message = match f.kind { // A host's failure reads as an Error of its message, whatever its kind. _ if f.host && f.message.is_empty() => format!("Error{trace}"), @@ -509,11 +629,16 @@ fn diagnose_text(vm: &mut Vm, e: &Value, code: &str) -> Diagnosed { _ => convert::error_to_string(vm, id), }; // A `stack` the program replaced with text naming no frame still says where the error was thrown. - return match first_frame(&text) { + return match first_frame(&text, vm.module_sources()) { Some(location) => (DiagnosticKind::ExecutionFailure, text, location, Vec::new()), None => { - let location = thrown.offset.map(|o| line_col(code, o)); - let message = format!("{text}{}", frame_line(location)); + let (file, src_code) = if thrown.source == 0 { + ("", code) + } else { + vm.source_info(thrown.source) + }; + let location = thrown.offset.map(|o| line_col(src_code, o)); + let message = format!("{text}{}", frame_line_for(file, location)); ( DiagnosticKind::ExecutionFailure, message, @@ -539,8 +664,15 @@ fn diagnose_text(vm: &mut Vm, e: &Value, code: &str) -> Diagnosed { } text }; - let location = thrown.offset.map(|o| line_col(code, o)); - let trace = thrown.trace.unwrap_or_else(|| frame_line(location)); + let (file, src_code) = if thrown.source == 0 { + ("", code) + } else { + vm.source_info(thrown.source) + }; + let location = thrown.offset.map(|o| line_col(src_code, o)); + let trace = thrown + .trace + .unwrap_or_else(|| frame_line_for(file, location)); ( DiagnosticKind::ExecutionFailure, format!("Uncaught {text}{trace}"), @@ -549,27 +681,36 @@ fn diagnose_text(vm: &mut Vm, e: &Value, code: &str) -> Diagnosed { ) } -/// The ` at :line:col` line a location stands for; none without one. -fn frame_line(location: Option<(u32, u32)>) -> String { +/// The ` at :line:col` line a location stands for; none without one. +fn frame_line_for(file: &str, location: Option<(u32, u32)>) -> String { match location { - Some((line, col)) => format!("\n at :{line}:{col}"), + Some((line, col)) => format!("\n at {file}:{line}:{col}"), None => String::new(), } } -/// The first `stack` line of `text` naming a program place, ` at [name (]:line:col[)]`: `Some` with its -/// line and column when it names a real one, `Some(None)` when its numbers name none, `None` when there is no such -/// line. -fn first_frame(text: &str) -> Option> { +/// The first `stack` line of `text` naming a program or loaded module place, +/// ` at [name (]:line:col[)]`: `Some` with its line and column when it names a real one, +/// `Some(None)` when its numbers name none, `None` when there is no such line. +fn first_frame(text: &str, modules: &[Arc]) -> Option> { + fn match_file<'a>(rest: &'a str, file: &str) -> Option<(&'a str, &'a str)> { + let after = if let Some(after) = rest.strip_prefix(file) { + after + } else { + let at = rest.rfind(file)?; + if at == 0 || !rest[..at].ends_with(" (") { + return None; + } + &rest[at + file.len()..] + }; + after.strip_prefix(':')?.split_once(':') + } text.split(['\n', '\r', '\u{2028}', '\u{2029}']) .find_map(|line| { let rest = line.strip_prefix(" at ")?; let rest = rest.strip_suffix(')').unwrap_or(rest); - let at = rest.rfind(":")?; - if at != 0 && !rest[..at].ends_with(" (") { - return None; - } - let (l, c) = rest[at + ":".len()..].split_once(':')?; + let (l, c) = match_file(rest, "") + .or_else(|| modules.iter().find_map(|m| match_file(rest, &m.name)))?; let digits = |t: &str| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()); if !digits(l) || !digits(c) { return None; @@ -667,8 +808,9 @@ fn bound_output(mut outcome: Outcome, max: Option) -> Outcome { outcome } -// A compiled program is shared by runs on any thread. +// Compiled programs and modules are immutable and shared across threads. const _: () = { const fn shared() {} - shared::() + shared::(); + shared::(); }; diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 76fc20fc..455b28ca 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -7,8 +7,8 @@ use std::sync::{Arc, Mutex}; use crate::data::Kept; use crate::host::RunId; use crate::{ - Code, Compiled, Data, Diagnostic, HostString, HostValue, Interrupted, Json, Limits, Program, - Snapshot, SnapshotError, from_bytes, + Code, Compiled, CompiledModule, Data, Diagnostic, HostString, HostValue, Interrupted, Json, + Limits, Program, Snapshot, SnapshotError, from_bytes, }; /// How a run ended: its value or failure, with what it logged and its metadata. @@ -422,6 +422,15 @@ impl Runtime { crate::run::compile_program(code, self.setup.limits.source_limit()) } + /// Parses and compiles a synchronous named module once into an immutable, `Send + Sync` + /// [`CompiledModule`] ready to be executed in any [`Session`](crate::Session) via + /// [`Session::eval_compiled`](crate::Session::eval_compiled) or + /// [`HostCtx::eval_compiled`](crate::HostCtx::eval_compiled). Respects + /// [`Limits::max_source_bytes`](crate::Limits::max_source_bytes). + pub fn compile_module(&self, source: &str, name: &str) -> Result { + crate::run::compile_module(source, name, self.setup.limits.source_limit()) + } + /// A program continuing a suspended run, from its state. It keeps the limits it was saved with, and its globals /// are made again for the run with its saved id and metadata. Fails with a [`SnapshotError`] when the state was /// saved by another build, with other host globals, from a source that no longer compiles the same, or is diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs index 35c7ead7..7fb9200d 100644 --- a/rust/crates/psychoscript/src/session.rs +++ b/rust/crates/psychoscript/src/session.rs @@ -11,7 +11,10 @@ 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}; +use crate::{ + Code, CompiledModule, Data, Outcome, ProgramOptions, Runtime, Snapshot, SnapshotError, + SuspendError, +}; /// What a session's run keeps: the value its top level returned, once it has. #[derive(Default)] @@ -50,6 +53,41 @@ impl Session { self.program.drive_session(|vm| call(vm, name, args)) } + /// Merges a precompiled [`CompiledModule`] into this session and executes it through the session + /// driver without re-compiling. Loaded modules survive [`Session::save`] and + /// [`Runtime::restore_session`]. + /// + /// Each call appends and executes the module's bytecode, so embedder module loaders should + /// cache module exports per specifier rather than repeatedly re-evaluating the same module. + pub fn eval_compiled(&mut self, module: &CompiledModule) -> Outcome { + self.program + .drive_session(|vm| eval_compiled_in_session(vm, module)) + } + + /// Compiles `source` as a synchronous named module (respecting + /// [`Limits::max_source_bytes`](crate::Limits::max_source_bytes)) and executes it in this + /// session. + pub fn eval_module(&mut self, source: &str, name: &str) -> Outcome { + let Some(vm) = self.program.session_vm() else { + return self.program.drive_session(|_| {}); + }; + if vm.fatal.is_some() { + return self.program.drive_session(|_| {}); + } + let limit = vm.limits.source_limit(); + let metadata = vm.host.run.metadata(); + match crate::run::compile_module(source, name, limit) { + Ok(compiled) => self.eval_compiled(&compiled), + Err(diag) => Outcome { + result: Err(diag), + warnings: Vec::new(), + logs: Vec::new(), + truncated: false, + metadata, + }, + } + } + /// 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. @@ -135,6 +173,54 @@ fn call(vm: &mut Vm, name: &str, args: &[Data]) { } } +/// Loads a precompiled module and drives its synchronous entry closure through `Promise.try`, +/// matching `call` so results, promises, limits, GC, and error stacks behave identically. +fn eval_compiled_in_session(vm: &mut Vm, module: &CompiledModule) { + let entry_idx = match vm.load_module(module) { + Ok(idx) => idx, + Err(e) => { + vm.outcome.get_or_insert(Err(e)); + return; + } + }; + let entry = make_module_entry(vm, entry_idx); + 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, + entry, + Value::Undef, + &[], + ); + match entered { + Ok(_) => vm.take_entered(), + Err(e) => vm.reject(p, e), + } +} + +fn make_module_entry(vm: &mut Vm, entry_idx: usize) -> Value { + let proto = vm.protos[entry_idx].clone(); + let fp = vm.realm.function_proto; + Value::Obj(vm.alloc(crate::object::Obj::new( + Some(fp), + Kind::Closure(Box::new(crate::object::Closure { + proto, + upvals: Arc::from(Vec::new()), + this: Value::Undef, + home: Value::Undef, + fields: Value::Undef, + })), + ))) +} + // ---------- direct host functions ---------- /// A program value a [`HostFunction::direct`](crate::HostFunction::direct) call can use while it runs, and only then: @@ -410,6 +496,51 @@ impl<'a> HostCtx<'a> { r.map(Val::of).map_err(Val::of) } + /// Merges a precompiled [`CompiledModule`] into this live VM and executes it synchronously + /// without re-compiling (ideal for host-implemented `require()` loaders). The time the module + /// executes is counted as program time. Loaded modules survive snapshots and session save/restore. + /// + /// Each call appends and executes the module's bytecode, so embedder module loaders should + /// cache module exports per specifier rather than repeatedly re-evaluating the same module. + pub fn eval_compiled(&mut self, module: &CompiledModule) -> Result, Val<'a>> { + if self.vm.fatal.is_some() { + return Err(Val::undefined()); + } + let entry_idx = self.vm.load_module(module).map_err(Val::of)?; + let entry = make_module_entry(self.vm, entry_idx); + self.call(Val::of(entry), Val::undefined(), &[]) + } + + /// Compiles `source` as a synchronous named module (respecting + /// [`Limits::max_source_bytes`](crate::Limits::max_source_bytes)) and executes it in this live + /// VM. + pub fn eval_module(&mut self, source: &str, name: &str) -> Result, Val<'a>> { + if self.vm.fatal.is_some() { + return Err(Val::undefined()); + } + let limit = self.vm.limits.source_limit(); + let budget = self.vm.stack_remaining(); + let compiled = crate::run::compile_module_with_budget(source, name, limit, budget); + let compiled = match compiled { + Ok(c) => c, + Err(e) => { + let msg = e + .message + .strip_prefix("SyntaxError: ") + .unwrap_or(&e.message); + let err = match e.kind { + crate::DiagnosticKind::ParseError => self.vm.syntax_error(msg), + _ => { + let proto = self.vm.realm.error_proto; + self.vm.make_error(proto, msg) + } + }; + return Err(Val::of(err)); + } + }; + self.eval_compiled(&compiled) + } + /// 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; diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index 11526277..8c276d76 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -416,38 +416,53 @@ fn vals(items: &[Value]) -> J { J::Array(items.iter().map(val).collect()) } -/// Where a rejection's reason was thrown, as `[offset, trace]`. -fn thrown(t: &Option>) -> J { - match t { - Some(t) => json!([t.offset, t.trace]), +/// Encodes a call site: plain `offset` when in `Vm::code` (preserving the existing format), +/// or `[offset, source]` when in a loaded named module. +fn call_site(s: &Option) -> J { + match s { None => J::Null, + Some(s) if s.is_program() => json!(s.offset()), + Some(s) => json!([s.offset(), s.source()]), } } -fn thrown_from(j: Option<&J>) -> R>> { - match j { - None | Some(J::Null) => Ok(None), - Some(j) => Ok(Some(Box::new(crate::object::Thrown { - offset: opt_u32(at(j, 0)?)?, - trace: trace_from(j.get(1))?, - }))), +/// Where a rejection's reason was thrown, as `[offset, trace]` (or `[offset, trace, source]` for a module). +fn thrown(t: &Option>) -> J { + match t { + Some(t) if t.source == 0 => json!([t.offset, t.trace]), + Some(t) => json!([t.offset, t.trace, t.source]), + None => J::Null, } } -/// A failure's stack lines, as the run writes them: at most 10 ` at` lines naming program places, each name at most -/// 200 characters. They reach a diagnostic's message, so a saved state can't make them anything else. -fn trace_from(j: Option<&J>) -> R> { +/// A failure's stack lines, as the run writes them: at most 10 ` at` lines naming program or loaded module places, +/// each name at most 200 characters. They reach a diagnostic's message, so a saved state can't make them anything else. +fn trace_from(j: Option<&J>, modules: &[Arc]) -> R> { let text = match j { None | Some(J::Null) => return Ok(None), Some(j) => string(j)?, }; + let max_name = modules + .iter() + .map(|m| m.name.chars().count()) + .max() + .unwrap_or(0); + let max_line = 240usize.saturating_add(max_name); + let max_total = 4_000usize.saturating_add(max_name.saturating_mul(10)); + let has_known_file = |line: &str| { + line.contains(":") + || modules.iter().any(|m| { + line.match_indices(&*m.name) + .any(|(i, _)| line[i + m.name.len()..].starts_with(':')) + }) + }; let lines: Vec<&str> = text.split('\n').collect(); - let valid = text.len() <= 4_000 + let valid = text.len() <= max_total && lines.first() == Some(&"") && lines.len() <= 11 && lines[1..].iter().all(|l| { l.strip_prefix(" at ") - .is_some_and(|l| l.contains(":") && l.chars().count() <= 240) + .is_some_and(|l| has_known_file(l) && l.chars().count() <= max_line) }); if !valid { return Err(invalid("a failure's stack is not stack lines.")); @@ -688,6 +703,19 @@ impl Enc<'_> { if let Some(s) = &vm.session { state["session"] = json!({ "exports": s.exports.as_ref().map(val) }); } + // Only runs that loaded named modules emit `modules`, keeping single-file snapshots unchanged. + if let Some(loaded) = vm.loaded_code.as_deref() + && !loaded.sources.is_empty() + { + state["modules"] = json!({ + "sources": loaded + .sources + .iter() + .map(|s| json!([&*s.name, &*s.code])) + .collect::>(), + "loads": loaded.loads, + }); + } Ok(state) } @@ -760,7 +788,7 @@ impl Enc<'_> { call.path.as_deref().map(texts), args, call.owner, - call.site + call_site(&call.site) ]); // A tag's raw strings, only for a call that has them. if let (Some(raw), J::Array(entry)) = (&call.raw, &mut entry) { @@ -830,7 +858,20 @@ impl Enc<'_> { Kind::Error(f) => match f { None => json!(["e", J::Null]), // A host's failure keeps that it is one: its kind may be named like the language's. - Some(f) => json!(["e", [f.kind.name(), f.message, f.offset, f.host, f.trace]]), + Some(f) if f.source == 0 => { + json!(["e", [f.kind.name(), f.message, f.offset, f.host, f.trace]]) + } + Some(f) => json!([ + "e", + [ + f.kind.name(), + f.message, + f.offset, + f.host, + f.trace, + f.source + ] + ]), }, Kind::Promise(d) => { let state = match &d.state { @@ -839,7 +880,7 @@ impl Enc<'_> { PromiseState::Rejected(e) => json!(["err", val(e)]), }; let reactions: Vec = d.reactions.iter().map(reaction).collect(); - json!(["p", state, reactions, d.site, thrown(&d.thrown)]) + json!(["p", state, reactions, call_site(&d.site), thrown(&d.thrown)]) } Kind::Map(m) => json!(["m", map(m)]), Kind::Set(m) => json!(["s", map(m)]), @@ -1031,7 +1072,7 @@ impl Enc<'_> { let (kind, message, suggestions) = f.parts(); json!([p, "fail", kind.name(), text(message), texts(suggestions)]) } - Settlement::Lost(message, site) => json!([p, "lost", message, site]), + Settlement::Lost(message, site) => json!([p, "lost", message, call_site(site)]), Settlement::Host(h) => { let Settled { result, @@ -1056,9 +1097,18 @@ impl Enc<'_> { if ok && let Some(at_label) = lost_path(data, label) { let message = format!("{at_label} produced a Lost, which the program cannot hold."); - return Ok(json!([p, "lost", message, site])); + return Ok(json!([p, "lost", message, call_site(site)])); } - json!([p, "host", ok, label, owner, hooked, host_value(data), site]) + json!([ + p, + "host", + ok, + label, + owner, + hooked, + host_value(data), + call_site(site) + ]) } Settlement::Interrupted => json!([p, "interrupted"]), }) @@ -1853,9 +1903,52 @@ struct Dec<'p> { heap_len: usize, bufs_len: usize, protos: usize, + sources: Vec>, _p: std::marker::PhantomData<&'p ()>, } +impl Dec<'_> { + fn source_id(&self, j: Option<&J>) -> R { + let Some(j) = j else { + return Ok(0); + }; + if j.is_null() { + return Ok(0); + } + let id = u32_(j)?; + if id as usize > self.sources.len() { + return Err(invalid("a module source index is out of range.")); + } + Ok(id) + } + + fn call_site(&self, j: Option<&J>) -> R> { + match j { + None | Some(J::Null) => Ok(None), + Some(J::Number(_)) => Ok(Some(crate::bytecode::CallSite::new(u32_(j.unwrap())?, 0))), + Some(J::Array(_)) => { + let j = j.unwrap(); + Ok(Some(crate::bytecode::CallSite::new( + u32_(at(j, 0)?)?, + self.source_id(Some(at(j, 1)?))?, + ))) + } + _ => Err(invalid("a call site is malformed.")), + } + } + + fn thrown_from(&self, j: Option<&J>) -> R>> { + match j { + None | Some(J::Null) => Ok(None), + Some(j) => Ok(Some(Box::new(crate::object::Thrown { + offset: opt_u32(at(j, 0)?)?, + source: self.source_id(j.get(2))?, + trace: trace_from(j.get(1), &self.sources)?, + }))), + } + } +} + impl Dec<'_> { fn val(&self, j: &J) -> R { let id = |s: &str| -> R { @@ -2273,9 +2366,10 @@ impl Dec<'_> { kind: kind_named(&string(at(e, 0)?)?)?, message: string(at(e, 1)?)?, offset: opt_u32(at(e, 2)?)?, + source: self.source_id(e.get(5))?, site: Default::default(), host: e.get(3).is_some_and(|h| h == &J::Bool(true)), - trace: trace_from(e.get(4))?, + trace: trace_from(e.get(4), &self.sources)?, })), }), "p" => { @@ -2292,8 +2386,8 @@ impl Dec<'_> { .iter() .map(|r| self.reaction(r)) .collect::>()?; - let site = opt_u32(f(3)?)?; - let thrown = thrown_from(f(4).ok())?; + let site = self.call_site(f(3).ok())?; + let thrown = self.thrown_from(f(4).ok())?; Kind::Promise(Box::new(PromiseData { state, reactions, @@ -2499,7 +2593,7 @@ impl Dec<'_> { Some("r") => Job::Reaction( self.reaction(at(j, 1)?)?, self.outcome(at(j, 2)?)?, - thrown_from(j.get(3))?, + self.thrown_from(j.get(3))?, ), Some("t") => Job::Thenable { promise: self.id(at(j, 1)?)?, @@ -2658,13 +2752,67 @@ pub fn restore(vm: &mut Vm, snapshot: &Snapshot, program_hash: &str) -> R<()> { .collect::>()?; vm.atoms.restore(texts, atoms).map_err(invalid)?; - // Built-in code the run compiled (`Array.fromAsync`'s), after the program's, compiled again. + // Dynamically compiled code (`Array.fromAsync` and named modules), replayed in exact load order. let code = st .get("code") .map(usize_) .transpose()? .unwrap_or(vm.protos.len()); - if code > vm.protos.len() { + let mut restored_sources: Vec> = Vec::new(); + let mut pending_bigints: Vec<(usize, num_bigint::BigInt)> = Vec::new(); + if let Some(mods) = st.get("modules") { + for pair in field_list(mods, "sources")? { + restored_sources.push(Arc::new(crate::bytecode::ModuleSource { + name: Arc::from(string(at(pair, 0)?)?), + code: Arc::from(string(at(pair, 1)?)?), + })); + } + let loads: Vec> = field_list(mods, "loads")? + .iter() + .map(|entry| { + if entry.is_null() { + Ok(None) + } else { + let idx = u32_(entry)?; + if idx as usize >= restored_sources.len() { + return Err(invalid("a loaded module index is out of range.")); + } + Ok(Some(idx)) + } + }) + .collect::>()?; + vm.loaded_code = Some(Box::new(crate::vm::LoadedCodeState { + sources: restored_sources.clone(), + loads: Vec::with_capacity(loads.len()), + })); + for entry in loads { + match entry { + None => { + if crate::builtins::array::from_async_code(vm, false).is_none() { + return Err(invalid("built-in code failed to compile.")); + } + } + Some(idx) => { + let src = &restored_sources[idx as usize]; + let mut mod_atoms = crate::strings::Strings::fresh(); + let program = crate::run::compile_module_program( + &src.code, + &mut mod_atoms, + src.code.len(), + ) + .map_err(|_| { + SnapshotError::new(format!( + "Module {} does not compile in this build, so it can't resume.", + src.name + )) + })?; + vm.restore_module(idx + 1, &program, &mod_atoms, &mut pending_bigints) + .map_err(invalid)?; + vm.loaded_code.get_or_insert_default().loads.push(Some(idx)); + } + } + } + } else if code > vm.protos.len() { crate::builtins::array::from_async_code(vm, false); } if code != vm.protos.len() { @@ -2677,6 +2825,7 @@ pub fn restore(vm: &mut Vm, snapshot: &Snapshot, program_hash: &str) -> R<()> { heap_len: base.heap + rest.len(), bufs_len: vm.atoms.counts().0, protos: vm.protos.len(), + sources: restored_sources, _p: std::marker::PhantomData, }; if vm.heap.len() != base.heap { @@ -2842,6 +2991,9 @@ pub fn restore(vm: &mut Vm, snapshot: &Snapshot, program_hash: &str) -> R<()> { if !vm.intern_restored(base.heap) { return Err(invalid("a BigInt is saved twice.")); } + for (const_idx, n) in pending_bigints { + vm.consts[const_idx] = vm.big_val(n); + } restore_host(vm, &dec, field(st, "host")?, base)?; let inbox = field_list(st, "inbox")?; @@ -2867,7 +3019,7 @@ fn restore_settlement(vm: &mut Vm, dec: &Dec, j: &J) -> R<(Id, Settlement)> { let owner = opt_string(at(j, 4)?)?; let hooked = boolean(at(j, 5)?)?; let saved = at(j, 6)?; - let site = j.get(7).and_then(J::as_u64).map(|s| s as u32); + let site = dec.call_site(j.get(7))?; // What a call returned is the host's until the program takes it, and may nest at any depth: the program // meets `max_value_depth` when it takes it, as it would have without a suspend. let mut v = host_value_within(saved, usize::MAX)?; @@ -2876,10 +3028,7 @@ fn restore_settlement(vm: &mut Vm, dec: &Dec, j: &J) -> R<(Id, Settlement)> { } Settlement::host(if ok { Ok(v) } else { Err(v) }, label, owner, site) } - Some("lost") => Settlement::Lost( - string(at(j, 2)?)?, - j.get(3).and_then(J::as_u64).map(|s| s as u32), - ), + Some("lost") => Settlement::Lost(string(at(j, 2)?)?, dec.call_site(j.get(3))?), Some("interrupted") => Settlement::Interrupted, _ => return Err(invalid("a settlement is unknown.")), }; @@ -3013,7 +3162,7 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { .map(host_value_from) .collect::>()?, owner: opt_string(at(c, 6)?)?, - site: at(c, 7)?.as_u64().map(|s| s as u32), + site: dec.call_site(c.get(7))?, start, raw: c.get(8).map(texts_from).transpose()?, }; diff --git a/rust/crates/psychoscript/src/stack.rs b/rust/crates/psychoscript/src/stack.rs index d9a75ce1..fdc0c200 100644 --- a/rust/crates/psychoscript/src/stack.rs +++ b/rust/crates/psychoscript/src/stack.rs @@ -31,14 +31,19 @@ impl Vm { /// `Runtime::program_lines` those in the host's lines. Then, as V8's async stack traces, `at async` lines for the /// async functions (and the program) awaiting the one the stack started in, each at its `await`. pub(crate) fn stack_trace(&mut self) -> String { - self.stack_trace_at(None, None) + self.stack_trace_at(None, 0, None) } /// `stack_trace` for a failure at `top`, the reference's `Vm.stackTrace(top, settled)`: `top` stands for the /// innermost frame's site, or is the only line when that frame isn't where it happened (a failure from elsewhere). /// With `settled`, the promise a host call at `top` settles while the program is elsewhere, the stack starts at the /// frame awaiting it instead, when that frame awaits the call at `top`. - pub(crate) fn stack_trace_at(&mut self, top: Option, settled: Option) -> String { + pub(crate) fn stack_trace_at( + &mut self, + top: Option, + top_source: u32, + settled: Option, + ) -> String { let mut trace = String::new(); let mut shown = 0; // The coroutine whose promise the async walk follows. @@ -52,11 +57,12 @@ impl Vm { let f = &self.frames[i]; let site = self.frame_site(f); let Some(site) = site else { continue }; + let source = f.func.source(); if shown == 0 && let Some(top) = top - && !self.frame_encloses(i, top) + && (source != top_source || !self.frame_encloses(i, top)) { - return self.stack_line(top, None); + return self.stack_line(top, None, top_source); } let at = if shown == 0 { top.unwrap_or(site) @@ -64,7 +70,7 @@ impl Vm { site }; let name = self.frame_name(i); - trace.push_str(&self.stack_line_as(at, name.as_deref(), false)); + trace.push_str(&self.stack_line_as(at, name.as_deref(), false, source)); shown += 1; } root = match self.frames.first().map(|f| &f.kind) { @@ -75,11 +81,17 @@ impl Vm { Some(p) => { if let (Some(top), Some(c)) = (top, self.awaiter(p)) && let Some((func, pc, callee)) = self.parked_frame(c) + && func.source() == top_source && func.pos.get(pc.wrapping_sub(2)) == Some(&top) { - if self.in_program(top) { + if func.source() != 0 || self.in_program(top) { let name = self.name_of(&func, callee); - trace.push_str(&self.stack_line_as(top, name.as_deref(), false)); + trace.push_str(&self.stack_line_as( + top, + name.as_deref(), + false, + func.source(), + )); shown += 1; } root = Some(c); @@ -98,15 +110,15 @@ impl Vm { break; }; if let Some(&site) = func.pos.get(pc.wrapping_sub(1)) - && self.in_program(site) + && (func.source() != 0 || self.in_program(site)) { let name = self.name_of(&func, callee); - trace.push_str(&self.stack_line_as(site, name.as_deref(), true)); + trace.push_str(&self.stack_line_as(site, name.as_deref(), true, func.source())); shown += 1; } } match top { - Some(top) if shown == 0 => self.stack_line(top, None), + Some(top) if shown == 0 => self.stack_line(top, None, top_source), _ => trace, } } @@ -118,7 +130,7 @@ impl Vm { return None; } let site = f.func.pos.get(f.pc.saturating_sub(1)).copied()?; - self.in_program(site).then_some(site) + (f.func.source() != 0 || self.in_program(site)).then_some(site) } /// Whether a failure at `top` happened in frame `i`: at the instruction it is at, or a part of it, or the call an @@ -135,7 +147,7 @@ impl Vm { && f.func.pos.get(at - 1) == Some(&top)) } - /// The name frame `i` shows: none for the program's own. + /// The name frame `i` shows: none for the program's own or a module's top-level entry. fn frame_name(&mut self, i: usize) -> Option { let f = &self.frames[i]; let func = f.func.clone(); @@ -148,7 +160,7 @@ impl Vm { func: &crate::bytecode::FuncProto, callee: Option, ) -> Option { - if func.is_program { + if func.is_program || func.is_module_entry { return None; } let name = match callee { @@ -196,15 +208,22 @@ impl Vm { Some((f.func.clone(), f.pc, saved.stack.first().map(|s| s.get()))) } - /// One `stack` line for a site of the program: `at name (:line:col)`, or `at :line:col`. - pub(crate) fn stack_line(&self, offset: u32, name: Option<&str>) -> String { - self.stack_line_as(offset, name, false) + /// One `stack` line for a site of a program or named module: `at name (file:line:col)`, or `at file:line:col`. + pub(crate) fn stack_line(&self, offset: u32, name: Option<&str>, source: u32) -> String { + self.stack_line_as(offset, name, false, source) } /// `stack_line`, with `async` after `at` for a frame awaiting the one above it. A name is the program's to set: /// one line of at most 200 characters, so it cannot make lines of its own. - fn stack_line_as(&self, offset: u32, name: Option<&str>, awaiting: bool) -> String { - let (line, column) = crate::run::line_col(&self.code, offset); + fn stack_line_as( + &self, + offset: u32, + name: Option<&str>, + awaiting: bool, + source: u32, + ) -> String { + let (file, code) = self.source_info(source); + let (line, column) = crate::run::line_col(code, offset); let at = if awaiting { "async " } else { "" }; match name { Some(n) => { @@ -216,9 +235,9 @@ impl Vm { c => c, }) .collect(); - format!("\n at {at}{n} (:{line}:{column})") + format!("\n at {at}{n} ({file}:{line}:{column})") } - None => format!("\n at {at}:{line}:{column}"), + None => format!("\n at {at}{file}:{line}:{column}"), } } @@ -231,12 +250,19 @@ impl Vm { .push_new(sk, text, HIDDEN | PENDING_STACK); } - /// Locates a host failure made at a call, at `offset`, and gives it the program's stack there (see + /// Locates a host failure made at a call, at `site`, and gives it the program's stack there (see /// `stack_trace_at`). - pub(crate) fn host_failure_stack(&mut self, id: Id, offset: u32, settled: Option) { - let line = self.stack_trace_at(Some(offset), settled); + pub(crate) fn host_failure_stack( + &mut self, + id: Id, + offset: u32, + source: u32, + settled: Option, + ) { + let line = self.stack_trace_at(Some(offset), source, settled); if let Kind::Error(Some(f)) = &mut self.heap[id as usize].kind { f.offset = Some(offset); + f.source = source; f.trace = Some(line.clone()); } let sk = self.names.stack; @@ -251,11 +277,12 @@ impl Vm { /// gets them as its `stack`. pub(crate) fn see_thrown(&mut self, e: Value) { if !matches!(self.thrown.as_deref(), Some((v, _)) if same_value(v, &e)) { - let offset = self.call_offset(); + let site = self.call_location(); self.thrown = Some(Box::new(( e, crate::object::Thrown { - offset, + offset: site.map(crate::bytecode::CallSite::offset), + source: site.map_or(0, crate::bytecode::CallSite::source), trace: None, }, ))); @@ -264,14 +291,15 @@ impl Vm { return; }; let Some(offset) = t.offset else { return }; + let source = t.source; match e { Value::Obj(id) if matches!(self.heap[id as usize].kind, Kind::Error(_)) => { if matches!(self.heap[id as usize].kind, Kind::Error(None)) { - self.locate_stack(id, offset); + self.locate_stack(id, offset, source); } } _ if t.trace.is_none() => { - let trace = self.stack_trace_at(Some(offset), None); + let trace = self.stack_trace_at(Some(offset), source, None); if let Some((_, t)) = self.thrown.as_deref_mut() { t.trace = Some(trace); } @@ -297,23 +325,25 @@ impl Vm { &mut self, p: Id, e: &Value, - site: Option, + site: Option, ) -> crate::object::Thrown { - if let (Value::Obj(id), Some(o)) = (*e, site) + if let (Value::Obj(id), Some(s)) = (*e, site) && let Kind::Error(Some(f)) = &self.heap[id as usize].kind && f.offset.is_none() { if f.host { - self.host_failure_stack(id, o, Some(p)); + self.host_failure_stack(id, s.offset(), s.source(), Some(p)); } else { if let Kind::Error(Some(f)) = &mut self.heap[id as usize].kind { - f.offset = Some(o); + f.offset = Some(s.offset()); + f.source = s.source(); } - self.locate_stack_settled(id, o, Some(p)); + self.locate_stack_settled(id, s.offset(), s.source(), Some(p)); } } self.take_thrown(e).unwrap_or(crate::object::Thrown { - offset: site, + offset: site.map(crate::bytecode::CallSite::offset), + source: site.map_or(0, crate::bytecode::CallSite::source), trace: None, }) } @@ -343,22 +373,31 @@ impl Vm { return; } let f = &self.frames[fi]; + let source = f.func.source(); let offset = match f.kind { FrameKind::Native(..) => None, _ => f.func.pos.get(f.pc.saturating_sub(1)).copied(), }; - let line = offset.map(|o| self.stack_line(o, None)).unwrap_or_default(); + let line = offset + .map(|o| self.stack_line(o, None, source)) + .unwrap_or_default(); let text = self.string_val(line); self.heap[id as usize].props.items[i].set_value(text); } /// Points the lines of a failure's `stack` not read yet at the site `offset` it failed at, once it has one. - pub(crate) fn locate_stack(&mut self, id: Id, offset: u32) { - self.locate_stack_settled(id, offset, None); + pub(crate) fn locate_stack(&mut self, id: Id, offset: u32, source: u32) { + self.locate_stack_settled(id, offset, source, None); } /// `locate_stack` for a host call at `offset` that settles `settled` (see `stack_trace_at`). - pub(crate) fn locate_stack_settled(&mut self, id: Id, offset: u32, settled: Option) { + pub(crate) fn locate_stack_settled( + &mut self, + id: Id, + offset: u32, + source: u32, + settled: Option, + ) { let sk = self.names.stack; let slot = self.heap[id as usize].props.find(sk).filter(|&i| { let p = &self.heap[id as usize].props.items[i]; @@ -370,7 +409,7 @@ impl Vm { if slot.is_none() && !traced { return; } - let line = self.stack_trace_at(Some(offset), settled); + let line = self.stack_trace_at(Some(offset), source, settled); if traced && let Kind::Error(Some(f)) = &mut self.heap[id as usize].kind { f.trace = Some(line.clone()); } diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 3cb0dd79..b301d1be 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -368,6 +368,17 @@ pub struct Vm { 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>, + /// Dynamically loaded code chunks (`Array.fromAsync` and named modules), in load order. Saved with the run. + pub(crate) loaded_code: Option>, +} + +/// Distinct named module sources and exact load order of dynamically appended bytecode chunks. +#[derive(Default)] +pub(crate) struct LoadedCodeState { + /// Distinct module sources loaded into this VM; `source_id = index + 1` (`0` is `Vm::code`). + pub sources: Vec>, + /// Load order of appended bytecode chunks (`None` = `Array.fromAsync`, `Some(i)` = `sources[i]`). + pub loads: Vec>, } impl Vm { @@ -516,6 +527,7 @@ impl Vm { slice: None, console: None, session: None, + loaded_code: None, } } @@ -546,6 +558,372 @@ impl Vm { } } + /// Source name and text for `source` (`0` = `Vm::code`, `1..` = loaded module). + #[inline] + pub(crate) fn source_info(&self, source: u32) -> (&str, &str) { + if source == 0 { + return ("", &self.code); + } + match self + .loaded_code + .as_deref() + .and_then(|m| m.sources.get(source as usize - 1)) + { + Some(src) => (&src.name, &src.code), + None => ("", &self.code), + } + } + + /// Source text for `source` (`0` = `Vm::code`, `1..` = loaded module). + #[inline] + pub(crate) fn source_code(&self, source: u32) -> &str { + self.source_info(source).1 + } + + /// Cloned `Arc` of source text for a `CallSite`. + #[inline(always)] + pub(crate) fn call_site_code( + &self, + site: Option, + ) -> Option<(u32, Arc)> { + let s = site?; + let code = if s.is_program() { + self.code.clone() + } else { + self.module_source_code_arc(s.source()) + }; + Some((s.offset(), code)) + } + + #[cold] + #[inline(never)] + fn module_source_code_arc(&self, source: u32) -> Arc { + match self + .loaded_code + .as_deref() + .and_then(|m| m.sources.get(source as usize - 1)) + { + Some(src) => src.code.clone(), + None => self.code.clone(), + } + } + + /// Distinct named module sources loaded into this VM (empty for single-file runs). + #[inline] + pub(crate) fn module_sources(&self) -> &[Arc] { + match self.loaded_code.as_deref() { + Some(m) => &m.sources, + None => &[], + } + } + + /// Records that `Array.fromAsync`'s prelude bytecode was appended to this VM's tables. + pub(crate) fn record_from_async(&mut self) { + self.loaded_code.get_or_insert_default().loads.push(None); + } + + /// Native stack bytes still available within `stack_budget` from `stack_base`. + pub(crate) fn stack_remaining(&self) -> usize { + if self.stack_base == 0 || self.stack_budget == usize::MAX { + return crate::run::RUN_STACK_BUDGET; + } + let probe = 0u8; + let used = self.stack_base.abs_diff(&probe as *const u8 as usize); + self.stack_budget.saturating_sub(used) + } + + /// Merges a precompiled module into this live VM without re-parsing or re-compiling, + /// remapping its interned atoms/strings and exhaustively rebasing all bytecode table indices. + /// Returns the index of the module's entry prototype in `self.protos`. + pub(crate) fn load_module( + &mut self, + module: &crate::run::CompiledModule, + ) -> Result { + if self.fatal.is_some() { + return Err(Value::Undef); + } + let (program, module_atoms) = module.parts(); + + // Step 1: Install any missing lazy built-ins and host globals using borrowed `&str` names + // BEFORE populating any local unrooted atom cache, while preserving pre-existing + // `self.global_map` entries (e.g. custom `console`, `Map`, `require`). + let saved_globals: Vec<(Atom, Value)> = + self.global_map.iter().map(|(&k, &v)| (k, v)).collect(); + let saved_keys: rustc_hash::FxHashSet = + saved_globals.iter().map(|&(k, _)| k).collect(); + let referenced_globals: rustc_hash::FxHashSet = + self.global_names.iter().copied().collect(); + + for &a in &program.globals { + crate::builtins::ensure_global(self, module_atoms.text(a)); + } + if program.names_constructor { + crate::builtins::ensure(self, crate::builtins::LAZY_COLLECTIONS); + crate::builtins::ensure(self, crate::builtins::LAZY_SYMBOLS); + crate::builtins::ensure(self, crate::builtins::LAZY_FROM_ASYNC); + } + for &(k, v) in &saved_globals { + self.gc_shade_atom(k); + if self.heap.marking { + self.gc_shade_value(v); + } + self.global_map.insert(k, v); + } + for &a in &program.globals { + let name = module_atoms.text(a); + let existing = self.atoms.lookup(name); + let unmapped = existing.is_none_or(|k| !saved_keys.contains(&k)); + let first_host_override = crate::host::has_host_global(self, name) + && existing.is_none_or(|k| !referenced_globals.contains(&k)); + if unmapped || first_host_override { + crate::host::define_host_global_by_name(self, name); + } + } + if self.fatal.is_some() { + return Err(Value::Undef); + } + + // Step 2: Check u32 table capacities AFTER lazy built-in setup (which can append protos such + // as `Array.fromAsync`) and BEFORE mutating VM bytecode tables. + let Some((proto_base, const_base, global_base, template_base)) = + self.check_module_capacity(program) + else { + return Err(self.range_error("Module exceeds VM bytecode table capacity.")); + }; + if self.atoms.bufs.len() >= MAX_STRINGS { + self.out_of_memory(); + return Err(Value::Undef); + } + + // Register module source and load order now that table capacities are verified. + let source_arc = module.source_arc(); + let source_id = { + let state = self.loaded_code.get_or_insert_default(); + let idx = if let Some(i) = state + .sources + .iter() + .position(|s| Arc::ptr_eq(s, &source_arc)) + { + i as u32 + } else { + let i = state.sources.len() as u32; + state.sources.push(source_arc); + i + }; + state.loads.push(Some(idx)); + idx + 1 + }; + + // Step 3: Intern atoms, constants, templates, and rebased protos. No `gc_point` runs below, + // and every newly allocated value/atom is shaded and appended to GC-traced VM tables. + let mut bigints = Vec::new(); + if !self.append_rebased_module( + program, + module_atoms, + source_id, + (proto_base, const_base, global_base, template_base), + true, + &mut bigints, + ) { + return Err(self.range_error("Module exceeds VM bytecode table capacity.")); + } + for (const_idx, n) in bigints { + let bv = self.big_val(n); + if self.heap.marking { + self.gc_shade_value(bv); + } + self.consts[const_idx] = bv; + } + if self.fatal.is_some() { + return Err(Value::Undef); + } + Ok(proto_base as usize) + } + + /// Replays a compiled module into this VM during snapshot restore, without touching `self.heap` + /// or `self.global_map`. BigInt constants are deferred to `pending_bigints` so they materialize + /// after `self.heap` and `self.bigints` are restored. + pub(crate) fn restore_module( + &mut self, + source_id: u32, + program: &crate::bytecode::Program, + module_atoms: &Strings, + pending_bigints: &mut Vec<(usize, num_bigint::BigInt)>, + ) -> Result<(), &'static str> { + let Some(bases) = self.check_module_capacity(program) else { + return Err("a restored module exceeds VM bytecode table capacity."); + }; + if !self.append_rebased_module( + program, + module_atoms, + source_id, + bases, + false, + pending_bigints, + ) { + return Err("a restored module exceeds VM bytecode table capacity."); + } + Ok(()) + } + + fn check_module_capacity( + &self, + program: &crate::bytecode::Program, + ) -> Option<(u32, u32, u32, u32)> { + let proto_base = u32::try_from(self.protos.len()).ok()?; + let const_base = u32::try_from(self.consts.len()).ok()?; + let global_base = u32::try_from(self.globals.len()).ok()?; + let template_base = u32::try_from(self.templates.len()).ok()?; + u32::try_from(program.protos.len()) + .ok()? + .checked_add(proto_base)?; + u32::try_from(program.consts.len()) + .ok()? + .checked_add(const_base)?; + u32::try_from(program.globals.len()) + .ok()? + .checked_add(global_base)?; + u32::try_from(program.templates.len()) + .ok()? + .checked_add(template_base)?; + Some((proto_base, const_base, global_base, template_base)) + } + + fn append_rebased_module( + &mut self, + program: &crate::bytecode::Program, + module_atoms: &Strings, + source_id: u32, + (proto_base, const_base, global_base, template_base): (u32, u32, u32, u32), + live: bool, + pending_bigints: &mut Vec<(usize, num_bigint::BigInt)>, + ) -> bool { + let mut atom_cache: FxHashMap = FxHashMap::default(); + let mut remap_atom = |vm: &mut Vm, a: Atom| -> Atom { + if a <= crate::strings::SYM_LAST { + return a; + } + if let Some(&mapped) = atom_cache.get(&a) { + return mapped; + } + if live && vm.atoms.bufs.len() >= MAX_STRINGS { + vm.out_of_memory(); + } + let mapped = vm.atoms.intern(module_atoms.text(a)); + if live { + vm.gc_shade_atom(mapped); + } + atom_cache.insert(a, mapped); + mapped + }; + + // Append remapped constants; defer BigInt constants to caller (live materializes immediately, + // restore materializes after heap + BigInt intern table are restored). + self.consts.reserve(program.consts.len()); + for &v in &program.consts { + let mapped = match v { + Value::Str(s) => { + let sv = self.string_val(module_atoms.get(s).to_owned()); + if live && self.heap.marking { + self.gc_shade_value(sv); + } + sv + } + other => other, + }; + self.consts.push(mapped); + } + for (i, n) in &program.bigints { + pending_bigints.push(((const_base + *i) as usize, n.clone())); + } + + // Append remapped tagged template sites. + self.templates.reserve(program.templates.len()); + self.template_objs.reserve(program.templates.len()); + for site in &program.templates { + let cooked = site + .cooked + .iter() + .map(|opt| { + opt.map(|v| match v { + Value::Str(s) => { + let sv = self.string_val(module_atoms.get(s).to_owned()); + if live && self.heap.marking { + self.gc_shade_value(sv); + } + sv + } + other => other, + }) + }) + .collect(); + let raw = site + .raw + .iter() + .map(|&v| match v { + Value::Str(s) => { + let sv = self.string_val(module_atoms.get(s).to_owned()); + if live && self.heap.marking { + self.gc_shade_value(sv); + } + sv + } + other => other, + }) + .collect(); + self.templates + .push(crate::bytecode::TemplateSite { cooked, raw }); + self.template_objs.push(None); + } + + // Append remapped global slots. + self.global_names.reserve(program.globals.len()); + self.globals.reserve(program.globals.len()); + for &a in &program.globals { + let mapped = remap_atom(self, a); + let v = if live { + let v = self + .global_map + .get(&mapped) + .copied() + .unwrap_or(Value::Uninit); + if self.heap.marking { + self.gc_shade_value(v); + } + self.gc_shade_atom(mapped); + v + } else { + Value::Uninit + }; + self.global_names.push(mapped); + self.globals.push(v); + } + + let source_tag = std::num::NonZeroU32::new(source_id.saturating_add(1)) + .unwrap_or(crate::bytecode::PROGRAM_SOURCE_TAG); + // Clone and rebase every FuncProto with exhaustive checked opcode rebasing. + self.protos.reserve(program.protos.len()); + for proto in &program.protos { + let mut p = (**proto).clone(); + p.name = remap_atom(self, p.name); + p.source_tag = source_tag; + for op in &mut p.code { + if !crate::bytecode::rebase_op( + op, + proto_base, + const_base, + global_base, + template_base, + &mut |a| remap_atom(self, a), + ) { + return false; + } + } + self.protos.push(Arc::new(p)); + } + true + } + // ---------- allocation ---------- #[inline] @@ -749,6 +1127,7 @@ impl Vm { kind, message: msg.to_owned(), offset: None, + source: 0, site: Default::default(), host: false, trace: None, @@ -1172,6 +1551,10 @@ impl Vm { &self.template_objs } + pub(crate) fn templates_ref(&self) -> &[TemplateSite] { + &self.templates + } + pub fn template_objs_mut(&mut self) -> &mut Vec> { &mut self.template_objs } @@ -1976,17 +2359,38 @@ impl Vm { } /// The source offset of that call, where an error about what it returns points. + #[allow(dead_code)] pub(crate) fn call_offset(&self) -> Option { - let own = self + self.call_location().map(crate::bytecode::CallSite::offset) + } + + /// The source site (byte offset and module source index) of the innermost non-native call. + #[inline] + pub(crate) fn call_location(&self) -> Option { + let frame = self .frames .iter() .rev() - .find(|f| !matches!(f.kind, FrameKind::Native(..))) - .and_then(|f| f.func.pos.get(f.pc.wrapping_sub(1)).copied()); - match (self.program, own) { - (Some(_), Some(o)) if !self.in_program(o) => self.program_site().or(own), - _ => own, + .find(|f| !matches!(f.kind, FrameKind::Native(..)))?; + let offset = frame.func.pos.get(frame.pc.wrapping_sub(1)).copied()?; + if self.program.is_none() { + return Some(crate::bytecode::CallSite::from_tag( + frame.func.source_tag, + offset, + )); } + Some(self.call_location_with_program(frame.func.source(), offset)) + } + + #[cold] + #[inline(never)] + fn call_location_with_program(&self, source: u32, offset: u32) -> crate::bytecode::CallSite { + let offset = if source == 0 && !self.in_program(offset) { + self.program_site().unwrap_or(offset) + } else { + offset + }; + crate::bytecode::CallSite::new(offset, source) } /// Whether `offset` is in the program's own lines (`Runtime::program_lines`; every offset without them). @@ -2000,7 +2404,7 @@ impl Vm { self.frames .iter() .rev() - .filter(|f| !matches!(f.kind, FrameKind::Native(..))) + .filter(|f| !matches!(f.kind, FrameKind::Native(..)) && f.func.source() == 0) .filter_map(|f| f.func.pos.get(f.pc.wrapping_sub(1)).copied()) .find(|&o| self.in_program(o)) } @@ -2152,17 +2556,19 @@ impl Vm { // An error the program made, thrown in the host's code (`Runtime::program_lines`): a failure at the nearest // frame of the program, as an error the VM raises there is. if self.program.is_some() + && func.source() == 0 && let Value::Obj(id) = *e && matches!(self.heap[id as usize].kind, Kind::Error(None)) && (func.pos.get(pc.saturating_sub(1))).is_some_and(|&o| !self.in_program(o)) && let Some(p) = self.program_site() { let (_, message) = crate::convert::error_parts(self, id); - let trace = Some(self.stack_trace_at(Some(p), None)); + let trace = Some(self.stack_trace_at(Some(p), 0, None)); self.heap[id as usize].kind = Kind::Error(Some(Box::new(Failure { kind: DiagnosticKind::ExecutionFailure, message, offset: Some(p), + source: 0, site: Default::default(), host: false, trace, @@ -2182,6 +2588,9 @@ impl Vm { { let at = pc.saturating_sub(1); f.offset = func.site(at, f.site).or_else(|| func.pos.get(at).copied()); + if f.offset.is_some() { + f.source = func.source(); + } // Built-in code has no positions (see `builtins::array::from_async_code`): it fails at the program's call // of it, which its function keeps. if func.pos.is_empty() @@ -2197,9 +2606,11 @@ impl Vm { && let Kind::Error(Some(f)) = &mut self.heap[*id as usize].kind { f.offset = Some(o as u32); + f.source = 0; } // Raised in the host's code: at the nearest frame of the program. if let Kind::Error(Some(f)) = &self.heap[*id as usize].kind + && f.source == 0 && let Some(o) = f.offset && !self.in_program(o) && let Some(p) = self.program_site() @@ -2212,7 +2623,8 @@ impl Vm { }; if let Some(o) = f.offset { let id = *id; - self.locate_stack(id, o); + let source = f.source; + self.locate_stack(id, o, source); } } } diff --git a/rust/crates/psychoscript/tests/modules.rs b/rust/crates/psychoscript/tests/modules.rs new file mode 100644 index 00000000..e8951b14 --- /dev/null +++ b/rust/crates/psychoscript/tests/modules.rs @@ -0,0 +1,1149 @@ +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use psychoscript::{ + Clock, CompiledModule, Data, DiagnosticKind, HostError, HostFunction, HostValue, Limits, + ProgramOptions, RunOutcome, Runtime, from_bytes, to_bytes, +}; + +#[test] +fn precompiled_module_runs_in_multiple_sessions_across_threads() { + let rt = Runtime::make(); + let module: CompiledModule = rt + .compile_module( + r#" + let count = 0; + const big = 9007199254740993n; + const map = new Map([["k", 7]]); + const re = /^hi-(\d+)$/; + function tag(parts, v) { + return parts.raw[0] + ":" + v + ":" + parts.raw[1]; + } + function step(delta) { + count += delta; + const m = re.exec("hi-" + count); + return { + count, + bigStr: big.toString(), + fromMap: map.get("k"), + matched: m ? Number(m[1]) : -1, + tagged: tag`pre${count}post`, + }; + } + return { step }; + "#, + "counter.js", + ) + .expect("compile_module"); + + assert_eq!(module.name(), "counter.js"); + assert!(module.code().contains("function step")); + + // Run the exact same Arc-backed CompiledModule in two independent Sessions on two threads + // without recompiling. + let m1 = module.clone(); + let m2 = module.clone(); + + let h1 = std::thread::spawn(move || { + let m = m1.clone(); + let rt = Runtime::make().globals(move |_| { + let m = m.clone(); + vec![( + "loadCounter", + HostValue::Function(HostFunction::direct(move |ctx, _| ctx.eval_compiled(&m))), + )] + }); + let (mut sess, init) = rt.session( + "const c = loadCounter(); return { step: (d) => c.step(d) };", + &ProgramOptions::new(), + ); + init.json().expect("session 1 init"); + let r1 = sess + .call("step", &[Data::from(serde_json::json!(3))]) + .json() + .expect("step 1"); + let r2 = sess + .call("step", &[Data::from(serde_json::json!(4))]) + .json() + .expect("step 2"); + (r1, r2) + }); + + let h2 = std::thread::spawn(move || { + let m = m2.clone(); + let rt = Runtime::make().globals(move |_| { + let m = m.clone(); + vec![( + "loadCounter", + HostValue::Function(HostFunction::direct(move |ctx, _| ctx.eval_compiled(&m))), + )] + }); + let (mut sess, init) = rt.session( + "const c = loadCounter(); return { step: (d) => c.step(d) };", + &ProgramOptions::new(), + ); + init.json().expect("session 2 init"); + // Independent state: starts at 0, not polluted by thread 1. + sess.call("step", &[Data::from(serde_json::json!(10))]) + .json() + .expect("step") + }); + + let (r1, r2) = h1.join().expect("thread 1"); + assert_eq!(r1["count"], serde_json::json!(3)); + assert_eq!( + r2, + serde_json::json!({ + "count": 7, + "bigStr": "9007199254740993", + "fromMap": 7, + "matched": 7, + "tagged": "pre:7:post", + }) + ); + assert_eq!(h2.join().expect("thread 2")["count"], serde_json::json!(10)); + + // Also verify Session::eval_compiled directly returns the module's JSON value. + let pure_mod = rt + .compile_module("const x = 19 + 23; return { answer: x };", "pure.js") + .expect("compile pure.js"); + let (mut sess, init) = rt.session("return {};", &ProgramOptions::new()); + init.json().expect("session init"); + assert_eq!( + sess.eval_compiled(&pure_mod) + .json() + .expect("Session::eval_compiled"), + serde_json::json!({ "answer": 42 }) + ); +} + +#[test] +fn multi_file_require_chain_stack_traces_and_function_to_string() { + let compiler_rt = Runtime::make(); + + let leaf_src = "\ +function greet(name) { return 'hi ' + name; } +function failInLeaf() { + throw new Error('boom from leaf'); +} +function typeErrorInLeaf() { + const x = null; + return x.missing; +} +return { greet, failInLeaf, typeErrorInLeaf }; +"; + + let helper_src = "\ +const leaf = require('leaf.js'); +function callLeaf() { + return leaf.failInLeaf(); +} +function callTypeError() { + return leaf.typeErrorInLeaf(); +} +function helperFn(a, b) { return a + b; } +return { callLeaf, callTypeError, helperFn, greet: leaf.greet }; +"; + + let init_src = "\ +function runChain() { + const helper = require('helper.js'); + try { + helper.callLeaf(); + } catch (e) { + return e.stack; + } +} +function runUncaught() { + const helper = require('helper.js'); + return helper.callLeaf(); +} +function runVmTypeError() { + const helper = require('helper.js'); + try { + helper.callTypeError(); + } catch (e) { + return e.stack; + } +} +function runUncaughtTypeError() { + const helper = require('helper.js'); + return helper.callTypeError(); +} +function inspectSources() { + const helper = require('helper.js'); + return [helper.helperFn.toString(), helper.greet.toString()]; +} +return { runChain, runUncaught, runVmTypeError, runUncaughtTypeError, inspectSources }; +"; + + let leaf_mod = compiler_rt + .compile_module(leaf_src, "leaf.js") + .expect("compile leaf"); + let helper_mod = compiler_rt + .compile_module(helper_src, "helper.js") + .expect("compile helper"); + let init_prog = compiler_rt.compile(init_src).expect("compile init"); + + let registry: Arc> = Arc::new(HashMap::from([ + ("leaf.js".to_owned(), leaf_mod), + ("helper.js".to_owned(), helper_mod), + ])); + let require_calls = Arc::new(Mutex::new(Vec::::new())); + + let rt = Runtime::make().globals({ + let reg = registry.clone(); + let calls = require_calls.clone(); + move |_| { + let reg = reg.clone(); + let calls = calls.clone(); + vec![( + "require", + HostValue::Function(HostFunction::direct(move |ctx, args| { + let Some(spec) = ctx.text(args.get(0)).map(|s| s.into_owned()) else { + return Err(ctx.type_error("require expects a string")); + }; + calls.lock().unwrap().push(spec.clone()); + let Some(module) = reg.get(&spec) else { + return Err(ctx.error(&format!("module not found: {spec}"))); + }; + ctx.eval_compiled(module) + })), + )] + } + }); + + let (mut sess, init) = rt.session(&init_prog, &ProgramOptions::new()); + init.json().expect("start session"); + + // 1. Caught Error.stack contains exact leaf.js, helper.js, and frames. + let stack = sess + .call("runChain", &[]) + .json() + .expect("runChain") + .as_str() + .unwrap() + .to_owned(); + assert!( + stack.contains("Error: boom from leaf"), + "missing error header: {stack}" + ); + assert!( + stack.contains("at failInLeaf (leaf.js:3:11)"), + "missing leaf frame with exact line:col: {stack}" + ); + assert!( + stack.contains("at callLeaf (helper.js:3:12)"), + "missing helper frame with exact line:col: {stack}" + ); + assert!( + stack.contains("at runChain (:4:9)"), + "missing program frame with exact line:col: {stack}" + ); + + // Confirm custom require was called for both helper.js and leaf.js (never clobbered). + assert_eq!(*require_calls.lock().unwrap(), vec!["helper.js", "leaf.js"]); + + // 2. Uncaught Error bubbles into Outcome Diagnostic with exact frames and leaf.js location. + let diag = sess + .call("runUncaught", &[]) + .result + .expect_err("expected uncaught error"); + let msg = diag.message_lossy(); + assert!(msg.contains("at failInLeaf (leaf.js:3:11)"), "msg: {msg}"); + assert!(msg.contains("at callLeaf (helper.js:3:12)"), "msg: {msg}"); + assert_eq!(diag.location, Some((3, 11))); + + // 3. VM-thrown TypeError inside leaf.js resolves exact leaf.js & helper.js frames + location. + let te_stack = sess + .call("runVmTypeError", &[]) + .json() + .expect("runVmTypeError") + .as_str() + .unwrap() + .to_owned(); + assert!( + te_stack.contains("at typeErrorInLeaf (leaf.js:7:"), + "missing VM TypeError leaf frame: {te_stack}" + ); + assert!( + te_stack.contains("at callTypeError (helper.js:6:"), + "missing VM TypeError helper frame: {te_stack}" + ); + + let te_diag = sess + .call("runUncaughtTypeError", &[]) + .result + .expect_err("expected uncaught TypeError"); + assert_eq!(te_diag.location.map(|(l, _)| l), Some(7)); + + // 4. Function.prototype.toString() slices each sub-module's own source text accurately. + let sources = sess + .call("inspectSources", &[]) + .json() + .expect("inspectSources"); + assert_eq!( + sources, + serde_json::json!([ + "function helperFn(a, b) { return a + b; }", + "function greet(name) { return 'hi ' + name; }" + ]) + ); +} + +#[test] +fn eval_module_gc_safety_and_source_limits() { + let rt = Runtime::make().globals(|_| { + vec![( + "loadDynamic", + HostValue::Function(HostFunction::direct(|ctx, _| { + ctx.eval_module( + r#" + const obj = { uniqueDynamicPropName: "hello-dynamic-gc" }; + function readIt() { + return obj.uniqueDynamicPropName; + } + return { readIt }; + "#, + "dynamic.js", + ) + })), + )] + }); + + let (mut sess, init) = rt.session( + r#" + const mod = loadDynamic(); + function churnAndRead() { + let junk = []; + for (let i = 0; i < 2000; i++) junk.push({ k: "tmp" + i }); + return mod.readIt(); + } + return { churnAndRead }; + "#, + &ProgramOptions::new(), + ); + init.json().expect("session init"); + + for _ in 0..3 { + let v = sess + .call("churnAndRead", &[]) + .json() + .expect("call after GC"); + assert_eq!(v, serde_json::json!("hello-dynamic-gc")); + } + + assert_eq!( + sess.eval_module("return 6 * 7;", "direct.js") + .json() + .expect("Session::eval_module"), + serde_json::json!(42) + ); + let parse_err = sess + .eval_module("const = ;", "bad_syntax.js") + .result + .expect_err("expected syntax error"); + assert_eq!(parse_err.kind, DiagnosticKind::ParseError); + assert!( + parse_err.message_lossy().contains("bad_syntax.js:"), + "expected bad_syntax.js in compile diagnostic: {}", + parse_err.message_lossy() + ); + assert_eq!( + sess.call("churnAndRead", &[]) + .json() + .expect("session still healthy"), + serde_json::json!("hello-dynamic-gc") + ); + + let err = rt + .compile_module("const x = await Promise.resolve(1); return x;", "bad.js") + .expect_err("top-level await must fail in sync module"); + assert_eq!(err.kind, DiagnosticKind::ParseError); + + let err = rt + .compile_module("for await (const x of []) {} return 1;", "bad_for.js") + .expect_err("top-level for-await must fail in sync module"); + assert_eq!(err.kind, DiagnosticKind::ParseError); + + // Limits::max_source_bytes applies to compile_module, Session::eval_module, and HostCtx::eval_module. + let tight_rt = Runtime::make() + .limits(Limits { + max_source_bytes: Some(32), + ..Default::default() + }) + .globals(|_| { + vec![( + "loadBig", + HostValue::Function(HostFunction::direct(|ctx, _| { + ctx.eval_module( + "const x = 'this source is definitely longer than 32 bytes'; return x;", + "too_big.js", + ) + })), + )] + }); + let too_big = tight_rt + .compile_module( + "const x = 'this source is definitely longer than 32 bytes'; return x;", + "too_big.js", + ) + .expect_err("compile_module must enforce Limits::max_source_bytes"); + assert_eq!(too_big.kind, DiagnosticKind::ParseError); + + let (mut tight_sess, init) = + tight_rt.session("return { go: () => loadBig() };", &ProgramOptions::new()); + init.json().expect("tight session init"); + let sess_err = tight_sess + .eval_module( + "const x = 'this source is definitely longer than 32 bytes'; return x;", + "too_big.js", + ) + .result + .expect_err("Session::eval_module must enforce Limits::max_source_bytes"); + assert_eq!(sess_err.kind, DiagnosticKind::ParseError); + + let host_err = tight_sess + .call("go", &[]) + .result + .expect_err("HostCtx::eval_module must enforce Limits::max_source_bytes"); + assert!( + host_err.message_lossy().contains("32 bytes"), + "expected source limit error, got: {}", + host_err.message_lossy() + ); + + // Larger Limits::max_source_bytes allows compiling >256 KiB modules. + let huge_rt = Runtime::make().limits(Limits { + max_source_bytes: Some(512 * 1024), + ..Default::default() + }); + let huge = format!( + "const pad = '{}'; return pad.length;", + "a".repeat(260 * 1024) + ); + assert!( + rt.compile_module(&huge, "huge.js").is_err(), + "default 256 KiB cap must reject >256 KiB module" + ); + let huge_mod = huge_rt + .compile_module(&huge, "huge.js") + .expect("custom max_source_bytes should accept >256 KiB module"); + let (mut huge_sess, init) = huge_rt.session("return {};", &ProgramOptions::new()); + init.json().expect("huge session init"); + assert_eq!( + huge_sess + .eval_compiled(&huge_mod) + .json() + .expect("eval large module"), + serde_json::json!(260 * 1024) + ); +} + +#[test] +fn load_module_preserves_custom_globals_under_lazy_builtins_and_gc_stress() { + let compiler_rt = Runtime::make(); + let mod_compiled = compiler_rt + .compile_module( + r#" + const u = new URL("https://example.com/a?b=1"); + const bytes = new Uint8Array([1, 2, 3]); + const s = new Set([10, 20]); + function check() { + return { + consoleTag: console.tag, + mapTag: Map.tag, + urlHost: u.hostname, + bytesLen: bytes.length, + setSize: s.size, + }; + } + return { check }; + "#, + "lazy_globals.js", + ) + .expect("compile lazy_globals"); + + let rt = Runtime::make().globals({ + let m = mod_compiled.clone(); + move |_| { + let m = m.clone(); + vec![ + ( + "console", + HostValue::object([("tag", HostValue::from("custom-console"))]), + ), + ( + "Map", + HostValue::object([("tag", HostValue::from("custom-map"))]), + ), + ( + "loadLazy", + HostValue::Function(HostFunction::direct(move |ctx, _| ctx.eval_compiled(&m))), + ), + ] + } + }); + + let (mut sess, init) = rt.session( + "const initTag = console.tag; const mod = loadLazy(); return { check: () => ({ initTag, ...mod.check() }) };", + &ProgramOptions::new(), + ); + init.json().expect("session init"); + + let res = sess.call("check", &[]).json().expect("check"); + assert_eq!( + res, + serde_json::json!({ + "initTag": "custom-console", + "consoleTag": "custom-console", + "mapTag": "custom-map", + "urlHost": "example.com", + "bytesLen": 3, + "setSize": 2, + }) + ); +} + +#[test] +fn host_ctx_eval_module_syntax_error_has_single_prefix_and_host_call_reports_module_location() { + let seen_loc: Arc>> = Arc::new(Mutex::new(None)); + let caller_mod = Runtime::make() + .compile_module( + "\ +function invokeHost() { + const padding = 1; + hostFail(); +} +return { invokeHost }; +", + "caller.js", + ) + .expect("compile caller.js"); + + let rt = Runtime::make().globals({ + let seen_loc = seen_loc.clone(); + let caller_mod = caller_mod.clone(); + move |_| { + let seen_loc = seen_loc.clone(); + let caller_mod = caller_mod.clone(); + vec![ + ( + "hostFail", + HostValue::Function(HostFunction::new(move |_args, call| { + *seen_loc.lock().unwrap() = call.location(); + Err(HostError::located("TypeError", "bad host input")) + })), + ), + ( + "loadBroken", + HostValue::Function(HostFunction::direct(|ctx, _| { + ctx.eval_module("const = ;", "broken.js") + })), + ), + ( + "loadCaller", + HostValue::Function(HostFunction::direct(move |ctx, _| { + ctx.eval_compiled(&caller_mod) + })), + ), + ] + } + }); + + let (mut sess, init) = rt.session( + "const caller = loadCaller(); return { broken: () => loadBroken(), invoke: () => caller.invokeHost() };", + &ProgramOptions::new(), + ); + init.json().expect("session init"); + + let syntax_err = sess + .call("broken", &[]) + .result + .expect_err("expected syntax error"); + let syntax_msg = syntax_err.message_lossy(); + assert!( + syntax_msg.starts_with("SyntaxError: "), + "expected SyntaxError header, got: {syntax_msg}" + ); + assert!( + !syntax_msg.contains("SyntaxError: SyntaxError:"), + "must not double-prefix SyntaxError: {syntax_msg}" + ); + + let host_err = sess + .call("invoke", &[]) + .result + .expect_err("expected located host error"); + assert_eq!(*seen_loc.lock().unwrap(), Some((3, 5))); + assert_eq!(host_err.location, Some((3, 5))); + let host_msg = host_err.message_lossy(); + assert!( + host_msg.contains("caller.js:3:5"), + "expected caller.js:3:5 in host error stack, got: {host_msg}" + ); +} + +// ---------- Durability & snapshot tests ---------- + +#[test] +fn session_save_restore_preserves_multiple_modules_state_to_string_and_stacks() { + let math_src = "\ +let acc = 10; +const big = 9007199254740993n; +const re = /^val-(\\d+)$/; +const seen = new Map(); +function tag(parts, v) { return parts.raw[0] + '=' + v; } +function add(n) { + acc += n; + seen.set(acc, re.exec('val-' + acc)[1]); + return { + acc, + big: (big + BigInt(acc)).toString(), + tagged: tag`total${acc}`, + fromMap: seen.get(acc), + rawTemplate: tag`same${0}`, + }; +} +function boom() { + throw new Error('math boom'); +} +function vmFail() { + const z = null; + return z.prop; +} +function throwString() { + throw 'plain-module-throw'; +} +function hostCall() { + return hostFail(); +} +function describeAdd() { return add.toString(); } +return { add, boom, vmFail, throwString, hostCall, describeAdd }; +"; + + let wrapper_src = "\ +const math = loadMath(); +function callBoom() { + return math.boom(); +} +function callVmFail() { + return math.vmFail(); +} +function callHost() { + return math.hostCall(); +} +function wrapperFn(x) { return x * 2; } +return { math, callBoom, callVmFail, callHost, wrapperFn }; +"; + + let make_runtime = |seen_loc: Arc>>| { + let math_mod = Runtime::make() + .compile_module(math_src, "math.js") + .expect("compile math.js"); + let wrapper_mod = Runtime::make() + .compile_module(wrapper_src, "wrapper.js") + .expect("compile wrapper.js"); + Runtime::make().globals(move |_| { + let math_mod = math_mod.clone(); + let wrapper_mod = wrapper_mod.clone(); + let seen_loc = seen_loc.clone(); + vec![ + ( + "loadMath", + HostValue::Function(HostFunction::direct(move |ctx, _| { + ctx.eval_compiled(&math_mod) + })), + ), + ( + "loadWrapper", + HostValue::Function(HostFunction::direct(move |ctx, _| { + ctx.eval_compiled(&wrapper_mod) + })), + ), + ( + "loadDynamic", + HostValue::Function(HostFunction::direct(|ctx, _| { + ctx.eval_module( + "function dynFn() { return 'from-dyn'; }\nfunction dynFail() {\n throw new Error('dyn boom');\n}\nreturn { dynFn, dynFail };", + "dyn.js", + ) + })), + ), + ( + "hostFail", + HostValue::Function(HostFunction::new(move |_args, call| { + *seen_loc.lock().unwrap() = call.location(); + Err(HostError::located("RangeError", "host boom")) + })), + ), + ("sharedBox", HostValue::object([] as [(&str, HostValue); 0])), + ] + }) + }; + + let seen_loc_1 = Arc::new(Mutex::new(None)); + let rt1 = make_runtime(seen_loc_1); + + let (mut sess1, init) = rt1.session( + r#" + const w = loadWrapper(); + const d = loadDynamic(); + let savedErr = null; + try { + w.callVmFail(); + } catch (e) { + savedErr = e; + } + return { + add: (n) => w.math.add(n), + boom: () => w.callBoom(), + vmFail: () => w.callVmFail(), + throwString: () => w.math.throwString(), + hostCall: () => w.callHost(), + rethrowSaved: () => { throw savedErr; }, + dynFail: () => d.dynFail(), + sources: () => [w.wrapperFn.toString(), d.dynFn.toString(), w.math.describeAdd()], + fromDirect: () => sharedBox.directHelper(), + directFail: () => sharedBox.directFail(), + }; + "#, + &ProgramOptions::new(), + ); + init.json().expect("session init"); + + // Also evaluate modules directly via Session::eval_compiled and Session::eval_module. + let helper_mod = rt1 + .compile_module( + "sharedBox.directHelper = function directHelper() { return 'direct-ok'; }; +sharedBox.directFail = function directFail() { + throw new Error('direct-boom'); +}; +return 123;", + "direct_mod.js", + ) + .expect("compile direct_mod.js"); + assert_eq!( + sess1 + .eval_compiled(&helper_mod) + .json() + .expect("eval_compiled"), + serde_json::json!(123) + ); + assert_eq!( + sess1 + .eval_module("return 'inline-mod-ok';", "inline_mod.js") + .json() + .expect("eval_module"), + serde_json::json!("inline-mod-ok") + ); + + let first = sess1 + .call("add", &[Data::from(serde_json::json!(5))]) + .json() + .expect("first add"); + assert_eq!(first["acc"], serde_json::json!(15)); + assert_eq!(first["big"], serde_json::json!("9007199254741008")); + + // Save -> serialize to bytes -> deserialize -> restore into a completely fresh Runtime! + let snap1 = sess1.save().expect("save session 1"); + let bytes1 = to_bytes(&snap1); + let decoded1 = from_bytes(&bytes1).expect("from_bytes 1"); + + let seen_loc_2 = Arc::new(Mutex::new(None)); + let rt2 = make_runtime(seen_loc_2.clone()); + let mut sess2 = rt2 + .restore_session(&decoded1) + .expect("restore_session in fresh Runtime"); + + // 1. State, BigInt consts, RegExp, Map, tagged templates all work after restore. + let second = sess2 + .call("add", &[Data::from(serde_json::json!(7))]) + .json() + .expect("second add after restore"); + assert_eq!( + second, + serde_json::json!({ + "acc": 22, + "big": "9007199254741015", + "tagged": "total=22", + "fromMap": "22", + "rawTemplate": "same=0", + }) + ); + assert_eq!( + sess2.call("fromDirect", &[]).json().expect("directHelper"), + serde_json::json!("direct-ok") + ); + let direct_diag = sess2 + .call("directFail", &[]) + .result + .expect_err("expected directFail after restore"); + assert!( + direct_diag + .message_lossy() + .contains("at directFail (direct_mod.js:3:11)"), + "expected direct_mod.js:3:11 after restore, got: {}", + direct_diag.message_lossy() + ); + + // 2. Function.prototype.toString() works for every restored module. + let sources = sess2.call("sources", &[]).json().expect("sources"); + assert_eq!( + sources[0], + serde_json::json!("function wrapperFn(x) { return x * 2; }") + ); + assert_eq!( + sources[1], + serde_json::json!("function dynFn() { return 'from-dyn'; }") + ); + assert!( + sources[2] + .as_str() + .unwrap() + .starts_with("function add(n) {"), + "unexpected math.add toString: {}", + sources[2] + ); + + // 3. Thrown Error after restore reports exact multi-module file:line:col stack trace. + let boom_diag = sess2 + .call("boom", &[]) + .result + .expect_err("expected boom after restore"); + let boom_msg = boom_diag.message_lossy(); + assert!( + boom_msg.contains("at boom (math.js:18:11)"), + "expected math.js:18:11 after restore, got: {boom_msg}" + ); + assert!( + boom_msg.contains("at callBoom (wrapper.js:3:12)"), + "expected wrapper.js:3:12 after restore, got: {boom_msg}" + ); + assert_eq!(boom_diag.location, Some((18, 11))); + + // 4. VM-thrown TypeError after restore reports math.js + wrapper.js stack & location. + let vm_diag = sess2 + .call("vmFail", &[]) + .result + .expect_err("expected vmFail after restore"); + let vm_msg = vm_diag.message_lossy(); + assert!( + vm_msg.contains("at vmFail (math.js:22:"), + "expected math.js:22 after restore, got: {vm_msg}" + ); + assert!( + vm_msg.contains("at callVmFail (wrapper.js:6:"), + "expected wrapper.js:6 after restore, got: {vm_msg}" + ); + assert_eq!(vm_diag.location.map(|(l, _)| l), Some(22)); + + // 5. Non-Error throw inside restored module reports math.js stack & location. + let str_diag = sess2 + .call("throwString", &[]) + .result + .expect_err("expected string throw after restore"); + let str_msg = str_diag.message_lossy(); + assert!( + str_msg.contains("at throwString (math.js:25:"), + "expected math.js:25 for string throw after restore, got: {str_msg}" + ); + assert_eq!(str_diag.location.map(|(l, _)| l), Some(25)); + + // 6. HostError::located inside restored module reports math.js location & Call::location(). + let host_diag = sess2 + .call("hostCall", &[]) + .result + .expect_err("expected host error after restore"); + assert_eq!(*seen_loc_2.lock().unwrap(), Some((28, 12))); + assert_eq!(host_diag.location, Some((28, 12))); + let host_msg = host_diag.message_lossy(); + assert!( + host_msg.contains("at hostCall (math.js:28:12)"), + "expected math.js:28:12 after restore, got: {host_msg}" + ); + assert!( + host_msg.contains("at callHost (wrapper.js:9:12)"), + "expected wrapper.js:9:12 after restore, got: {host_msg}" + ); + + // 7. Error caught BEFORE save and rethrown AFTER restore keeps its math.js Failure.source & trace. + let saved_diag = sess2 + .call("rethrowSaved", &[]) + .result + .expect_err("expected rethrown saved error"); + let saved_msg = saved_diag.message_lossy(); + assert!( + saved_msg.contains("at vmFail (math.js:22:"), + "expected math.js:22 on rethrown pre-save error, got: {saved_msg}" + ); + assert_eq!(saved_diag.location.map(|(l, _)| l), Some(22)); + + // 8. Dynamically compiled module (dyn.js) also keeps its stack traces after restore. + let dyn_diag = sess2 + .call("dynFail", &[]) + .result + .expect_err("expected dynFail after restore"); + assert!( + dyn_diag + .message_lossy() + .contains("at dynFail (dyn.js:3:11)"), + "expected dyn.js:3:11 after restore, got: {}", + dyn_diag.message_lossy() + ); + + // 9. Second save -> bytes -> restore cycle works identically. + let snap2 = sess2.save().expect("save session 2"); + let bytes2 = to_bytes(&snap2); + let decoded2 = from_bytes(&bytes2).expect("from_bytes 2"); + let rt3 = make_runtime(Arc::new(Mutex::new(None))); + let mut sess3 = rt3 + .restore_session(&decoded2) + .expect("restore_session cycle 2"); + let third = sess3 + .call("add", &[Data::from(serde_json::json!(8))]) + .json() + .expect("third add after second restore"); + assert_eq!(third["acc"], serde_json::json!(30)); + assert_eq!(third["big"], serde_json::json!("9007199254741023")); +} + +#[test] +fn session_save_restore_with_interleaved_array_from_async_and_modules() { + let mod_a = Runtime::make() + .compile_module( + "function fnA() { return 'A'; }\nfunction errA() { throw new Error('err-a'); }\nreturn { fnA, errA };", + "mod_a.js", + ) + .expect("compile mod_a"); + let mod_b = Runtime::make() + .compile_module( + "function fnB() { return 'B'; }\nfunction errB() { throw new Error('err-b'); }\nreturn { fnB, errB };", + "mod_b.js", + ) + .expect("compile mod_b"); + + let make_rt = || { + let a = mod_a.clone(); + let b = mod_b.clone(); + Runtime::make().globals(move |_| { + let a = a.clone(); + let b = b.clone(); + vec![ + ( + "loadA", + HostValue::Function(HostFunction::direct(move |ctx, _| ctx.eval_compiled(&a))), + ), + ( + "loadB", + HostValue::Function(HostFunction::direct(move |ctx, _| ctx.eval_compiled(&b))), + ), + ] + }) + }; + + let rt1 = make_rt(); + let (sess1, init) = rt1.session( + r#" + const a = loadA(); + const mid = await Array.fromAsync([1, 2, 3], (x) => x * 10); + const b = loadB(); + return { + check: async () => ({ + a: a.fnA(), + mid, + b: b.fnB(), + again: await Array.fromAsync([4, 5]), + }), + errA: () => a.errA(), + errB: () => b.errB(), + }; + "#, + &ProgramOptions::new(), + ); + init.json().expect("init interleaved"); + + let snap = sess1.save().expect("save interleaved"); + let bytes = to_bytes(&snap); + let decoded = from_bytes(&bytes).expect("from_bytes interleaved"); + + let rt2 = make_rt(); + let mut sess2 = rt2.restore_session(&decoded).expect("restore interleaved"); + + let out = sess2.call("check", &[]).json().expect("check restored"); + assert_eq!( + out, + serde_json::json!({ + "a": "A", + "mid": [10, 20, 30], + "b": "B", + "again": [4, 5], + }) + ); + let e_a = sess2.call("errA", &[]).result.expect_err("errA"); + assert!( + e_a.message_lossy().contains("mod_a.js:2:"), + "expected mod_a.js:2, got: {}", + e_a.message_lossy() + ); + let e_b = sess2.call("errB", &[]).result.expect_err("errB"); + assert!( + e_b.message_lossy().contains("mod_b.js:2:"), + "expected mod_b.js:2, got: {}", + e_b.message_lossy() + ); +} + +#[test] +fn program_with_loaded_module_suspends_and_resumes_mid_loop() { + let worker_mod = Runtime::make() + .compile_module( + r#" + function crunch(n) { + let total = 0; + for (let i = 0; i < n; i++) { + total = (total + i * 3) % 1_000_003; + } + return total; + } + return { crunch }; + "#, + "worker.js", + ) + .expect("compile worker.js"); + + let make_rt = || { + let m = worker_mod.clone(); + Runtime::make().globals(move |_| { + let m = m.clone(); + vec![( + "loadWorker", + HostValue::Function(HostFunction::direct(move |ctx, _| ctx.eval_compiled(&m))), + )] + }) + }; + + let code = "const w = loadWorker(); return w.crunch(1_500_000);"; + let expected = make_rt().execute(code).json().expect("baseline run"); + + let rt1 = make_rt(); + let prog = rt1.program(code, &ProgramOptions::new()); + let suspender = prog.suspender(); + let (outcome, answer) = std::thread::scope(|s| { + let h = s.spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(5)); + suspender.suspend(None) + }); + ( + prog.run_resumable().expect("run_resumable"), + h.join().unwrap(), + ) + }); + + let suspended = match outcome { + RunOutcome::Suspended(s) => s, + RunOutcome::Done(o) => { + assert_eq!(o.json().expect("done result"), expected); + return; + } + }; + assert!(matches!( + answer.expect("suspend answer"), + RunOutcome::Suspended(_) + )); + + let bytes = to_bytes(&suspended.state); + let decoded = from_bytes(&bytes).expect("from_bytes"); + let resumed = make_rt().resume(&decoded).expect("resume in fresh runtime"); + let final_outcome = match resumed.run_resumable().expect("run resumed") { + RunOutcome::Done(o) => o, + RunOutcome::Suspended(_) => panic!("unexpected second suspend"), + }; + assert_eq!(final_outcome.json().expect("resumed result"), expected); +} + +#[test] +fn session_eval_compiled_respects_limits_and_roundtrip() { + // 1. Looping module runs cleanly through Session::eval_compiled (including under PSYCHOSCRIPT_ROUNDTRIP=1). + let loop_mod = Runtime::make() + .compile_module( + r#" + let sum = 0; + for (let i = 0; i < 5000; i++) { + sum += i; + } + return sum; + "#, + "loop_mod.js", + ) + .expect("compile loop_mod"); + let (mut sess, init) = Runtime::make().session("return {};", &ProgramOptions::new()); + init.json().expect("init"); + assert_eq!( + sess.eval_compiled(&loop_mod).json().expect("eval loop_mod"), + serde_json::json!(12_497_500) + ); + + // 2. timeout_ms (Wall) stops an infinite loop inside Session::eval_compiled. + let inf_mod = Runtime::make() + .compile_module("while (true) {}", "inf.js") + .expect("compile inf.js"); + let wall_rt = Runtime::make().limits(Limits { + timeout_ms: Some(30), + clock: Clock::Wall, + ..Default::default() + }); + let (mut wall_sess, init) = wall_rt.session("return {};", &ProgramOptions::new()); + init.json().expect("wall init"); + let wall_err = wall_sess + .eval_compiled(&inf_mod) + .result + .expect_err("expected wall timeout"); + assert_eq!(wall_err.kind, DiagnosticKind::TimeoutExceeded); + + // 3. timeout_ms (ThreadCpu) stops an infinite loop inside Session::eval_compiled. + let cpu_rt = Runtime::make().limits(Limits { + timeout_ms: Some(30), + clock: Clock::ThreadCpu, + ..Default::default() + }); + let (mut cpu_sess, init) = cpu_rt.session("return {};", &ProgramOptions::new()); + init.json().expect("cpu init"); + let cpu_err = cpu_sess + .eval_compiled(&inf_mod) + .result + .expect_err("expected cpu timeout"); + assert_eq!(cpu_err.kind, DiagnosticKind::TimeoutExceeded); + + // 4. slice_ms stops a long stretch inside Session::eval_compiled. + let slice_rt = Runtime::make().limits(Limits { + slice_ms: Some(30), + ..Default::default() + }); + let (mut slice_sess, init) = slice_rt.session("return {};", &ProgramOptions::new()); + init.json().expect("slice init"); + let slice_err = slice_sess + .eval_compiled(&inf_mod) + .result + .expect_err("expected slice exceeded"); + assert_eq!(slice_err.kind, DiagnosticKind::SliceExceeded); + + // 5. max_heap_bytes stops runaway allocation inside Session::eval_compiled. + let mem_mod = Runtime::make() + .compile_module( + "const a = []; for (let i = 0; i < 100000; i++) a.push({ x: i, s: 'abcdefghij' + i }); return a.length;", + "mem.js", + ) + .expect("compile mem.js"); + let mem_rt = Runtime::make().limits(Limits { + max_heap_bytes: Some(256 * 1024), + ..Default::default() + }); + let (mut mem_sess, init) = mem_rt.session("return {};", &ProgramOptions::new()); + init.json().expect("mem init"); + let mem_err = mem_sess + .eval_compiled(&mem_mod) + .result + .expect_err("expected memory limit"); + assert_eq!(mem_err.kind, DiagnosticKind::MemoryLimitExceeded); +}