From 814162a5349db88dcaaa46bb18b1d87edba28a8a Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:32:03 +1000 Subject: [PATCH 1/2] feat(rust): add precompiled modules with per-module stacks and opt-in TS stripping --- .../crates/psychoscript/src/builtins/array.rs | 5 +- .../psychoscript/src/builtins/collections.rs | 4 +- .../psychoscript/src/builtins/object.rs | 12 +- rust/crates/psychoscript/src/bytecode.rs | 212 ++++ rust/crates/psychoscript/src/collector.rs | 17 + rust/crates/psychoscript/src/compiler.rs | 627 +++++++++-- rust/crates/psychoscript/src/host.rs | 109 +- rust/crates/psychoscript/src/lib.rs | 4 +- rust/crates/psychoscript/src/native.rs | 2 + rust/crates/psychoscript/src/object.rs | 2 + rust/crates/psychoscript/src/reach.rs | 15 +- rust/crates/psychoscript/src/run.rs | 196 +++- rust/crates/psychoscript/src/runtime.rs | 71 +- rust/crates/psychoscript/src/session.rs | 129 ++- rust/crates/psychoscript/src/snapshot.rs | 67 +- rust/crates/psychoscript/src/stack.rs | 134 ++- rust/crates/psychoscript/src/vm.rs | 250 ++++- .../psychoscript/tests/modules_and_ts.rs | 991 ++++++++++++++++++ 18 files changed, 2652 insertions(+), 195 deletions(-) create mode 100644 rust/crates/psychoscript/tests/modules_and_ts.rs diff --git a/rust/crates/psychoscript/src/builtins/array.rs b/rust/crates/psychoscript/src/builtins/array.rs index 0f3310df..b345006d 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.source.is_none()) + .map_or(Value::Undef, |s| Value::Num(s.offset as f64)); let f = vm.alloc(Obj::new( Some(fp), Kind::Closure(Box::new(Closure { diff --git a/rust/crates/psychoscript/src/builtins/collections.rs b/rust/crates/psychoscript/src/builtins/collections.rs index b875b7d2..d9a4df23 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.clone(); } } diff --git a/rust/crates/psychoscript/src/builtins/object.rs b/rust/crates/psychoscript/src/builtins/object.rs index 055eb38c..f26650ee 100644 --- a/rust/crates/psychoscript/src/builtins/object.rs +++ b/rust/crates/psychoscript/src/builtins/object.rs @@ -1048,11 +1048,15 @@ 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.clone()), + _ => (None, None), + }; + let code: &str = match &source { + Some(src) => &src.code, + None => &vm.code, }; - 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]| code.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..1d00cda7 100644 --- a/rust/crates/psychoscript/src/bytecode.rs +++ b/rust/crates/psychoscript/src/bytecode.rs @@ -291,6 +291,213 @@ 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, +} + +/// A bytecode source site: byte offset plus optional named module source (`None` = `Vm::code`). +#[derive(Clone, Debug)] +pub(crate) struct CallSite { + pub offset: u32, + pub source: Option>, +} + +/// 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 +512,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,6 +532,9 @@ 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]>, + /// Source metadata for functions compiled as a named module; `None` for single-file runs so + /// existing single-file programs incur zero overhead. + pub(crate) source: Option>, } impl FuncProto { diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index b3cdbce7..398c3778 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1157,6 +1157,23 @@ impl Vm { } } + /// Write barrier for values stored into VM root tables (e.g. `Vm::consts`, `Vm::templates`, + /// `Vm::globals`, `Vm::global_map`) while incremental marking is in progress. + #[inline] + pub(crate) fn gc_shade(&mut self, val: Value) { + if self.gc.phase == Phase::Mark { + self.gc_shade_value(val); + } + } + + /// 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 bb3eb3c9..b93719f3 100644 --- a/rust/crates/psychoscript/src/compiler.rs +++ b/rust/crates/psychoscript/src/compiler.rs @@ -17,8 +17,8 @@ use rustc_hash::{FxHashMap, FxHashSet}; use crate::DiagnosticKind; use crate::bytecode::{ - Arith, Capture, FuncProto, ITER_DELEGATE, ITER_DESTRUCTURE, ITER_FOR_AWAIT, ITER_FOR_OF, Op, - Program, TemplateSite, + Arith, Capture, FuncProto, ITER_DELEGATE, ITER_DESTRUCTURE, ITER_FOR_AWAIT, ITER_FOR_OF, + ModuleSource, Op, Program, TemplateSite, }; use crate::bytecode::{CLASS_BASE, CLASS_DERIVED}; use crate::strings::{Atom, Strings}; @@ -39,15 +39,69 @@ const MAX_NESTING: u32 = 2_000; /// (256 KiB); `run::compile` refuses a larger one. pub const DEFAULT_MAX_SOURCE_BYTES: usize = 256 * 1024; +/// Options controlling how source code is parsed and compiled. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CompileOptions { + /// Override erasable TypeScript type-stripping (`None` inherits from + /// [`Runtime::typescript`](crate::Runtime::typescript), which defaults to `false`). + pub typescript: Option, + /// Optional module name attached to compiled functions for `module:line:col` stack traces. + pub module_name: Option, + /// Optional maximum source size in bytes (`None` uses the default 256 KiB limit). + pub max_source_bytes: Option, +} + +impl CompileOptions { + pub fn new() -> Self { + Self::default() + } + + /// Enables or disables erasable TypeScript type-stripping for this compilation. + pub fn typescript(mut self, enabled: bool) -> Self { + self.typescript = Some(enabled); + self + } + + /// Sets the module name shown in stack traces for functions compiled from this source. + pub fn module_name(mut self, name: impl Into) -> Self { + self.module_name = Some(name.into()); + self + } + + /// Sets the maximum source size in bytes accepted for this compilation. + pub fn max_source_bytes(mut self, bytes: usize) -> Self { + self.max_source_bytes = Some(bytes); + self + } +} + +#[cfg(feature = "test262")] pub fn compile(source: &str, atoms: &mut Strings) -> R { - compile_as(source, atoms, false) + compile_as( + source, + atoms, + false, + &CompileOptions::default(), + false, + None, + ) +} + +pub(crate) fn compile_with( + source: &str, + atoms: &mut Strings, + options: &CompileOptions, + sync_module: bool, + module_source: Option>, +) -> R { + compile_as(source, atoms, false, options, sync_module, module_source) } /// 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, &CompileOptions::default(), false, None) } /// The offset of the first token after a class element's leading `static`. @@ -59,7 +113,14 @@ 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, + options: &CompileOptions, + sync_module: bool, + module_source: Option>, +) -> 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 +128,15 @@ 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, + options, + sync_module, + module_source, + ); match arena.capacity() > ARENA_KEEP_BYTES { true => *arena = Allocator::default(), false => arena.reset(), @@ -75,7 +144,15 @@ 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, + options, + sync_module, + module_source, + ), }) } @@ -84,6 +161,9 @@ fn compile_in( source: &str, atoms: &mut Strings, internal: bool, + options: &CompileOptions, + sync_module: bool, + module_source: Option>, ) -> R { if source.trim().is_empty() { return Err(CompileError { @@ -92,18 +172,25 @@ fn compile_in( offset: None, }); } + let typescript = options.typescript.unwrap_or(false); let renamed: String; let mut await_alias = None; - let mut parsed = parse(allocator, source, SourceType::mjs()); + let initial_type = if typescript { + SourceType::ts() + } else { + SourceType::mjs() + }; + let mut parsed = parse(allocator, source, initial_type); // The reference parses a script that allows top-level `await`: `await` is a plain name there, read as the // operator only where an expression starts with it. A program whose first error is naming something `await` is // parsed again as a script, unless it also uses `await` as an expression at the top level; then the names are // renamed for the parse instead, keeping the expressions. - if parsed - .diagnostics - .errors() - .next() - .is_some_and(|d| names_await(source, d)) + if !typescript + && parsed + .diagnostics + .errors() + .next() + .is_some_and(|d| names_await(source, d)) { let script = parse(allocator, source, SourceType::script()); if script.diagnostics.errors().next().is_none() @@ -155,13 +242,24 @@ fn compile_in( } // Parsed as a module for top-level `await`, but bound as a script, like the reference: top-level functions and // `var`s share one scope, so redeclaring one as the other is allowed. - parsed.program.source_type = SourceType::script(); + parsed.program.source_type = if typescript { + SourceType::ts().with_script(true) + } else { + SourceType::script() + }; let program = &parsed.program; - if let Some(export) = program - .body - .iter() - .find(|s| s.is_module_declaration() && !matches!(s, Statement::ImportDeclaration(_))) - { + if typescript && let Some((msg, at)) = find_non_erasable_ts(program) { + return Err(CompileError { + kind: DiagnosticKind::ParseError, + message: format!("SyntaxError: {msg}"), + offset: Some(at), + }); + } + if let Some(export) = program.body.iter().find(|s| { + s.is_module_declaration() + && !matches!(s, Statement::ImportDeclaration(_)) + && !(typescript && is_type_only_module_decl(s)) + }) { return Err(CompileError { kind: DiagnosticKind::ParseError, message: "SyntaxError: Exports aren't available. Return the result instead.".into(), @@ -209,6 +307,9 @@ fn compile_in( let mut c = Compiler::new(scoping, semantic.semantic.nodes(), atoms); c.await_alias = await_alias; c.internal = internal; + c.typescript = typescript; + c.sync_module = sync_module; + c.module_source = module_source; c.source = program.source_text; c.find_unbound(program); c.find_field_values(program); @@ -235,6 +336,173 @@ fn parse<'a>(allocator: &'a Allocator, text: &'a str, source_type: SourceType) - .parse() } +/// Rejects runtime-emitting TypeScript syntax (enums, non-ambient namespaces/modules, constructor +/// parameter properties, non-type `import =`, and `export =`) so only erasable TypeScript passes. +fn find_non_erasable_ts(program: &oxc_ast::ast::Program<'_>) -> Option<(&'static str, u32)> { + struct Check(Option<(&'static str, u32)>); + impl Check { + fn record(&mut self, msg: &'static str, at: u32) { + if self.0.is_none_or(|(_, cur)| at < cur) { + self.0 = Some((msg, at)); + } + } + } + impl<'a> Visit<'a> for Check { + fn visit_class(&mut self, it: &Class<'a>) { + if !it.declare { + walk::walk_class(self, it); + } + } + fn visit_ts_global_declaration(&mut self, _it: &TSGlobalDeclaration<'a>) {} + fn visit_ts_enum_declaration(&mut self, it: &TSEnumDeclaration<'a>) { + if !it.declare { + self.record( + "TypeScript `enum` is not supported; only erasable TypeScript syntax is supported.", + it.span.start, + ); + } + } + fn visit_ts_namespace_declaration(&mut self, it: &TSNamespaceDeclaration<'a>) { + if !it.declare { + self.record( + "TypeScript `namespace` is not supported; only erasable TypeScript syntax is supported.", + it.span.start, + ); + } + } + fn visit_ts_external_module_declaration(&mut self, it: &TSExternalModuleDeclaration<'a>) { + if !it.declare { + self.record( + "TypeScript `module` declaration is not supported; only erasable TypeScript syntax is supported.", + it.span.start, + ); + } + } + fn visit_formal_parameter(&mut self, it: &FormalParameter<'a>) { + if it.accessibility.is_some() || it.readonly || it.r#override { + self.record( + "TypeScript parameter properties are not supported; only erasable TypeScript syntax is supported.", + it.span.start, + ); + } + walk::walk_formal_parameter(self, it); + } + fn visit_ts_import_equals_declaration(&mut self, it: &TSImportEqualsDeclaration<'a>) { + if !it.import_kind.is_type() { + self.record( + "TypeScript `import =` is not supported; only erasable TypeScript syntax is supported.", + it.span.start, + ); + } + } + fn visit_ts_export_assignment(&mut self, it: &TSExportAssignment<'a>) { + self.record( + "TypeScript `export =` is not supported; only erasable TypeScript syntax is supported.", + it.span.start, + ); + } + } + let mut check = Check(None); + check.visit_program(program); + check.0 +} + +fn is_type_only_export_decl(d: &ExportDeclaration<'_>) -> bool { + match &d.declaration { + Declaration::TSTypeAliasDeclaration(_) + | Declaration::TSInterfaceDeclaration(_) + | Declaration::TSGlobalDeclaration(_) => true, + Declaration::VariableDeclaration(v) => v.declare, + Declaration::FunctionDeclaration(f) => f.declare || f.body.is_none(), + Declaration::ClassDeclaration(c) => c.declare, + Declaration::TSNamespaceDeclaration(n) => n.declare, + Declaration::TSExternalModuleDeclaration(m) => m.declare, + Declaration::TSImportEqualsDeclaration(i) => i.import_kind.is_type(), + Declaration::TSEnumDeclaration(e) => e.declare, + } +} + +fn is_type_only_export_named(d: &ExportNamedDeclaration<'_>) -> bool { + // Also allows empty `export {}`, the standard TypeScript module-scoping marker. + d.export_kind.is_type() || d.specifiers.iter().all(|s| s.export_kind.is_type()) +} + +fn is_type_only_export_from(d: &ExportFromDeclaration<'_>) -> bool { + d.export_kind.is_type() + || (!d.specifiers.is_empty() && d.specifiers.iter().all(|s| s.export_kind.is_type())) +} + +fn is_type_only_export_default(d: &ExportDefaultDeclaration<'_>) -> bool { + matches!( + d.declaration, + ExportDefaultDeclarationKind::TSInterfaceDeclaration(_) + ) +} + +fn is_type_only_module_decl(s: &Statement<'_>) -> bool { + match s { + Statement::ExportDeclaration(d) => is_type_only_export_decl(d), + Statement::ExportNamedDeclaration(d) => is_type_only_export_named(d), + Statement::ExportFromDeclaration(d) => is_type_only_export_from(d), + Statement::ExportDefaultDeclaration(d) => is_type_only_export_default(d), + Statement::ExportAllDeclaration(d) => d.export_kind.is_type(), + Statement::TSNamespaceExportDeclaration(_) => true, + _ => false, + } +} + +fn is_erased_class_element(m: &ClassElement<'_>) -> bool { + match m { + ClassElement::TSIndexSignature(_) => true, + ClassElement::PropertyDefinition(p) => { + p.declare || p.r#type == PropertyDefinitionType::TSAbstractPropertyDefinition + } + ClassElement::MethodDefinition(d) => { + d.value.body.is_none() || d.r#type == MethodDefinitionType::TSAbstractMethodDefinition + } + ClassElement::AccessorProperty(a) => { + a.r#type == AccessorPropertyType::TSAbstractAccessorProperty + } + _ => false, + } +} + +/// Unwraps erasable TypeScript expression wrappers (and parens around them) while preserving +/// non-wrapper expressions such as `SequenceExpression` (`(0, o.m)()`). +fn strip_ts_expr<'a>(mut e: &'a Expression<'a>) -> &'a Expression<'a> { + loop { + e = match e { + Expression::ParenthesizedExpression(p) => &p.expression, + Expression::TSAsExpression(x) => &x.expression, + Expression::TSSatisfiesExpression(x) => &x.expression, + Expression::TSNonNullExpression(x) => &x.expression, + Expression::TSTypeAssertion(x) => &x.expression, + Expression::TSInstantiationExpression(x) => &x.expression, + _ => return e, + }; + } +} + +enum ResolvedTarget<'a> { + Ident(&'a IdentifierReference<'a>), + Static(&'a StaticMemberExpression<'a>), + Computed(&'a ComputedMemberExpression<'a>), + Super(&'a MemberExpression<'a>), +} + +fn resolve_expr_target<'a>(e: &'a Expression<'a>) -> Option> { + let e = strip_ts_expr(e); + if let Some(m) = Compiler::super_member(e.as_member_expression()) { + return Some(ResolvedTarget::Super(m)); + } + match e { + Expression::Identifier(id) => Some(ResolvedTarget::Ident(id)), + Expression::StaticMemberExpression(m) => Some(ResolvedTarget::Static(m)), + Expression::ComputedMemberExpression(m) => Some(ResolvedTarget::Computed(m)), + _ => None, + } +} + /// The source with each `await` the reference reads as a name replaced by the returned five-letter identifier, which /// the source does not contain, padded with spaces to keep every offset (an escaped `await` is longer); `await` /// expressions stay. `None` when the module parse fails for another reason. @@ -1276,6 +1544,12 @@ struct Compiler<'a, 's> { last_home: bool, /// Compiling a prelude built-in (see `compile_internal`). internal: bool, + /// Strip erasable TypeScript syntax during compilation. + typescript: bool, + /// Compile top-level program as a synchronous module (`is_async = false; is_program = false`). + sync_module: bool, + /// Optional per-module source metadata attached to every compiled `FuncProto`. + module_source: Option>, /// The text the program was parsed from, which spans index. source: &'a str, } @@ -1321,6 +1595,9 @@ impl<'a, 's> Compiler<'a, 's> { pseudo: 0, last_home: false, internal: false, + typescript: false, + sync_module: false, + module_source: None, source: "", } } @@ -1697,6 +1974,9 @@ impl<'a, 's> Compiler<'a, 's> { let Statement::ImportDeclaration(d) = st else { continue; }; + if self.typescript && d.import_kind.is_type() { + continue; + } if d.import_kind.is_type() || d.phase.is_some() { return Err(unsupported("This form of `import`", d.span)); } @@ -1728,6 +2008,12 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); } for spec in specifiers { + if self.typescript + && let ImportDeclarationSpecifier::ImportSpecifier(x) = spec + && x.import_kind.is_type() + { + continue; + } let (kind, name, local, pos) = match spec { ImportDeclarationSpecifier::ImportDefaultSpecifier(x) => { (0, None, &x.local, x.span.start) @@ -1787,6 +2073,9 @@ impl<'a, 's> Compiler<'a, 's> { fn hoist_functions(&mut self, stmts: &'a [Statement<'a>]) -> R<()> { for st in stmts { if let Statement::FunctionDeclaration(f) = st { + if self.typescript && (f.declare || f.body.is_none()) { + continue; + } self.closure_for_function(f, None)?; let id = f.id.as_ref().and_then(|id| id.symbol_id.get()); match id { @@ -1911,6 +2200,16 @@ impl<'a, 's> Compiler<'a, 's> { self.0.push(it.body.span()); } } + if self.typescript { + for sym in self.scoping.symbol_ids() { + let flags = self.scoping.symbol_flags(sym); + if flags.contains(SymbolFlags::Ambient) + || !flags.intersects(SymbolFlags::Value | SymbolFlags::Import) + { + self.unbound.insert(sym); + } + } + } let mut withs = Withs(Vec::new()); withs.visit_program(program); if withs.0.is_empty() { @@ -2067,7 +2366,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 +2407,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 +2419,7 @@ impl<'a, 's> Compiler<'a, 's> { callees: f.callees, sites: f.sites, text: None, + source: self.module_source.clone(), }, ); // Closure instructions index `protos` assuming the program is not in the list; shift them. @@ -2366,6 +2667,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 +2676,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: self.module_source.clone(), }); Ok(self.protos.len() as u32 - 1) } @@ -2404,6 +2707,7 @@ impl<'a, 's> Compiler<'a, 's> { Statement::EmptyStatement(_) => Ok(()), Statement::DebuggerStatement(d) => self.throw_syntax("DebuggerStatement", d.span), Statement::ExpressionStatement(e) => self.expr_stmt(&e.expression), + Statement::VariableDeclaration(d) if self.typescript && d.declare => Ok(()), Statement::VariableDeclaration(d) => self.var_decl(d), Statement::FunctionDeclaration(_) => Ok(()), Statement::IfStatement(s) => { @@ -2454,6 +2758,7 @@ impl<'a, 's> Compiler<'a, 's> { Statement::LabeledStatement(l) => self.labeled(l), Statement::SwitchStatement(s) => self.switch(s, Vec::new()), Statement::TryStatement(t) => self.try_stmt(t), + Statement::ClassDeclaration(c) if self.typescript && c.declare => Ok(()), Statement::ClassDeclaration(c) => self.class_declaration(c), Statement::WithStatement(w) => self.throw_syntax("WithStatement", w.span), // Bound before the body runs (see `imports`); one below the top level of the program does nothing there, @@ -2467,6 +2772,43 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } + Statement::TSTypeAliasDeclaration(_) + | Statement::TSInterfaceDeclaration(_) + | Statement::TSGlobalDeclaration(_) + | Statement::TSNamespaceExportDeclaration(_) + if self.typescript => + { + Ok(()) + } + Statement::TSEnumDeclaration(d) if self.typescript && d.declare => Ok(()), + Statement::TSNamespaceDeclaration(d) if self.typescript && d.declare => Ok(()), + Statement::TSExternalModuleDeclaration(d) if self.typescript && d.declare => Ok(()), + Statement::TSImportEqualsDeclaration(d) + if self.typescript && d.import_kind.is_type() => + { + Ok(()) + } + Statement::ExportAllDeclaration(d) if self.typescript && d.export_kind.is_type() => { + Ok(()) + } + Statement::ExportDefaultDeclaration(d) + if self.typescript && is_type_only_export_default(d) => + { + Ok(()) + } + Statement::ExportNamedDeclaration(d) + if self.typescript && is_type_only_export_named(d) => + { + Ok(()) + } + Statement::ExportDeclaration(d) if self.typescript && is_type_only_export_decl(d) => { + Ok(()) + } + Statement::ExportFromDeclaration(d) + if self.typescript && is_type_only_export_from(d) => + { + Ok(()) + } // Only reached below the top level: `compile` refuses an export at the top. Statement::ExportAllDeclaration(d) => self.throw_syntax("ExportAllDeclaration", d.span), Statement::ExportDefaultDeclaration(d) => { @@ -2893,6 +3235,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() { @@ -3417,13 +3768,66 @@ impl<'a, 's> Compiler<'a, 's> { } } - fn assign_simple(&mut self, s: &'a SimpleAssignmentTarget<'a>) -> R<()> { + fn resolve_simple_target( + &self, + s: &'a SimpleAssignmentTarget<'a>, + ) -> Option> { if let Some(m) = Self::super_member(s.as_member_expression()) { - return self.super_target(m.object().span()); + return Some(ResolvedTarget::Super(m)); } match s { - SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => self.store_ident(id), - SimpleAssignmentTarget::StaticMemberExpression(m) => { + SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => { + Some(ResolvedTarget::Ident(id)) + } + SimpleAssignmentTarget::StaticMemberExpression(m) => Some(ResolvedTarget::Static(m)), + SimpleAssignmentTarget::ComputedMemberExpression(m) => { + Some(ResolvedTarget::Computed(m)) + } + SimpleAssignmentTarget::TSAsExpression(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + SimpleAssignmentTarget::TSSatisfiesExpression(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + SimpleAssignmentTarget::TSNonNullExpression(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + SimpleAssignmentTarget::TSTypeAssertion(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + _ => None, + } + } + + fn resolve_assign_target(&self, t: &'a AssignmentTarget<'a>) -> Option> { + if let Some(m) = Self::super_member(t.as_member_expression()) { + return Some(ResolvedTarget::Super(m)); + } + match t { + AssignmentTarget::AssignmentTargetIdentifier(id) => Some(ResolvedTarget::Ident(id)), + AssignmentTarget::StaticMemberExpression(m) => Some(ResolvedTarget::Static(m)), + AssignmentTarget::ComputedMemberExpression(m) => Some(ResolvedTarget::Computed(m)), + AssignmentTarget::TSAsExpression(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + AssignmentTarget::TSSatisfiesExpression(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + AssignmentTarget::TSNonNullExpression(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + AssignmentTarget::TSTypeAssertion(x) if self.typescript => { + resolve_expr_target(&x.expression) + } + _ => None, + } + } + + fn assign_simple(&mut self, s: &'a SimpleAssignmentTarget<'a>) -> R<()> { + match self.resolve_simple_target(s) { + Some(ResolvedTarget::Super(m)) => self.super_target(m.object().span()), + Some(ResolvedTarget::Ident(id)) => self.store_ident(id), + Some(ResolvedTarget::Static(m)) => { self.expr(&m.object)?; self.emit(Op::Swap); let a = self.atom(m.property.name.as_str()); @@ -3431,7 +3835,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); Ok(()) } - SimpleAssignmentTarget::ComputedMemberExpression(m) => { + Some(ResolvedTarget::Computed(m)) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -3440,13 +3844,14 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); Ok(()) } - other => Err(unsupported("This assignment target", other.span())), + None => Err(unsupported("This assignment target", s.span())), } } // ---------- expressions ---------- fn expr_named(&mut self, e: &'a Expression<'a>, name: Option<&str>) -> R<()> { + let e = if self.typescript { strip_ts_expr(e) } else { e }; match e { Expression::ClassExpression(c) if c.id.is_none() => { self.pos = c.span.start; @@ -3570,6 +3975,9 @@ impl<'a, 's> Compiler<'a, 's> { self.chains.push(Vec::new()); match &c.expression { ChainElement::CallExpression(call) => self.call(call)?, + ChainElement::TSNonNullExpression(x) if self.typescript => { + self.expr(&x.expression)?; + } other => match other.as_member_expression() { Some(m) => self.expr(m_as_expr(m))?, None => return Err(unsupported("TypeScript syntax", other.span())), @@ -3581,6 +3989,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); } @@ -3636,6 +4053,13 @@ impl<'a, 's> Compiler<'a, 's> { Expression::PrivateInExpression(p) => { return Err(unsupported("Private fields", p.span)); } + Expression::TSAsExpression(x) if self.typescript => self.expr(&x.expression)?, + Expression::TSSatisfiesExpression(x) if self.typescript => self.expr(&x.expression)?, + Expression::TSNonNullExpression(x) if self.typescript => self.expr(&x.expression)?, + Expression::TSTypeAssertion(x) if self.typescript => self.expr(&x.expression)?, + Expression::TSInstantiationExpression(x) if self.typescript => { + self.expr(&x.expression)?; + } other => return Err(unsupported("This syntax", other.span())), } Ok(()) @@ -3686,7 +4110,17 @@ impl<'a, 's> Compiler<'a, 's> { /// `tag\`...\``: calls the tag, read like a callee, with the site's strings array and the substitutions. fn tagged_template(&mut self, t: &'a TaggedTemplateExpression<'a>) -> R<()> { - match &t.tag { + let tag = if self.typescript { + strip_ts_expr(&t.tag) + } else { + &t.tag + }; + match tag { + tag if Self::super_member(tag.as_member_expression()).is_some() => { + if let Some(m) = tag.as_member_expression() { + self.super_get(m, true)?; + } + } Expression::StaticMemberExpression(m) => { self.expr(&m.object)?; let a = self.atom(m.property.name.as_str()); @@ -3881,7 +4315,11 @@ impl<'a, 's> Compiler<'a, 's> { /// `delete`: a member expression deletes, optionally; an identifier fails when it runs, as in the reference; /// anything else is evaluated and gives true. fn delete(&mut self, argument: &'a Expression<'a>) -> R<()> { - let argument = argument.without_parentheses(); + let argument = if self.typescript { + strip_ts_expr(argument) + } else { + argument.without_parentheses() + }; if let Expression::Identifier(id) = argument { let msg = self.str_const("Only data fields may be deleted."); self.pos = id.span.start; @@ -3889,7 +4327,12 @@ impl<'a, 's> Compiler<'a, 's> { return Ok(()); } let member = match argument { - Expression::ChainExpression(c) => c.expression.as_member_expression(), + Expression::ChainExpression(c) => match &c.expression { + ChainElement::TSNonNullExpression(x) if self.typescript => { + strip_ts_expr(&x.expression).as_member_expression() + } + other => other.as_member_expression(), + }, other => other.as_member_expression(), }; let Some(member) = member else { @@ -3971,7 +4414,12 @@ impl<'a, 's> Compiler<'a, 's> { _ => {} } } - match &c.callee { + let callee = if self.typescript { + strip_ts_expr(&c.callee) + } else { + &c.callee + }; + match callee { callee if Self::super_member(callee.as_member_expression()).is_some() => { if let Some(m) = callee.as_member_expression() { self.super_get(m, true)?; @@ -4032,7 +4480,12 @@ impl<'a, 's> Compiler<'a, 's> { fn unary(&mut self, u: &'a UnaryExpression<'a>) -> R<()> { match u.operator { UnaryOperator::Typeof => { - if let Expression::Identifier(id) = &u.argument + let arg = if self.typescript { + strip_ts_expr(&u.argument) + } else { + &u.argument + }; + if let Expression::Identifier(id) = arg && self.ident_symbol(id).is_none() && id.name.as_str() != "undefined" && id.name.as_str() != "arguments" @@ -4070,40 +4523,48 @@ impl<'a, 's> Compiler<'a, 's> { } fn assignment(&mut self, a: &'a AssignmentExpression<'a>) -> R<()> { - if let Some(m) = Self::super_member(a.left.as_member_expression()) { + let op = a.operator; + if op == AssignmentOperator::Assign + && matches!( + a.left, + AssignmentTarget::ArrayAssignmentTarget(_) + | AssignmentTarget::ObjectAssignmentTarget(_) + ) + { + self.expr(&a.right)?; + self.emit(Op::Dup); + return self.assign_target(&a.left); + } + let Some(target) = self.resolve_assign_target(&a.left) else { + return Err(unsupported("This assignment target", a.left.span())); + }; + if let ResolvedTarget::Super(m) = target { return self.super_assign(m, a); } - let op = a.operator; if op == AssignmentOperator::Assign { - match &a.left { - AssignmentTarget::AssignmentTargetIdentifier(id) => { + return match target { + ResolvedTarget::Ident(id) => { self.expr_named(&a.right, Some(id.name.as_str()))?; self.emit(Op::Dup); - return self.store_ident(id); + self.store_ident(id) } - AssignmentTarget::StaticMemberExpression(m) => { + ResolvedTarget::Static(m) => { self.expr(&m.object)?; self.expr(&a.right)?; let at = self.atom(m.property.name.as_str()); self.emit_member(Op::SetProp(at), &m.object, None); - return Ok(()); + Ok(()) } - AssignmentTarget::ComputedMemberExpression(m) => { + ResolvedTarget::Computed(m) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); self.expr(&a.right)?; self.emit_member(Op::SetElem, &m.object, Some(&m.expression)); - return Ok(()); - } - AssignmentTarget::ArrayAssignmentTarget(_) - | AssignmentTarget::ObjectAssignmentTarget(_) => { - self.expr(&a.right)?; - self.emit(Op::Dup); - return self.assign_target(&a.left); + Ok(()) } - other => return Err(unsupported("This assignment target", other.span())), - } + ResolvedTarget::Super(_) => unreachable!(), + }; } let logical = match op { AssignmentOperator::LogicalAnd => Some(Op::JumpIfFalseKeep(0)), @@ -4111,8 +4572,8 @@ impl<'a, 's> Compiler<'a, 's> { AssignmentOperator::LogicalNullish => Some(Op::JumpIfNotNullishKeep(0)), _ => None, }; - match &a.left { - AssignmentTarget::AssignmentTargetIdentifier(id) => { + match target { + ResolvedTarget::Ident(id) => { if let Some(jop) = logical { self.load_ident(id)?; let j = self.emit(jop); @@ -4128,7 +4589,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Dup); self.store_ident(id) } - AssignmentTarget::StaticMemberExpression(m) => { + ResolvedTarget::Static(m) => { let at = self.atom(m.property.name.as_str()); self.expr(&m.object)?; self.emit(Op::Dup); @@ -4149,7 +4610,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit_member(Op::SetProp(at), &m.object, None); Ok(()) } - AssignmentTarget::ComputedMemberExpression(m) => { + ResolvedTarget::Computed(m) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -4172,12 +4633,15 @@ impl<'a, 's> Compiler<'a, 's> { self.emit_member(Op::SetElem, &m.object, Some(&m.expression)); Ok(()) } - other => Err(unsupported("This assignment target", other.span())), + ResolvedTarget::Super(_) => unreachable!(), } } fn update(&mut self, u: &'a UpdateExpression<'a>) -> R<()> { - if let Some(m) = Self::super_member(u.argument.as_member_expression()) { + let Some(target) = self.resolve_simple_target(&u.argument) else { + return Err(unsupported("This update target", u.argument.span())); + }; + if let ResolvedTarget::Super(m) = target { return self.super_update(m, u); } let step = if u.operator == UpdateOperator::Increment { @@ -4185,8 +4649,8 @@ impl<'a, 's> Compiler<'a, 's> { } else { Op::Dec }; - match &u.argument { - SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => { + match target { + ResolvedTarget::Ident(id) => { self.load_ident(id)?; if u.prefix { self.emit(step); @@ -4198,7 +4662,7 @@ impl<'a, 's> Compiler<'a, 's> { } self.store_ident(id) } - SimpleAssignmentTarget::StaticMemberExpression(m) => { + ResolvedTarget::Static(m) => { let at = self.atom(m.property.name.as_str()); self.expr(&m.object)?; self.emit(Op::Dup); @@ -4216,7 +4680,7 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } - SimpleAssignmentTarget::ComputedMemberExpression(m) => { + ResolvedTarget::Computed(m) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -4237,7 +4701,7 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } - other => Err(unsupported("This update target", other.span())), + ResolvedTarget::Super(_) => unreachable!(), } } } @@ -4474,7 +4938,10 @@ impl<'a, 's> Compiler<'a, 's> { struct Fields(Vec); impl<'a> Visit<'a> for Fields { fn visit_property_definition(&mut self, it: &PropertyDefinition<'a>) { - if let Some(v) = &it.value { + if !it.declare + && it.r#type != PropertyDefinitionType::TSAbstractPropertyDefinition + && let Some(v) = &it.value + { self.0.push(v.span()); } walk::walk_property_definition(self, it); @@ -4577,7 +5044,11 @@ impl<'a, 's> Compiler<'a, 's> { } fn class_declaration(&mut self, c: &'a Class<'a>) -> R<()> { - if c.body.body.iter().any(|m| !supported_member(m)) { + if c.body + .body + .iter() + .any(|m| !(self.typescript && is_erased_class_element(m)) && !supported_member(m)) + { return self.compile_class(c, None); } self.compile_class(c, None)?; @@ -4593,7 +5064,12 @@ impl<'a, 's> Compiler<'a, 's> { /// A class definition, which leaves its constructor on the stack (see `classes.rs`). `name` is an anonymous /// class's NamedEvaluation name. fn compile_class(&mut self, c: &'a Class<'a>, name: Option<&str>) -> R<()> { - if let Some(m) = c.body.body.iter().find(|m| !supported_member(m)) { + if let Some(m) = c + .body + .body + .iter() + .find(|m| !(self.typescript && is_erased_class_element(m)) && !supported_member(m)) + { return self.throw_syntax(class_syntax_name(m), m.span()); } let saved_pos = self.pos; @@ -4615,6 +5091,9 @@ impl<'a, 's> Compiler<'a, 's> { }; // A computed field's key is evaluated once, in order, into a binding of its own. for m in &c.body.body { + if self.typescript && is_erased_class_element(m) { + continue; + } if let ClassElement::PropertyDefinition(p) = m && p.computed { @@ -4629,7 +5108,10 @@ impl<'a, 's> Compiler<'a, 's> { self.expr(sc)?; } let ctor = c.body.body.iter().find_map(|m| match m { - ClassElement::MethodDefinition(d) if d.kind == MethodDefinitionKind::Constructor => { + ClassElement::MethodDefinition(d) + if d.kind == MethodDefinitionKind::Constructor + && (!self.typescript || d.value.body.is_some()) => + { Some(d) } _ => None, @@ -4639,7 +5121,11 @@ impl<'a, 's> Compiler<'a, 's> { .body .iter() .filter_map(|m| match m { - ClassElement::PropertyDefinition(p) if !p.r#static => Some(&**p), + ClassElement::PropertyDefinition(p) + if !p.r#static && !(self.typescript && is_erased_class_element(m)) => + { + Some(&**p) + } _ => None, }) .collect(); @@ -4648,7 +5134,11 @@ impl<'a, 's> Compiler<'a, 's> { .body .iter() .filter_map(|m| match m { - ClassElement::PropertyDefinition(p) if p.r#static => Some(&**p), + ClassElement::PropertyDefinition(p) + if p.r#static && !(self.typescript && is_erased_class_element(m)) => + { + Some(&**p) + } _ => None, }) .collect(); @@ -4699,6 +5189,9 @@ impl<'a, 's> Compiler<'a, 's> { let at = heritage.map_or(c.span.start, |s| s.without_parentheses().span().start); self.emit_at(at, Op::Class(derived)); for m in &c.body.body { + if self.typescript && is_erased_class_element(m) { + continue; + } match m { ClassElement::PropertyDefinition(p) if p.computed => { let Some(e) = p.key.as_expression() else { diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 8d0c4210..d92e8548 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>, @@ -593,6 +593,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 { @@ -690,7 +695,7 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) { } Settlement::Lost(message, site) => { let e = vm.type_error(&message); - locate_settled(vm, &e, site, Some(p)); + locate_settled(vm, &e, site.as_ref(), Some(p)); vm.reject(p, e); } Settlement::Host(settled) => { @@ -707,14 +712,14 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) { Ok(v) => vm.fulfill(p, v), Err(e) => { // The reference converts the value at the call, so its errors point there. - locate_settled(vm, &e, site, Some(p)); + locate_settled(vm, &e, site.as_ref(), Some(p)); vm.reject(p, e) } } } Err(HostValue::Interrupt) => interrupt(vm), Err(thrown) => { - let e = thrown_value(vm, &thrown, &label, site, Some(p)); + let e = thrown_value(vm, &thrown, &label, site.as_ref(), Some(p)); vm.reject(p, e); } } @@ -728,7 +733,7 @@ fn thrown_value( vm: &mut Vm, thrown: &HostValue, label: &str, - site: Option, + site: Option<&crate::bytecode::CallSite>, settled: Option, ) -> Value { match thrown { @@ -753,8 +758,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.as_ref(), settled); } e } @@ -762,22 +767,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<&crate::bytecode::CallSite>) { 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<&crate::bytecode::CallSite>, + 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.clone(); + let id = *id; + vm.locate_stack_settled(id, s.offset, s.source.as_deref(), settled); } } @@ -827,8 +837,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.as_ref(), None); } return Err(e); } @@ -944,14 +954,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(); - locate_at(vm, &e, site); + let site = vm.call_location(); + locate_at(vm, &e, site.as_ref()); 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 { @@ -1007,9 +1017,16 @@ 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, + call_site.map(|s| { + let code = s.source.map_or_else(|| vm.code.clone(), |m| m.code.clone()); + (s.offset, code) + }), + ) .with_raw(raw); // Host work, which neither the CPU time nor the stretch under `Limits::slice_ms` counts. let span = vm.host_span(); @@ -1052,21 +1069,28 @@ 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))?; + .inspect_err(|e| locate_at(vm, e, site.as_ref()))?; Ok(if f.thenable { promise_like(vm, v) } else { v }) } Returned::Now(Err(thrown)) => { - let site = vm.call_offset(); - Err(thrown_value(vm, &thrown, &target.label, site, None)) + let site = vm.call_location(); + Err(thrown_value( + vm, + &thrown, + &target.label, + site.as_ref(), + 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_site = site.clone(); let future: BoxFuture<'_, Settlement> = - Box::pin(async move { Settlement::host(work.await, label, owner, site) }); + Box::pin(async move { Settlement::host(work.await, label, owner, future_site) }); let in_flight = InFlight { promise: p, call: call_id, @@ -1231,11 +1255,20 @@ 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, + r.site.as_ref().map(|s| { + let code = s + .source + .as_ref() + .map_or_else(|| vm.code.clone(), |m| m.code.clone()); + (s.offset, code) + }), + ) .with_raw(r.raw.clone()); let home = home_of(vm); let detached = Arc::new(AtomicBool::new(false)); - let (label, owner, site) = (r.label.clone(), r.owner.clone(), r.site); + let (label, owner, site) = (r.label.clone(), r.owner.clone(), r.site.clone()); let (kind, future): (CallKind, BoxFuture<'static, Settlement>) = match f { Callee::Fn(f) => { let Body::Async(body) = &f.body else { @@ -2682,8 +2715,8 @@ 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(); - locate_at(vm, &e, site); + let site = vm.call_location(); + locate_at(vm, &e, site.as_ref()); vm.reject(p, e) } } @@ -2713,7 +2746,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(); - thrown_value(vm, &thrown, &label, site, None) + let site = vm.call_location(); + thrown_value(vm, &thrown, &label, site.as_ref(), None) }) } diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index 1512cdf5..89b4a9c2 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -54,7 +54,7 @@ mod time; mod value; mod vm; -pub use compiler::DEFAULT_MAX_SOURCE_BYTES; +pub use compiler::{CompileOptions, DEFAULT_MAX_SOURCE_BYTES}; pub use convert::MAX_VALUE_DEPTH_LIMIT; pub use data::Data; pub use diagnostic::{Clock, Diagnostic, DiagnosticKind, Interrupted, Limits}; @@ -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..a62ef285 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: None, } } diff --git a/rust/crates/psychoscript/src/object.rs b/rust/crates/psychoscript/src/object.rs index d7b77c25..84aff863 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, + /// Module source `offset` belongs to when raised in a named module (`None` uses `Vm::code`). + pub source: Option>, /// 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 diff --git a/rust/crates/psychoscript/src/reach.rs b/rust/crates/psychoscript/src/reach.rs index 915c36ed..d0229fa9 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.is_some()`) intern atoms after the permanent base, so they live by their + // code without double-billing the run's heap limit. + for p in vm + .protos + .iter() + .filter(|p| p.pos.is_empty() || p.source.is_some()) + { 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..ea555174 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -3,8 +3,8 @@ use std::panic::AssertUnwindSafe; use std::sync::Arc; -use crate::bytecode::Program; -use crate::compiler::{self, CompileError}; +use crate::bytecode::{ModuleSource, Program}; +use crate::compiler::{self, CompileError, CompileOptions}; use crate::convert; use crate::host::{self, RunHost}; use crate::nesting; @@ -45,6 +45,7 @@ struct CompiledProgram { code: Arc, program: Program, atoms: Strings, + typescript: bool, } impl Compiled { @@ -87,13 +88,107 @@ impl<'a> From<&'a Compiled> for Code<'a> { } } -/// 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 { +/// A synchronous named module compiled once off-thread to be merged and executed in any +/// [`Session`](crate::Session) 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 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 with [`CompileOptions`], or returns the compile diagnostic. +pub fn compile_program_with(code: &str, options: &CompileOptions) -> Result { let mut atoms = Strings::fresh(); - let program = - compile(code, &mut atoms, max_source_bytes).map_err(|e| compile_diagnostic(code, e))?; + let code_arc: Arc = Arc::from(code); + let module_source = options.module_name.as_deref().map(|name| { + Arc::new(ModuleSource { + name: Arc::from(name), + code: code_arc.clone(), + }) + }); + let program = compile_with(code, &mut atoms, options, false, module_source) + .map_err(|e| compile_diagnostic(code, e))?; Ok(Compiled(Arc::new(CompiledProgram { + code: code_arc, + program, + atoms, + typescript: options.typescript.unwrap_or(false), + }))) +} + +/// Parses and compiles a synchronous named module once, tagging every function prototype with +/// `ModuleSource { name, code }` and compiling the entry as a synchronous function so `return` +/// produces the module value directly. +pub fn compile_module_with( + code: &str, + name: &str, + options: &CompileOptions, +) -> Result { + compile_module_inner(code, name, options, false) +} + +/// Compiles a synchronous named module while already nested inside a running VM (`native_depth > 0`). +/// On non-wasm targets this compiles on a scoped thread with a fresh stack so deeply nested `require()` +/// chains cannot overflow a small caller stack (e.g. 1 MiB on Windows). +pub(crate) fn compile_module_in_call( + code: &str, + name: &str, + options: &CompileOptions, +) -> Result { + compile_module_inner(code, name, options, true) +} + +fn compile_module_inner( + code: &str, + name: &str, + options: &CompileOptions, + force_off_thread: bool, +) -> Result { + let mut atoms = Strings::fresh(); + let source = Arc::new(ModuleSource { + name: Arc::from(name), code: Arc::from(code), + }); + let program = compile_with_stack( + code, + &mut atoms, + options, + true, + Some(source.clone()), + force_off_thread, + ) + .map_err(|e| compile_diagnostic(code, e))?; + Ok(CompiledModule(Arc::new(CompiledModuleInner { + source, program, atoms, }))) @@ -120,11 +215,37 @@ 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. +#[cfg(test)] pub fn compile( code: &str, atoms: &mut Strings, max_source_bytes: usize, ) -> Result { + let opts = CompileOptions::new().max_source_bytes(max_source_bytes); + compile_with(code, atoms, &opts, false, None) +} + +pub(crate) fn compile_with( + code: &str, + atoms: &mut Strings, + options: &CompileOptions, + sync_module: bool, + module_source: Option>, +) -> Result { + compile_with_stack(code, atoms, options, sync_module, module_source, false) +} + +fn compile_with_stack( + code: &str, + atoms: &mut Strings, + options: &CompileOptions, + sync_module: bool, + module_source: Option>, + force_off_thread: bool, +) -> Result { + let max_source_bytes = options + .max_source_bytes + .unwrap_or(crate::DEFAULT_MAX_SOURCE_BYTES); if code.len() > max_source_bytes { return Err(CompileError { kind: DiagnosticKind::ParseError, @@ -138,8 +259,15 @@ pub fn compile( true => 0, false => nesting::bound(code).saturating_mul(COMPILE_STACK_PER_LEVEL), }; - if need <= RUN_STACK_BUDGET { - return compiler::compile(code, atoms); + #[cfg(target_arch = "wasm32")] + let off_thread = { + let _ = force_off_thread; + need > RUN_STACK_BUDGET + }; + #[cfg(not(target_arch = "wasm32"))] + let off_thread = force_off_thread || need > RUN_STACK_BUDGET; + if !off_thread { + return compiler::compile_with(code, atoms, options, sync_module, module_source); } if need > MAX_COMPILE_LEVELS.saturating_mul(COMPILE_STACK_PER_LEVEL) { return Err(CompileError { @@ -159,10 +287,13 @@ 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, || { + compiler::compile_with(code, atoms, options, sync_module, module_source) + }) .map_err(|_| CompileError { kind: DiagnosticKind::ExecutionFailure, message: @@ -207,21 +338,30 @@ pub fn start( code: Code<'_>, options: &ProgramOptions, ) -> Result, Box> { - let (code, mut program, atoms) = match code { - Code::Compiled(c) => (c.0.code.clone(), c.0.program.clone(), c.0.atoms.clone()), + let setup = rt.setup(); + let (code, mut program, atoms, typescript) = match code { + Code::Compiled(c) => ( + c.0.code.clone(), + c.0.program.clone(), + c.0.atoms.clone(), + c.0.typescript || setup.typescript, + ), Code::Source(code) => { let mut atoms = Strings::fresh(); - match compile(code, &mut atoms, rt.setup().limits.source_limit()) { - Ok(p) => (Arc::from(code), p, atoms), + let opts = CompileOptions::new() + .typescript(setup.typescript) + .max_source_bytes(setup.limits.source_limit()); + match compile_with(code, &mut atoms, &opts, false, None) { + Ok(p) => (Arc::from(code), p, atoms, setup.typescript), Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))), } } }; - let setup = rt.setup(); let run = Run::new(options.run_id.clone(), Data::Null); let globals = setup.globals_for(&run); let host = RunHost::new(globals, setup.modules.clone(), setup.translate, run); let mut vm = Vm::new(host, setup.limits, atoms); + vm.typescript = typescript; vm.start_cpu_meter(); vm.setup(); crate::builtins::ensure_program(&mut vm, &program); @@ -256,9 +396,13 @@ pub fn start_for_resume( restored: crate::snapshot::Restored, ) -> Result { let code = restored.code; + let typescript = restored.typescript; let mut atoms = Strings::fresh(); // The run that saved the state accepted its source: it compiles again whatever its size. - let mut program = compile(&code, &mut atoms, code.len()).map_err(|_| { + let opts = CompileOptions::new() + .typescript(typescript) + .max_source_bytes(code.len()); + let mut program = compile_with(&code, &mut atoms, &opts, false, None).map_err(|_| { crate::snapshot::SnapshotError::new( "Source main does not compile in this build, so it can't resume.", ) @@ -274,6 +418,7 @@ pub fn start_for_resume( } let host = RunHost::new(globals, setup.modules.clone(), setup.translate, run); let mut vm = Vm::new(host, restored.limits, atoms); + vm.typescript = typescript; vm.start_cpu_meter(); vm.setup(); crate::builtins::ensure_program(&mut vm, &program); @@ -477,8 +622,18 @@ 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 src_code: &str = match &f.source { + Some(src) => &src.code, + None => code, + }; + let location = f.offset.map(|o| line_col(src_code, o)); + let trace = f + .trace + .clone() + .unwrap_or_else(|| match (&f.source, location) { + (Some(src), Some((line, col))) => format!("\n at {}:{line}:{col}", src.name), + _ => frame_line(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}"), @@ -667,8 +822,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..7e587596 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, CompileOptions, 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. @@ -223,6 +223,7 @@ pub(crate) struct Setup { pub locale: Option>, pub measure_heap: bool, pub offload: bool, + pub typescript: bool, } impl Default for Setup { @@ -236,6 +237,7 @@ impl Default for Setup { locale: None, measure_heap: false, offload: true, + typescript: false, } } } @@ -370,6 +372,18 @@ impl Runtime { self } + /// Enables or disables opt-in erasable TypeScript type-stripping (default: `false`). + /// + /// When enabled, `execute`, `session`, `compile`, `compile_with` (unless overridden), + /// `compile_module`, `compile_module_with` (unless overridden), and `eval_module` accept + /// erasable TypeScript syntax and strip type-only constructs at compile time. Note that + /// TypeScript grammar changes the parse of ambiguous JavaScript expressions such as + /// `f(a < b, c > (d))` (parsed as generic type arguments in TypeScript). + pub fn typescript(mut self, enabled: bool) -> Self { + Arc::make_mut(&mut self.setup).typescript = enabled; + self + } + /// Parses, compiles and runs `code` on the calling thread, blocking on asynchronous host work. An interrupted /// run ends with an `ExecutionFailure` saying so; [`Program::run`] tells the two apart. pub fn execute<'c>(&self, code: impl Into>) -> Outcome { @@ -419,7 +433,58 @@ impl Runtime { /// without doing it again; or the diagnostic a run of it would fail with first (an empty program, a syntax /// error). Unsupported syntax still fails where it runs, as from source. A compiled program runs in any runtime. pub fn compile(&self, code: &str) -> Result { - crate::run::compile_program(code, self.setup.limits.source_limit()) + let opts = CompileOptions::new() + .typescript(self.setup.typescript) + .max_source_bytes(self.setup.limits.source_limit()); + crate::run::compile_program_with(code, &opts) + } + + /// Parses and compiles a program once with explicit [`CompileOptions`] (e.g. a module name for + /// stack traces, opt-in TypeScript stripping, or a custom source size limit). When + /// `options.typescript` or `options.max_source_bytes` is `None`, it inherits from this + /// runtime's configuration. + pub fn compile_with( + &self, + code: &str, + options: &CompileOptions, + ) -> Result { + let mut resolved = options.clone(); + if resolved.typescript.is_none() { + resolved.typescript = Some(self.setup.typescript); + } + if resolved.max_source_bytes.is_none() { + resolved.max_source_bytes = Some(self.setup.limits.source_limit()); + } + crate::run::compile_program_with(code, &resolved) + } + + /// Parses and compiles a synchronous named module once off-thread 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). + pub fn compile_module(&self, source: &str, name: &str) -> Result { + let opts = CompileOptions::new() + .typescript(self.setup.typescript) + .max_source_bytes(self.setup.limits.source_limit()); + crate::run::compile_module_with(source, name, &opts) + } + + /// [`Runtime::compile_module`] with explicit [`CompileOptions`]. When `options.typescript` or + /// `options.max_source_bytes` is `None`, it inherits from this runtime's configuration. + pub fn compile_module_with( + &self, + source: &str, + name: &str, + options: &CompileOptions, + ) -> Result { + let mut resolved = options.clone(); + if resolved.typescript.is_none() { + resolved.typescript = Some(self.setup.typescript); + } + if resolved.max_source_bytes.is_none() { + resolved.max_source_bytes = Some(self.setup.limits.source_limit()); + } + crate::run::compile_module_with(source, name, &resolved) } /// A program continuing a suspended run, from its state. It keeps the limits it was saved with, and its globals diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs index 35c7ead7..552f910c 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, CompileOptions, 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,47 @@ 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. + /// + /// 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 and executes it in this session. + pub fn eval_module(&mut self, source: &str, name: &str) -> Outcome { + if let Some(vm) = self.program.session_vm() + && vm.fatal.is_some() + { + return self.program.drive_session(|_| {}); + } + let (typescript, max_source_bytes) = self + .program + .session_vm() + .map(|vm| (vm.typescript, vm.limits.source_limit())) + .unwrap_or((false, crate::DEFAULT_MAX_SOURCE_BYTES)); + let opts = CompileOptions::new() + .typescript(typescript) + .max_source_bytes(max_source_bytes); + match crate::run::compile_module_with(source, name, &opts) { + Ok(compiled) => self.eval_compiled(&compiled), + Err(diag) => Outcome { + result: Err(diag), + warnings: Vec::new(), + logs: Vec::new(), + truncated: false, + metadata: self + .program + .session_vm() + .map(|vm| vm.host.run.metadata()) + .unwrap_or(Data::Null), + }, + } + } + /// 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 +179,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 +502,41 @@ 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. + /// + /// 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 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 opts = CompileOptions::new() + .typescript(self.vm.typescript) + .max_source_bytes(self.vm.limits.source_limit()); + let compiled = crate::run::compile_module_in_call(source, name, &opts); + let compiled = match compiled { + Ok(c) => c, + Err(d) => { + let raw = d.message_lossy(); + let msg = raw.strip_prefix("SyntaxError: ").unwrap_or(&raw); + return Err(Val::of(self.vm.syntax_error(msg))); + } + }; + 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 a9eb1933..f05c279a 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -564,9 +564,17 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { let state = enc.state(c).map_err(|e| Refusal::Other(e.message))?; let base = vm.snapshot_base; // The run accepted its source when it started: it compiles again whatever its size. - let fresh = &mut crate::strings::Strings::fresh(); - let program = - crate::run::compile(c.code, fresh, c.code.len()).map_err(|e| Refusal::Other(e.message))?; + let opts = crate::CompileOptions::new() + .typescript(vm.typescript) + .max_source_bytes(c.code.len()); + let program = crate::run::compile_with( + c.code, + &mut crate::strings::Strings::fresh(), + &opts, + false, + None, + ) + .map_err(|e| Refusal::Other(e.message))?; let limits = *vm.limits; // Deep metadata is saved flat: as plain JSON, it would pass the nesting limit of the JSON reader in `from_bytes`. let (metadata, metadata_data) = vm.host.run.update_metadata(|m| { @@ -615,6 +623,9 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { if let Some(n) = limits.max_value_depth { header["limits"]["maxValueDepth"] = json!(n); } + if vm.typescript { + header["source"]["typescript"] = json!(true); + } Ok(Snapshot( json!({ "format": FORMAT, "header": header, "state": state }), )) @@ -757,7 +768,7 @@ impl Enc<'_> { call.path.as_deref().map(texts), args, call.owner, - call.site + call.site.as_ref().map(|s| s.offset) ]); // A tag's raw strings, only for a call that has them. if let (Some(raw), J::Array(entry)) = (&call.raw, &mut entry) { @@ -1028,7 +1039,9 @@ 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, site.as_ref().map(|s| s.offset)]) + } Settlement::Host(h) => { let Settled { result, @@ -1053,9 +1066,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, site.as_ref().map(|s| s.offset)])); } - json!([p, "host", ok, label, owner, hooked, host_value(data), site]) + json!([ + p, + "host", + ok, + label, + owner, + hooked, + host_value(data), + site.as_ref().map(|s| s.offset) + ]) } Settlement::Interrupted => json!([p, "interrupted"]), }) @@ -1156,7 +1178,10 @@ fn hex_bytes(s: &str) -> R> { /// Each object of a fresh run's base, encoded, to see which ones the run changed. fn baseline(vm: &Vm, code: &str) -> R> { let mut atoms = crate::strings::Strings::fresh(); - let program = crate::run::compile(code, &mut atoms, code.len()) + let opts = crate::CompileOptions::new() + .typescript(vm.typescript) + .max_source_bytes(code.len()); + let program = crate::run::compile_with(code, &mut atoms, &opts, false, None) .map_err(|e| SnapshotError::new(e.message))?; let h = &vm.host; let host = host::RunHost::new( @@ -2270,6 +2295,7 @@ impl Dec<'_> { kind: kind_named(&string(at(e, 0)?)?)?, message: string(at(e, 1)?)?, offset: opt_u32(at(e, 2)?)?, + source: None, site: Default::default(), host: e.get(3).is_some_and(|h| h == &J::Bool(true)), trace: trace_from(e.get(4))?, @@ -2519,6 +2545,7 @@ fn pairs(j: &J) -> R> { /// A saved state, checked against this runtime and ready to resume. pub struct Restored { pub code: String, + pub typescript: bool, pub run_id: Option, pub metadata: crate::Data, /// The shape of the host globals it was saved with (`hosts_id`). @@ -2560,6 +2587,10 @@ pub fn header(snapshot: &Snapshot) -> R { }; Ok(Restored { code, + typescript: source + .get("typescript") + .and_then(J::as_bool) + .unwrap_or(false), run_id: field(header, "runId")?.as_str().map(str::to_owned), metadata: match header.get("metadataData") { Some(saved) if !saved.is_null() => data_from(saved)?, @@ -2858,7 +2889,13 @@ 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 = j + .get(7) + .and_then(J::as_u64) + .map(|s| crate::bytecode::CallSite { + offset: s as u32, + source: None, + }); // 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)?; @@ -2869,7 +2906,12 @@ fn restore_settlement(vm: &mut Vm, dec: &Dec, j: &J) -> R<(Id, Settlement)> { } Some("lost") => Settlement::Lost( string(at(j, 2)?)?, - j.get(3).and_then(J::as_u64).map(|s| s as u32), + j.get(3) + .and_then(J::as_u64) + .map(|s| crate::bytecode::CallSite { + offset: s as u32, + source: None, + }), ), Some("interrupted") => Settlement::Interrupted, _ => return Err(invalid("a settlement is unknown.")), @@ -3004,7 +3046,10 @@ 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: at(c, 7)?.as_u64().map(|s| crate::bytecode::CallSite { + offset: s as u32, + source: None, + }), 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..fe5e0eeb 100644 --- a/rust/crates/psychoscript/src/stack.rs +++ b/rust/crates/psychoscript/src/stack.rs @@ -3,6 +3,7 @@ //! access, so a subclass constructor that sets `this.name` is in the header). Until then the property holds the lines //! alone and has `PENDING_STACK` among its flags; any read formats it (`Vm::fix_stack`), a write replaces it. +use crate::bytecode::ModuleSource; use crate::object::*; use crate::value::{Id, Value}; use crate::vm::{FrameKind, Vm}; @@ -25,20 +26,33 @@ pub(crate) fn same_value(a: &Value, b: &Value) -> bool { } } +fn same_source(a: Option<&ModuleSource>, b: Option<&ModuleSource>) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => std::ptr::eq(x, y), + _ => false, + } +} + impl Vm { /// The program frames on the stack as `stack` lines, innermost first: a function's by its `name` (or /// ``), the program's own without one, each at the site it is at. Native frames are left out, and with /// `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, None, 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: Option<&ModuleSource>, + settled: Option, + ) -> String { let mut trace = String::new(); let mut shown = 0; // The coroutine whose promise the async walk follows. @@ -52,11 +66,13 @@ impl Vm { let f = &self.frames[i]; let site = self.frame_site(f); let Some(site) = site else { continue }; + let source = f.func.source.clone(); if shown == 0 && let Some(top) = top - && !self.frame_encloses(i, top) + && (!same_source(source.as_deref(), 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 +80,12 @@ 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.as_deref(), + )); shown += 1; } root = match self.frames.first().map(|f| &f.kind) { @@ -75,11 +96,17 @@ impl Vm { Some(p) => { if let (Some(top), Some(c)) = (top, self.awaiter(p)) && let Some((func, pc, callee)) = self.parked_frame(c) + && same_source(func.source.as_deref(), top_source) && func.pos.get(pc.wrapping_sub(2)) == Some(&top) { - if self.in_program(top) { + if func.source.is_some() || 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.as_deref(), + )); shown += 1; } root = Some(c); @@ -98,15 +125,20 @@ impl Vm { break; }; if let Some(&site) = func.pos.get(pc.wrapping_sub(1)) - && self.in_program(site) + && (func.source.is_some() || 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.as_deref(), + )); 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 +150,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.is_some() || 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 +167,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 +180,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 +228,30 @@ 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: Option<&ModuleSource>, + ) -> 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: Option<&ModuleSource>, + ) -> String { + let (file, code): (&str, &str) = match source { + Some(src) => (&src.name, &src.code), + None => ("", &self.code), + }; + let (line, column) = crate::run::line_col(code, offset); let at = if awaiting { "async " } else { "" }; match name { Some(n) => { @@ -216,9 +263,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 +278,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: Option<&std::sync::Arc>, + settled: Option, + ) { + let line = self.stack_trace_at(Some(offset), source.map(|s| s.as_ref()), settled); if let Kind::Error(Some(f)) = &mut self.heap[id as usize].kind { f.offset = Some(offset); + f.source = source.cloned(); f.trace = Some(line.clone()); } let sk = self.names.stack; @@ -250,8 +304,9 @@ impl Vm { /// A value that is not an Error gets the program's stack there; an Error made with no `stack` lines (a host's) /// gets them as its `stack`. pub(crate) fn see_thrown(&mut self, e: Value) { + let site = self.call_location(); if !matches!(self.thrown.as_deref(), Some((v, _)) if same_value(v, &e)) { - let offset = self.call_offset(); + let offset = site.as_ref().map(|s| s.offset); self.thrown = Some(Box::new(( e, crate::object::Thrown { @@ -264,14 +319,18 @@ impl Vm { return; }; let Some(offset) = t.offset else { return }; + let source = site + .as_ref() + .filter(|s| s.offset == offset) + .and_then(|s| s.source.clone()); 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.as_deref()); } } _ if t.trace.is_none() => { - let trace = self.stack_trace_at(Some(offset), None); + let trace = self.stack_trace_at(Some(offset), source.as_deref(), None); if let Some((_, t)) = self.thrown.as_deref_mut() { t.trace = Some(trace); } @@ -304,12 +363,12 @@ impl Vm { && f.offset.is_none() { if f.host { - self.host_failure_stack(id, o, Some(p)); + self.host_failure_stack(id, o, None, Some(p)); } else { if let Kind::Error(Some(f)) = &mut self.heap[id as usize].kind { f.offset = Some(o); } - self.locate_stack_settled(id, o, Some(p)); + self.locate_stack_settled(id, o, None, Some(p)); } } self.take_thrown(e).unwrap_or(crate::object::Thrown { @@ -343,22 +402,31 @@ impl Vm { return; } let f = &self.frames[fi]; + let source = f.func.source.clone(); 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.as_deref())) + .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: Option<&ModuleSource>) { + 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: Option<&ModuleSource>, + 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 +438,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 da8f790b..83dd8e06 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -368,6 +368,8 @@ 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>, + /// Whether this VM's runtime enables opt-in erasable TypeScript type-stripping for `eval_module`. + pub(crate) typescript: bool, } impl Vm { @@ -516,6 +518,7 @@ impl Vm { slice: None, console: None, session: None, + typescript: false, } } @@ -546,6 +549,206 @@ impl Vm { } } + /// 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. `Session::set_global("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); + self.gc_shade(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), Some(const_base), Some(global_base), Some(template_base)) = ( + u32::try_from(self.protos.len()).ok(), + u32::try_from(self.consts.len()).ok(), + u32::try_from(self.globals.len()).ok(), + u32::try_from(self.templates.len()).ok(), + ) else { + return Err(self.range_error("Module exceeds VM bytecode table capacity.")); + }; + let fits = u32::try_from(program.protos.len()) + .ok() + .and_then(|n| proto_base.checked_add(n)) + .is_some() + && u32::try_from(program.consts.len()) + .ok() + .and_then(|n| const_base.checked_add(n)) + .is_some() + && u32::try_from(program.globals.len()) + .ok() + .and_then(|n| global_base.checked_add(n)) + .is_some() + && u32::try_from(program.templates.len()) + .ok() + .and_then(|n| template_base.checked_add(n)) + .is_some(); + if !fits { + return Err(self.range_error("Module exceeds VM bytecode table capacity.")); + } + if self.atoms.bufs.len() >= MAX_STRINGS { + self.strings_full(); + if self.fatal.is_some() { + return Err(Value::Undef); + } + } + + // 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 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 vm.atoms.bufs.len() >= MAX_STRINGS { + vm.strings_full(); + } + let mapped = vm.atoms.intern(module_atoms.text(a)); + vm.gc_shade_atom(mapped); + atom_cache.insert(a, mapped); + mapped + }; + + // Append remapped constants and materialize BigInt constants. + 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()); + self.gc_shade(sv); + sv + } + other => other, + }; + self.consts.push(mapped); + } + for (i, n) in &program.bigints { + let bv = self.big_val(n.clone()); + self.gc_shade(bv); + self.consts[(const_base + *i) as usize] = bv; + } + + // 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()); + self.gc_shade(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()); + self.gc_shade(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 = self + .global_map + .get(&mapped) + .copied() + .unwrap_or(Value::Uninit); + self.gc_shade(v); + self.gc_shade_atom(mapped); + self.global_names.push(mapped); + self.globals.push(v); + } + + // 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); + 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 Err(self.range_error("Module exceeds VM bytecode table capacity.")); + } + } + self.protos.push(Arc::new(p)); + } + + if self.fatal.is_some() { + return Err(Value::Undef); + } + Ok(proto_base as usize) + } + // ---------- allocation ---------- #[inline] @@ -749,6 +952,7 @@ impl Vm { kind, message: msg.to_owned(), offset: None, + source: None, site: Default::default(), host: false, trace: None, @@ -1172,6 +1376,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 } @@ -1937,16 +2145,30 @@ impl Vm { /// The source offset of that call, where an error about what it returns points. pub(crate) fn call_offset(&self) -> Option { - let own = self + self.call_location().map(|s| s.offset) + } + + 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 frame.func.source.is_some() { + return Some(crate::bytecode::CallSite { + offset, + source: frame.func.source.clone(), + }); + } + let offset = match self.program { + Some(_) if !self.in_program(offset) => self.program_site().unwrap_or(offset), + _ => offset, + }; + Some(crate::bytecode::CallSite { + offset, + source: None, + }) } /// Whether `offset` is in the program's own lines (`Runtime::program_lines`; every offset without them). @@ -1960,7 +2182,7 @@ impl Vm { self.frames .iter() .rev() - .filter(|f| !matches!(f.kind, FrameKind::Native(..))) + .filter(|f| !matches!(f.kind, FrameKind::Native(..)) && f.func.source.is_none()) .filter_map(|f| f.func.pos.get(f.pc.wrapping_sub(1)).copied()) .find(|&o| self.in_program(o)) } @@ -2112,17 +2334,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.is_none() && 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), None, None)); self.heap[id as usize].kind = Kind::Error(Some(Box::new(Failure { kind: DiagnosticKind::ExecutionFailure, message, offset: Some(p), + source: None, site: Default::default(), host: false, trace, @@ -2142,6 +2366,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.clone(); + } // 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() @@ -2157,9 +2384,11 @@ impl Vm { && let Kind::Error(Some(f)) = &mut self.heap[*id as usize].kind { f.offset = Some(o as u32); + f.source = None; } // 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.is_none() && let Some(o) = f.offset && !self.in_program(o) && let Some(p) = self.program_site() @@ -2172,7 +2401,8 @@ impl Vm { }; if let Some(o) = f.offset { let id = *id; - self.locate_stack(id, o); + let source = f.source.clone(); + self.locate_stack(id, o, source.as_deref()); } } } diff --git a/rust/crates/psychoscript/tests/modules_and_ts.rs b/rust/crates/psychoscript/tests/modules_and_ts.rs new file mode 100644 index 00000000..93accfff --- /dev/null +++ b/rust/crates/psychoscript/tests/modules_and_ts.rs @@ -0,0 +1,991 @@ +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use psychoscript::{ + CompileOptions, CompiledModule, Data, DiagnosticKind, HostError, HostFunction, HostValue, + ProgramOptions, RunOutcome, Runtime, Val, 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_with(init_src, &CompileOptions::new().module_name("init.js")) + .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 init.js 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 (init.js:4:9)"), + "missing init 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. + 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}"); + + // 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_size_options() { + 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"); + + // Repeated calls run gc_idle() between turns and incremental GC during churn, verifying + // dynamically loaded module atoms and constants remain rooted. + for _ in 0..3 { + let v = sess + .call("churnAndRead", &[]) + .json() + .expect("call after GC"); + assert_eq!(v, serde_json::json!("hello-dynamic-gc")); + } + + // Session::eval_module convenience helper works directly and returns ParseError on bad syntax + // without poisoning the session. + 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); + // Session remains healthy after a compile error in eval_module. + assert_eq!( + sess.call("churnAndRead", &[]) + .json() + .expect("session still healthy"), + serde_json::json!("hello-dynamic-gc") + ); + + // Synchronous module rejects top-level await cleanly. + 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); + + // Default 256 KiB source size cap stays intact, while CompileOptions::max_source_bytes overrides it. + let huge = format!( + "const pad = '{}'; return pad.length;", + "a".repeat(260 * 1024) + ); + let too_big = rt + .compile(&huge) + .expect_err("default 256 KiB cap must reject >256 KiB source"); + assert_eq!(too_big.kind, DiagnosticKind::ParseError); + + let ok_compiled = rt + .compile_with(&huge, &CompileOptions::new().max_source_bytes(512 * 1024)) + .expect("custom max_source_bytes should accept >256 KiB source"); + let outcome = rt.execute(&ok_compiled); + assert_eq!( + outcome.json().expect("run large compiled"), + serde_json::json!(260 * 1024) + ); +} + +#[test] +fn opt_in_typescript_stripping_works_and_default_js_mode_rejects_ts() { + // 1. Default Runtime (typescript: false) still rejects TypeScript syntax. + let js_rt = Runtime::make(); + for snippet in [ + "const x: number = 1; return x;", + "type Foo = number; return 1;", + "interface Bar { a: string } return 1;", + "const v = 1 as number; return v;", + ] { + let res = js_rt.compile(snippet); + assert!( + res.is_err(), + "typescript: false should reject TS syntax: {snippet}" + ); + assert_eq!(res.unwrap_err().kind, DiagnosticKind::ParseError); + } + + // 2. Opt-in TypeScript runtime strips erasable TS syntax cleanly. + let ts_rt = Runtime::make() + .typescript(true) + .globals(|_| vec![("hostBase", HostValue::Number(100.0))]); + + let ts_program = r#" + import type { Ghost } from "ghost-types"; + export type LocalId = string | number; + export interface Boxed { + value: T; + } + export type * from "ghost-types"; + + declare const hostBase: number; + declare function unusedAmbient(x: number): void; + declare class AmbientOnly { x: number } + + type Pair = { first: A; second: B }; + interface Named { name: string } + + function add(a: number, b: number): number; + function add(a: string, b: string): string; + function add(a: any, b: any): any { + return a + b; + } + + function withThis(this: { n: number }, delta?: number): number { + return this.n + (delta ?? 1); + } + + const identity = (x: T): T => x; + const numIdentity = identity; + + class Counter implements Boxed { + [key: string]: any; + declare ghostField: string; + readonly value: T; + private step: number = 2; + + constructor(initial: T); + constructor(initial: T) { + this.value = initial; + } + + inc(times?: number): number; + inc(times: number = 1): number { + return (this.value as number) + this.step * times; + } + } + + const pair = { first: hostBase, second: 23 } satisfies Pair; + const maybeStr: string | null = "hello"; + const len = maybeStr!.length; + const castVal = 7; + const box = { n: 10 }; + const holder: { x?: number } = {}; + holder.x! = 9; + const counter = new Counter(5); + + return { + sum: add(pair.first, pair.second), + concat: add("a", "b"), + thisRes: withThis.call(box, 4), + idRes: numIdentity(42), + len, + castVal, + assigned: holder.x, + counterInc: counter.inc(3), + }; + "#; + + let outcome = ts_rt.execute(ts_program); + let val = outcome.json().expect("TS program should execute"); + assert_eq!( + val, + serde_json::json!({ + "sum": 123, + "concat": "ab", + "thisRes": 14, + "idRes": 42, + "len": 5, + "castVal": 7, + "assigned": 9, + "counterInc": 11, + }) + ); + + // 3. TypeScript precompiled module with accurate .ts stack traces. + let ts_mod = ts_rt + .compile_module( + r#" +type Input = { x: number }; +function compute(v: Input): number { + throw new Error("ts boom: " + v.x); +} +return { compute }; +"#, + "math.ts", + ) + .expect("compile_module TS"); + + let ts_sess_rt = Runtime::make().typescript(true).globals({ + let ts_mod = ts_mod.clone(); + move |_| { + let ts_mod = ts_mod.clone(); + vec![ + ( + "loadMath", + HostValue::Function(HostFunction::direct(move |ctx, _| { + ctx.eval_compiled(&ts_mod) + })), + ), + ( + "loadInlineTs", + HostValue::Function(HostFunction::direct(|ctx, _| { + ctx.eval_module( + "const greet = (who: string): string => 'hello ' + who; return greet('ts');", + "inline.ts", + ) + })), + ), + ] + } + }); + + let (mut sess, init) = ts_sess_rt.session( + "const m = loadMath(); return { run: (x: number) => m.compute({ x }), inline: () => loadInlineTs() };", + &ProgramOptions::new(), + ); + init.json().expect("TS session"); + let err = sess + .call("run", &[Data::from(serde_json::json!(99))]) + .result + .expect_err("expected TS runtime error"); + let err_msg = err.message_lossy(); + assert!( + err_msg.contains("at compute (math.ts:4:11)"), + "expected math.ts:4:11 frame, got: {err_msg}" + ); + + // 4. HostCtx::eval_module inherits session's typescript setting. + assert_eq!( + sess.call("inline", &[]) + .json() + .expect("HostCtx::eval_module TS"), + serde_json::json!("hello ts") + ); + + // 5. Non-erasable TypeScript constructs fail with clear ParseError. + for (label, bad_ts) in [ + ("enum", "enum Color { Red, Green } return Color.Red;"), + ("const enum", "const enum Dir { Up = 1 } return Dir.Up;"), + ( + "namespace", + "namespace Foo { export const x = 1; } return Foo.x;", + ), + ( + "parameter property", + "class A { constructor(public x: number) {} } return new A(1).x;", + ), + ( + "readonly parameter property", + "class A { constructor(readonly x: number) {} } return new A(1).x;", + ), + ("import =", "import x = require('foo'); return x;"), + ("export =", "const x = 1; export = x;"), + ] { + let err = ts_rt + .compile(bad_ts) + .expect_err(&format!("{label} must be rejected")); + assert_eq!( + err.kind, + DiagnosticKind::ParseError, + "{label} should return ParseError" + ); + let msg = err.message_lossy(); + assert!( + msg.contains("erasable TypeScript"), + "{label} error should mention erasable TypeScript, got: {msg}" + ); + } +} + +#[test] +fn ts_wrappers_preserve_this_delete_typeof_compound_assign_update_and_ambient_syntax() { + let ts_rt = Runtime::make().typescript(true); + + // 1. Call & tagged-template `this` preservation, plus `(0, o.m)()` still dropping `this`. + let calls_out = ts_rt + .execute( + r#" + class Base { + tag: string = "base"; + who(): string { return this.tag; } + } + class Sub extends Base { + tag: string = "sub"; + callSuper(): string { return super.who!(); } + } + const o: any = { + tag: "obj", + m(): string { return this ? this.tag : "undef"; }, + t(parts: TemplateStringsArray, v: number): string { + return this.tag + ":" + parts[0] + v; + }, + }; + const maybe: any = o; + const nil: any = null; + const indirect = (0, o.m)(); + return { + bang: o.m!(), + asAny: (o.m as any)(), + optBang: maybe?.m!(), + optNil: nil?.m!() === undefined, + superBang: new Sub().callSuper(), + tagged: o.t!`v=${7}`, + indirect, + }; + "#, + ) + .json() + .expect("TS call/tagged-template preservation"); + assert_eq!( + calls_out, + serde_json::json!({ + "bang": "obj", + "asAny": "obj", + "optBang": "obj", + "optNil": true, + "superBang": "sub", + "tagged": "obj:v=7", + "indirect": "undef", + }) + ); + + // 2. delete with TS wrappers and optional chaining. + let del_out = ts_rt + .execute( + r#" + const o: any = { a: 1, b: 2, c: 3 }; + const nil: any = null; + const d1 = delete o.a!; + const d2 = delete (o.b as any); + const d3 = delete o?.c!; + const d4 = delete nil?.x!; + return { + d1, d2, d3, d4, + hasA: "a" in o, + hasB: "b" in o, + hasC: "c" in o, + }; + "#, + ) + .json() + .expect("TS delete"); + assert_eq!( + del_out, + serde_json::json!({ + "d1": true, + "d2": true, + "d3": true, + "d4": true, + "hasA": false, + "hasB": false, + "hasC": false, + }) + ); + + // 3. Compound/logical assignments, update expressions, and super targets with TS wrappers. + let mut_out = ts_rt + .execute( + r#" + let x: number | null = 10; + (x as number) += 2; + const pre = ++x!; + + const o: any = { x: 5, c: 20 }; + o.x! += 1; + o.y! ??= 99; + o.x! ??= 777; + const post = o.c!++; + + class Parent { + _v: number = 0; + get val(): number { return this._v; } + set val(v: number) { this._v = v; } + } + class Child extends Parent { + run(): number { + super.val! = 3; + super.val! += 4; + return this._v; + } + forSuper(): string { + try { + for (super.val! of [1]) {} + return "no-throw"; + } catch (e: any) { + return e.name; + } + } + } + const ch = new Child(); + return { + x, + pre, + ox: o.x, + oy: o.y, + oc: o.c, + post, + superVal: ch.run(), + forSuper: ch.forSuper(), + }; + "#, + ) + .json() + .expect("TS compound/update/super"); + assert_eq!( + mut_out, + serde_json::json!({ + "x": 13, + "pre": 13, + "ox": 6, + "oy": 99, + "oc": 21, + "post": 20, + "superVal": 7, + "forSuper": "SyntaxError", + }) + ); + + // 4. typeof with TS wrappers on undeclared globals. + let typeof_out = ts_rt + .execute( + r#" + return [typeof undeclaredVar!, typeof (undeclaredVar as any)]; + "#, + ) + .json() + .expect("TS typeof"); + assert_eq!(typeof_out, serde_json::json!(["undefined", "undefined"])); + + // 5. Ambient/type-only TS edge cases: export {}, export default interface, declare enum, + // declare class, declare global, abstract accessor. + let ambient_out = ts_rt + .execute( + r#" + export {}; + export default interface DefaultIface { id: string } + declare enum ExternalStatus { Ok = 1, Fail = 2 } + declare class ExternalClass { + readonly x: number; + constructor(x: number); + } + declare global { + enum GlobalAmbientEnum { A } + } + abstract class AbstractHolder { + abstract accessor label: string; + ping(): string { return "ok"; } + } + class ConcreteHolder extends AbstractHolder { + getLabel(): string { return this.ping(); } + } + return new ConcreteHolder().getLabel(); + "#, + ) + .json() + .expect("TS ambient & type-only edge cases"); + assert_eq!(ambient_out, serde_json::json!("ok")); + + // 6. CompileOptions::typescript = None inherits Runtime::typescript(true). + let inherited = ts_rt + .compile_with( + "const n: number = 41; return n + 1;", + &CompileOptions::new().module_name("inherited.ts"), + ) + .expect("compile_with should inherit Runtime::typescript(true)"); + assert_eq!( + ts_rt.execute(&inherited).json().unwrap(), + serde_json::json!(42) + ); + + let overridden = ts_rt.compile_with( + "const n: number = 41; return n + 1;", + &CompileOptions::new().typescript(false), + ); + assert!( + overridden.is_err(), + "explicit CompileOptions::typescript(false) must override Runtime::typescript(true)" + ); +} + +#[test] +fn typescript_program_suspends_and_resumes_via_snapshot() { + let ts_code = r#" + type Acc = { total: number }; + const state: Acc = { total: 0 }; + for (let i: number = 0; i < 2_000_000; i++) { + state.total! = ((state.total as number) + i) % 1_000_003; + } + return state.total; + "#; + + let rt = Runtime::make().typescript(true); + let expected = rt.execute(ts_code).json().expect("baseline TS run"); + let prog = rt.program(ts_code, &ProgramOptions::new()); + let suspender = prog.suspender(); + let (outcome, answer) = std::thread::scope(|s| { + let h = s.spawn(move || suspender.suspend(None)); + std::thread::sleep(std::time::Duration::from_millis(5)); + ( + prog.run_resumable().expect("run_resumable"), + h.join().unwrap(), + ) + }); + let suspended = match outcome { + RunOutcome::Suspended(s) => s, + RunOutcome::Done(o) => panic!("expected suspension, got complete: {:?}", o.result), + }; + assert!(matches!( + answer.expect("suspend answer"), + RunOutcome::Suspended(_) + )); + + let bytes = to_bytes(&suspended.state); + let decoded = from_bytes(&bytes).expect("from_bytes"); + let resumed = rt.resume(&decoded).expect("resume TS snapshot"); + let final_outcome = match resumed.run_resumable().expect("run resumed TS") { + RunOutcome::Done(o) => o, + RunOutcome::Suspended(_) => panic!("unexpected second suspend"), + }; + assert_eq!(final_outcome.json().expect("resumed result"), expected); +} + +#[test] +fn load_module_preserves_custom_globals_under_lazy_builtins_and_gc_stress() { + let compiler_rt = Runtime::make(); + // Module references `console`, `Map`, `URL`, `Uint8Array`, and `Set` (triggering lazy groups). + 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"); + + // Host overrides `console` (referenced at init) and `Map` (NOT referenced at init) via + // Runtime::globals; neither may be clobbered when loading a module that triggers lazy built-ins. + 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) + })), + ), + ( + "noop", + HostValue::Function(HostFunction::direct(|_, _| Ok(Val::undefined()))), + ), + ] + } + }); + + let (mut sess, init) = rt.session( + "const caller = loadCaller(); return { broken: () => loadBroken(), invoke: () => caller.invokeHost() };", + &ProgramOptions::new(), + ); + init.json().expect("session init"); + + // 1. HostCtx::eval_module syntax error must NOT double-prefix "SyntaxError: SyntaxError: ...". + 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}" + ); + + // 2. Host call inside a named module resolves Call::location() and Diagnostic.location against + // that module's source (line 3, col 5 in caller.js, NOT init.js). + 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}" + ); +} From b4023ae8524d5c7b3f8ad7cce17eff249f30b92a Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Thu, 3 Dec 2026 02:10:16 +0100 Subject: [PATCH 2/2] =?UTF-8?q?refactor(rust):=20rework=20#159=20=E2=80=94?= =?UTF-8?q?=20drop=20TS=20mode,=20add=20module=20snapshot=20durability?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Drop TypeScript stripping, CompileOptions, duplicate max_source_bytes, and unrelated super tagged-template fix - Respect Limits::max_source_bytes in compile_module / eval_module - Avoid spawning an OS thread per nested eval_module when stack budget allows inline compile - Reuse first_frame error-location helper for loaded modules - Persist loaded modules, load order (including Array.fromAsync), and per-module source metadata across Session::save / restore_session and suspend/resume snapshots - Pack CallSite into 8 bytes (Option == Option) to stay within 0.1% on all callgrind bench programs - Document Rust-only precompiled modules and per-module stacks/toString in rust/README.md --- rust/README.md | 1 + .../crates/psychoscript/src/builtins/array.rs | 5 +- .../psychoscript/src/builtins/collections.rs | 2 +- .../psychoscript/src/builtins/object.rs | 12 +- rust/crates/psychoscript/src/bytecode.rs | 53 +- rust/crates/psychoscript/src/collector.rs | 9 - rust/crates/psychoscript/src/compiler.rs | 602 +-------- rust/crates/psychoscript/src/host.rs | 62 +- rust/crates/psychoscript/src/lib.rs | 2 +- rust/crates/psychoscript/src/native.rs | 2 +- rust/crates/psychoscript/src/object.rs | 7 +- rust/crates/psychoscript/src/promise.rs | 2 +- rust/crates/psychoscript/src/reach.rs | 6 +- rust/crates/psychoscript/src/run.rs | 242 ++-- rust/crates/psychoscript/src/runtime.rs | 70 +- rust/crates/psychoscript/src/session.rs | 66 +- rust/crates/psychoscript/src/snapshot.rs | 252 ++-- rust/crates/psychoscript/src/stack.rs | 99 +- rust/crates/psychoscript/src/vm.rs | 340 +++-- rust/crates/psychoscript/tests/modules.rs | 1149 +++++++++++++++++ .../psychoscript/tests/modules_and_ts.rs | 991 -------------- 21 files changed, 1936 insertions(+), 2038 deletions(-) create mode 100644 rust/crates/psychoscript/tests/modules.rs delete mode 100644 rust/crates/psychoscript/tests/modules_and_ts.rs 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 b345006d..d99fb0be 100644 --- a/rust/crates/psychoscript/src/builtins/array.rs +++ b/rust/crates/psychoscript/src/builtins/array.rs @@ -438,8 +438,8 @@ fn array_from_async(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res // Its `fields` hold where the program called it, where its failures point (see `Vm::locate`). let origin = vm .call_location() - .filter(|s| s.source.is_none()) - .map_or(Value::Undef, |s| Value::Num(s.offset as f64)); + .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 { @@ -521,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 d9a4df23..9f03c6f8 100644 --- a/rust/crates/psychoscript/src/builtins/collections.rs +++ b/rust/crates/psychoscript/src/builtins/collections.rs @@ -565,7 +565,7 @@ fn locate_call(vm: &mut Vm, e: &Value) { && let Some(offset) = caller.func.pos.get(caller.pc.saturating_sub(1)).copied() { f.offset = Some(offset); - f.source = caller.func.source.clone(); + f.source = caller.func.source(); } } diff --git a/rust/crates/psychoscript/src/builtins/object.rs b/rust/crates/psychoscript/src/builtins/object.rs index f26650ee..968876d7 100644 --- a/rust/crates/psychoscript/src/builtins/object.rs +++ b/rust/crates/psychoscript/src/builtins/object.rs @@ -1049,14 +1049,12 @@ fn function_to_string(vm: &mut Vm, this: Value, _: &[Value], _: Id) -> Res { return Err(vm.type_error("Function.prototype.toString called on incompatible receiver.")); }; let (span, source) = match &vm.heap[id as usize].kind { - Kind::Closure(c) => (c.proto.text, c.proto.source.clone()), - _ => (None, None), + Kind::Closure(c) => (c.proto.text, c.proto.source()), + _ => (None, 0), }; - let code: &str = match &source { - Some(src) => &src.code, - None => &vm.code, - }; - if let Some(text) = span.and_then(|[start, end]| 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 1d00cda7..56d7d078 100644 --- a/rust/crates/psychoscript/src/bytecode.rs +++ b/rust/crates/psychoscript/src/bytecode.rs @@ -298,11 +298,46 @@ pub struct ModuleSource { pub code: Arc, } -/// A bytecode source site: byte offset plus optional named module source (`None` = `Vm::code`). -#[derive(Clone, Debug)] +/// 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 offset: u32, - pub source: Option>, + 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 @@ -532,12 +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]>, - /// Source metadata for functions compiled as a named module; `None` for single-file runs so - /// existing single-file programs incur zero overhead. - pub(crate) source: Option>, + /// 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 398c3778..9335a84c 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1157,15 +1157,6 @@ impl Vm { } } - /// Write barrier for values stored into VM root tables (e.g. `Vm::consts`, `Vm::templates`, - /// `Vm::globals`, `Vm::global_map`) while incremental marking is in progress. - #[inline] - pub(crate) fn gc_shade(&mut self, val: Value) { - if self.gc.phase == Phase::Mark { - self.gc_shade_value(val); - } - } - /// Shades an atom stored into VM root tables during an active GC cycle. #[inline] pub(crate) fn gc_shade_atom(&mut self, a: Atom) { diff --git a/rust/crates/psychoscript/src/compiler.rs b/rust/crates/psychoscript/src/compiler.rs index b93719f3..e0211f63 100644 --- a/rust/crates/psychoscript/src/compiler.rs +++ b/rust/crates/psychoscript/src/compiler.rs @@ -17,8 +17,8 @@ use rustc_hash::{FxHashMap, FxHashSet}; use crate::DiagnosticKind; use crate::bytecode::{ - Arith, Capture, FuncProto, ITER_DELEGATE, ITER_DESTRUCTURE, ITER_FOR_AWAIT, ITER_FOR_OF, - ModuleSource, Op, Program, TemplateSite, + Arith, Capture, FuncProto, ITER_DELEGATE, ITER_DESTRUCTURE, ITER_FOR_AWAIT, ITER_FOR_OF, Op, + Program, TemplateSite, }; use crate::bytecode::{CLASS_BASE, CLASS_DERIVED}; use crate::strings::{Atom, Strings}; @@ -39,69 +39,21 @@ const MAX_NESTING: u32 = 2_000; /// (256 KiB); `run::compile` refuses a larger one. pub const DEFAULT_MAX_SOURCE_BYTES: usize = 256 * 1024; -/// Options controlling how source code is parsed and compiled. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct CompileOptions { - /// Override erasable TypeScript type-stripping (`None` inherits from - /// [`Runtime::typescript`](crate::Runtime::typescript), which defaults to `false`). - pub typescript: Option, - /// Optional module name attached to compiled functions for `module:line:col` stack traces. - pub module_name: Option, - /// Optional maximum source size in bytes (`None` uses the default 256 KiB limit). - pub max_source_bytes: Option, -} - -impl CompileOptions { - pub fn new() -> Self { - Self::default() - } - - /// Enables or disables erasable TypeScript type-stripping for this compilation. - pub fn typescript(mut self, enabled: bool) -> Self { - self.typescript = Some(enabled); - self - } - - /// Sets the module name shown in stack traces for functions compiled from this source. - pub fn module_name(mut self, name: impl Into) -> Self { - self.module_name = Some(name.into()); - self - } - - /// Sets the maximum source size in bytes accepted for this compilation. - pub fn max_source_bytes(mut self, bytes: usize) -> Self { - self.max_source_bytes = Some(bytes); - self - } -} - -#[cfg(feature = "test262")] pub fn compile(source: &str, atoms: &mut Strings) -> R { - compile_as( - source, - atoms, - false, - &CompileOptions::default(), - false, - None, - ) + compile_as(source, atoms, false, false) } -pub(crate) fn compile_with( - source: &str, - atoms: &mut Strings, - options: &CompileOptions, - sync_module: bool, - module_source: Option>, -) -> R { - compile_as(source, atoms, false, options, sync_module, module_source) +/// 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, &CompileOptions::default(), false, None) + compile_as(source, atoms, true, false) } /// The offset of the first token after a class element's leading `static`. @@ -113,14 +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, - options: &CompileOptions, - sync_module: bool, - module_source: Option>, -) -> 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. @@ -128,15 +73,7 @@ fn compile_as( } ARENA.with(|arena| match arena.try_borrow_mut() { Ok(mut arena) => { - let r = compile_in( - &arena, - source, - atoms, - internal, - options, - sync_module, - module_source, - ); + let r = compile_in(&arena, source, atoms, internal, sync_module); match arena.capacity() > ARENA_KEEP_BYTES { true => *arena = Allocator::default(), false => arena.reset(), @@ -144,15 +81,7 @@ fn compile_as( 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, - options, - sync_module, - module_source, - ), + Err(_) => compile_in(&Allocator::default(), source, atoms, internal, sync_module), }) } @@ -161,9 +90,7 @@ fn compile_in( source: &str, atoms: &mut Strings, internal: bool, - options: &CompileOptions, sync_module: bool, - module_source: Option>, ) -> R { if source.trim().is_empty() { return Err(CompileError { @@ -172,25 +99,18 @@ fn compile_in( offset: None, }); } - let typescript = options.typescript.unwrap_or(false); let renamed: String; let mut await_alias = None; - let initial_type = if typescript { - SourceType::ts() - } else { - SourceType::mjs() - }; - let mut parsed = parse(allocator, source, initial_type); + let mut parsed = parse(allocator, source, SourceType::mjs()); // The reference parses a script that allows top-level `await`: `await` is a plain name there, read as the // operator only where an expression starts with it. A program whose first error is naming something `await` is // parsed again as a script, unless it also uses `await` as an expression at the top level; then the names are // renamed for the parse instead, keeping the expressions. - if !typescript - && parsed - .diagnostics - .errors() - .next() - .is_some_and(|d| names_await(source, d)) + if parsed + .diagnostics + .errors() + .next() + .is_some_and(|d| names_await(source, d)) { let script = parse(allocator, source, SourceType::script()); if script.diagnostics.errors().next().is_none() @@ -242,24 +162,13 @@ fn compile_in( } // Parsed as a module for top-level `await`, but bound as a script, like the reference: top-level functions and // `var`s share one scope, so redeclaring one as the other is allowed. - parsed.program.source_type = if typescript { - SourceType::ts().with_script(true) - } else { - SourceType::script() - }; + parsed.program.source_type = SourceType::script(); let program = &parsed.program; - if typescript && let Some((msg, at)) = find_non_erasable_ts(program) { - return Err(CompileError { - kind: DiagnosticKind::ParseError, - message: format!("SyntaxError: {msg}"), - offset: Some(at), - }); - } - if let Some(export) = program.body.iter().find(|s| { - s.is_module_declaration() - && !matches!(s, Statement::ImportDeclaration(_)) - && !(typescript && is_type_only_module_decl(s)) - }) { + if let Some(export) = program + .body + .iter() + .find(|s| s.is_module_declaration() && !matches!(s, Statement::ImportDeclaration(_))) + { return Err(CompileError { kind: DiagnosticKind::ParseError, message: "SyntaxError: Exports aren't available. Return the result instead.".into(), @@ -307,9 +216,7 @@ fn compile_in( let mut c = Compiler::new(scoping, semantic.semantic.nodes(), atoms); c.await_alias = await_alias; c.internal = internal; - c.typescript = typescript; c.sync_module = sync_module; - c.module_source = module_source; c.source = program.source_text; c.find_unbound(program); c.find_field_values(program); @@ -336,173 +243,6 @@ fn parse<'a>(allocator: &'a Allocator, text: &'a str, source_type: SourceType) - .parse() } -/// Rejects runtime-emitting TypeScript syntax (enums, non-ambient namespaces/modules, constructor -/// parameter properties, non-type `import =`, and `export =`) so only erasable TypeScript passes. -fn find_non_erasable_ts(program: &oxc_ast::ast::Program<'_>) -> Option<(&'static str, u32)> { - struct Check(Option<(&'static str, u32)>); - impl Check { - fn record(&mut self, msg: &'static str, at: u32) { - if self.0.is_none_or(|(_, cur)| at < cur) { - self.0 = Some((msg, at)); - } - } - } - impl<'a> Visit<'a> for Check { - fn visit_class(&mut self, it: &Class<'a>) { - if !it.declare { - walk::walk_class(self, it); - } - } - fn visit_ts_global_declaration(&mut self, _it: &TSGlobalDeclaration<'a>) {} - fn visit_ts_enum_declaration(&mut self, it: &TSEnumDeclaration<'a>) { - if !it.declare { - self.record( - "TypeScript `enum` is not supported; only erasable TypeScript syntax is supported.", - it.span.start, - ); - } - } - fn visit_ts_namespace_declaration(&mut self, it: &TSNamespaceDeclaration<'a>) { - if !it.declare { - self.record( - "TypeScript `namespace` is not supported; only erasable TypeScript syntax is supported.", - it.span.start, - ); - } - } - fn visit_ts_external_module_declaration(&mut self, it: &TSExternalModuleDeclaration<'a>) { - if !it.declare { - self.record( - "TypeScript `module` declaration is not supported; only erasable TypeScript syntax is supported.", - it.span.start, - ); - } - } - fn visit_formal_parameter(&mut self, it: &FormalParameter<'a>) { - if it.accessibility.is_some() || it.readonly || it.r#override { - self.record( - "TypeScript parameter properties are not supported; only erasable TypeScript syntax is supported.", - it.span.start, - ); - } - walk::walk_formal_parameter(self, it); - } - fn visit_ts_import_equals_declaration(&mut self, it: &TSImportEqualsDeclaration<'a>) { - if !it.import_kind.is_type() { - self.record( - "TypeScript `import =` is not supported; only erasable TypeScript syntax is supported.", - it.span.start, - ); - } - } - fn visit_ts_export_assignment(&mut self, it: &TSExportAssignment<'a>) { - self.record( - "TypeScript `export =` is not supported; only erasable TypeScript syntax is supported.", - it.span.start, - ); - } - } - let mut check = Check(None); - check.visit_program(program); - check.0 -} - -fn is_type_only_export_decl(d: &ExportDeclaration<'_>) -> bool { - match &d.declaration { - Declaration::TSTypeAliasDeclaration(_) - | Declaration::TSInterfaceDeclaration(_) - | Declaration::TSGlobalDeclaration(_) => true, - Declaration::VariableDeclaration(v) => v.declare, - Declaration::FunctionDeclaration(f) => f.declare || f.body.is_none(), - Declaration::ClassDeclaration(c) => c.declare, - Declaration::TSNamespaceDeclaration(n) => n.declare, - Declaration::TSExternalModuleDeclaration(m) => m.declare, - Declaration::TSImportEqualsDeclaration(i) => i.import_kind.is_type(), - Declaration::TSEnumDeclaration(e) => e.declare, - } -} - -fn is_type_only_export_named(d: &ExportNamedDeclaration<'_>) -> bool { - // Also allows empty `export {}`, the standard TypeScript module-scoping marker. - d.export_kind.is_type() || d.specifiers.iter().all(|s| s.export_kind.is_type()) -} - -fn is_type_only_export_from(d: &ExportFromDeclaration<'_>) -> bool { - d.export_kind.is_type() - || (!d.specifiers.is_empty() && d.specifiers.iter().all(|s| s.export_kind.is_type())) -} - -fn is_type_only_export_default(d: &ExportDefaultDeclaration<'_>) -> bool { - matches!( - d.declaration, - ExportDefaultDeclarationKind::TSInterfaceDeclaration(_) - ) -} - -fn is_type_only_module_decl(s: &Statement<'_>) -> bool { - match s { - Statement::ExportDeclaration(d) => is_type_only_export_decl(d), - Statement::ExportNamedDeclaration(d) => is_type_only_export_named(d), - Statement::ExportFromDeclaration(d) => is_type_only_export_from(d), - Statement::ExportDefaultDeclaration(d) => is_type_only_export_default(d), - Statement::ExportAllDeclaration(d) => d.export_kind.is_type(), - Statement::TSNamespaceExportDeclaration(_) => true, - _ => false, - } -} - -fn is_erased_class_element(m: &ClassElement<'_>) -> bool { - match m { - ClassElement::TSIndexSignature(_) => true, - ClassElement::PropertyDefinition(p) => { - p.declare || p.r#type == PropertyDefinitionType::TSAbstractPropertyDefinition - } - ClassElement::MethodDefinition(d) => { - d.value.body.is_none() || d.r#type == MethodDefinitionType::TSAbstractMethodDefinition - } - ClassElement::AccessorProperty(a) => { - a.r#type == AccessorPropertyType::TSAbstractAccessorProperty - } - _ => false, - } -} - -/// Unwraps erasable TypeScript expression wrappers (and parens around them) while preserving -/// non-wrapper expressions such as `SequenceExpression` (`(0, o.m)()`). -fn strip_ts_expr<'a>(mut e: &'a Expression<'a>) -> &'a Expression<'a> { - loop { - e = match e { - Expression::ParenthesizedExpression(p) => &p.expression, - Expression::TSAsExpression(x) => &x.expression, - Expression::TSSatisfiesExpression(x) => &x.expression, - Expression::TSNonNullExpression(x) => &x.expression, - Expression::TSTypeAssertion(x) => &x.expression, - Expression::TSInstantiationExpression(x) => &x.expression, - _ => return e, - }; - } -} - -enum ResolvedTarget<'a> { - Ident(&'a IdentifierReference<'a>), - Static(&'a StaticMemberExpression<'a>), - Computed(&'a ComputedMemberExpression<'a>), - Super(&'a MemberExpression<'a>), -} - -fn resolve_expr_target<'a>(e: &'a Expression<'a>) -> Option> { - let e = strip_ts_expr(e); - if let Some(m) = Compiler::super_member(e.as_member_expression()) { - return Some(ResolvedTarget::Super(m)); - } - match e { - Expression::Identifier(id) => Some(ResolvedTarget::Ident(id)), - Expression::StaticMemberExpression(m) => Some(ResolvedTarget::Static(m)), - Expression::ComputedMemberExpression(m) => Some(ResolvedTarget::Computed(m)), - _ => None, - } -} - /// The source with each `await` the reference reads as a name replaced by the returned five-letter identifier, which /// the source does not contain, padded with spaces to keep every offset (an escaped `await` is longer); `await` /// expressions stay. `None` when the module parse fails for another reason. @@ -1544,12 +1284,8 @@ struct Compiler<'a, 's> { last_home: bool, /// Compiling a prelude built-in (see `compile_internal`). internal: bool, - /// Strip erasable TypeScript syntax during compilation. - typescript: bool, - /// Compile top-level program as a synchronous module (`is_async = false; is_program = false`). + /// Compiling a synchronous named module (`is_async = false; is_program = false`). sync_module: bool, - /// Optional per-module source metadata attached to every compiled `FuncProto`. - module_source: Option>, /// The text the program was parsed from, which spans index. source: &'a str, } @@ -1595,9 +1331,7 @@ impl<'a, 's> Compiler<'a, 's> { pseudo: 0, last_home: false, internal: false, - typescript: false, sync_module: false, - module_source: None, source: "", } } @@ -1974,9 +1708,6 @@ impl<'a, 's> Compiler<'a, 's> { let Statement::ImportDeclaration(d) = st else { continue; }; - if self.typescript && d.import_kind.is_type() { - continue; - } if d.import_kind.is_type() || d.phase.is_some() { return Err(unsupported("This form of `import`", d.span)); } @@ -2008,12 +1739,6 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); } for spec in specifiers { - if self.typescript - && let ImportDeclarationSpecifier::ImportSpecifier(x) = spec - && x.import_kind.is_type() - { - continue; - } let (kind, name, local, pos) = match spec { ImportDeclarationSpecifier::ImportDefaultSpecifier(x) => { (0, None, &x.local, x.span.start) @@ -2073,9 +1798,6 @@ impl<'a, 's> Compiler<'a, 's> { fn hoist_functions(&mut self, stmts: &'a [Statement<'a>]) -> R<()> { for st in stmts { if let Statement::FunctionDeclaration(f) = st { - if self.typescript && (f.declare || f.body.is_none()) { - continue; - } self.closure_for_function(f, None)?; let id = f.id.as_ref().and_then(|id| id.symbol_id.get()); match id { @@ -2200,16 +1922,6 @@ impl<'a, 's> Compiler<'a, 's> { self.0.push(it.body.span()); } } - if self.typescript { - for sym in self.scoping.symbol_ids() { - let flags = self.scoping.symbol_flags(sym); - if flags.contains(SymbolFlags::Ambient) - || !flags.intersects(SymbolFlags::Value | SymbolFlags::Import) - { - self.unbound.insert(sym); - } - } - } let mut withs = Withs(Vec::new()); withs.visit_program(program); if withs.0.is_empty() { @@ -2419,7 +2131,7 @@ impl<'a, 's> Compiler<'a, 's> { callees: f.callees, sites: f.sites, text: None, - source: self.module_source.clone(), + source_tag: crate::bytecode::PROGRAM_SOURCE_TAG, }, ); // Closure instructions index `protos` assuming the program is not in the list; shift them. @@ -2676,7 +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: self.module_source.clone(), + source_tag: crate::bytecode::PROGRAM_SOURCE_TAG, }); Ok(self.protos.len() as u32 - 1) } @@ -2707,7 +2419,6 @@ impl<'a, 's> Compiler<'a, 's> { Statement::EmptyStatement(_) => Ok(()), Statement::DebuggerStatement(d) => self.throw_syntax("DebuggerStatement", d.span), Statement::ExpressionStatement(e) => self.expr_stmt(&e.expression), - Statement::VariableDeclaration(d) if self.typescript && d.declare => Ok(()), Statement::VariableDeclaration(d) => self.var_decl(d), Statement::FunctionDeclaration(_) => Ok(()), Statement::IfStatement(s) => { @@ -2758,7 +2469,6 @@ impl<'a, 's> Compiler<'a, 's> { Statement::LabeledStatement(l) => self.labeled(l), Statement::SwitchStatement(s) => self.switch(s, Vec::new()), Statement::TryStatement(t) => self.try_stmt(t), - Statement::ClassDeclaration(c) if self.typescript && c.declare => Ok(()), Statement::ClassDeclaration(c) => self.class_declaration(c), Statement::WithStatement(w) => self.throw_syntax("WithStatement", w.span), // Bound before the body runs (see `imports`); one below the top level of the program does nothing there, @@ -2772,43 +2482,6 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } - Statement::TSTypeAliasDeclaration(_) - | Statement::TSInterfaceDeclaration(_) - | Statement::TSGlobalDeclaration(_) - | Statement::TSNamespaceExportDeclaration(_) - if self.typescript => - { - Ok(()) - } - Statement::TSEnumDeclaration(d) if self.typescript && d.declare => Ok(()), - Statement::TSNamespaceDeclaration(d) if self.typescript && d.declare => Ok(()), - Statement::TSExternalModuleDeclaration(d) if self.typescript && d.declare => Ok(()), - Statement::TSImportEqualsDeclaration(d) - if self.typescript && d.import_kind.is_type() => - { - Ok(()) - } - Statement::ExportAllDeclaration(d) if self.typescript && d.export_kind.is_type() => { - Ok(()) - } - Statement::ExportDefaultDeclaration(d) - if self.typescript && is_type_only_export_default(d) => - { - Ok(()) - } - Statement::ExportNamedDeclaration(d) - if self.typescript && is_type_only_export_named(d) => - { - Ok(()) - } - Statement::ExportDeclaration(d) if self.typescript && is_type_only_export_decl(d) => { - Ok(()) - } - Statement::ExportFromDeclaration(d) - if self.typescript && is_type_only_export_from(d) => - { - Ok(()) - } // Only reached below the top level: `compile` refuses an export at the top. Statement::ExportAllDeclaration(d) => self.throw_syntax("ExportAllDeclaration", d.span), Statement::ExportDefaultDeclaration(d) => { @@ -3768,66 +3441,13 @@ impl<'a, 's> Compiler<'a, 's> { } } - fn resolve_simple_target( - &self, - s: &'a SimpleAssignmentTarget<'a>, - ) -> Option> { + fn assign_simple(&mut self, s: &'a SimpleAssignmentTarget<'a>) -> R<()> { if let Some(m) = Self::super_member(s.as_member_expression()) { - return Some(ResolvedTarget::Super(m)); + return self.super_target(m.object().span()); } match s { - SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => { - Some(ResolvedTarget::Ident(id)) - } - SimpleAssignmentTarget::StaticMemberExpression(m) => Some(ResolvedTarget::Static(m)), - SimpleAssignmentTarget::ComputedMemberExpression(m) => { - Some(ResolvedTarget::Computed(m)) - } - SimpleAssignmentTarget::TSAsExpression(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - SimpleAssignmentTarget::TSSatisfiesExpression(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - SimpleAssignmentTarget::TSNonNullExpression(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - SimpleAssignmentTarget::TSTypeAssertion(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - _ => None, - } - } - - fn resolve_assign_target(&self, t: &'a AssignmentTarget<'a>) -> Option> { - if let Some(m) = Self::super_member(t.as_member_expression()) { - return Some(ResolvedTarget::Super(m)); - } - match t { - AssignmentTarget::AssignmentTargetIdentifier(id) => Some(ResolvedTarget::Ident(id)), - AssignmentTarget::StaticMemberExpression(m) => Some(ResolvedTarget::Static(m)), - AssignmentTarget::ComputedMemberExpression(m) => Some(ResolvedTarget::Computed(m)), - AssignmentTarget::TSAsExpression(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - AssignmentTarget::TSSatisfiesExpression(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - AssignmentTarget::TSNonNullExpression(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - AssignmentTarget::TSTypeAssertion(x) if self.typescript => { - resolve_expr_target(&x.expression) - } - _ => None, - } - } - - fn assign_simple(&mut self, s: &'a SimpleAssignmentTarget<'a>) -> R<()> { - match self.resolve_simple_target(s) { - Some(ResolvedTarget::Super(m)) => self.super_target(m.object().span()), - Some(ResolvedTarget::Ident(id)) => self.store_ident(id), - Some(ResolvedTarget::Static(m)) => { + SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => self.store_ident(id), + SimpleAssignmentTarget::StaticMemberExpression(m) => { self.expr(&m.object)?; self.emit(Op::Swap); let a = self.atom(m.property.name.as_str()); @@ -3835,7 +3455,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); Ok(()) } - Some(ResolvedTarget::Computed(m)) => { + SimpleAssignmentTarget::ComputedMemberExpression(m) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -3844,14 +3464,13 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); Ok(()) } - None => Err(unsupported("This assignment target", s.span())), + other => Err(unsupported("This assignment target", other.span())), } } // ---------- expressions ---------- fn expr_named(&mut self, e: &'a Expression<'a>, name: Option<&str>) -> R<()> { - let e = if self.typescript { strip_ts_expr(e) } else { e }; match e { Expression::ClassExpression(c) if c.id.is_none() => { self.pos = c.span.start; @@ -3975,9 +3594,6 @@ impl<'a, 's> Compiler<'a, 's> { self.chains.push(Vec::new()); match &c.expression { ChainElement::CallExpression(call) => self.call(call)?, - ChainElement::TSNonNullExpression(x) if self.typescript => { - self.expr(&x.expression)?; - } other => match other.as_member_expression() { Some(m) => self.expr(m_as_expr(m))?, None => return Err(unsupported("TypeScript syntax", other.span())), @@ -4053,13 +3669,6 @@ impl<'a, 's> Compiler<'a, 's> { Expression::PrivateInExpression(p) => { return Err(unsupported("Private fields", p.span)); } - Expression::TSAsExpression(x) if self.typescript => self.expr(&x.expression)?, - Expression::TSSatisfiesExpression(x) if self.typescript => self.expr(&x.expression)?, - Expression::TSNonNullExpression(x) if self.typescript => self.expr(&x.expression)?, - Expression::TSTypeAssertion(x) if self.typescript => self.expr(&x.expression)?, - Expression::TSInstantiationExpression(x) if self.typescript => { - self.expr(&x.expression)?; - } other => return Err(unsupported("This syntax", other.span())), } Ok(()) @@ -4110,17 +3719,7 @@ impl<'a, 's> Compiler<'a, 's> { /// `tag\`...\``: calls the tag, read like a callee, with the site's strings array and the substitutions. fn tagged_template(&mut self, t: &'a TaggedTemplateExpression<'a>) -> R<()> { - let tag = if self.typescript { - strip_ts_expr(&t.tag) - } else { - &t.tag - }; - match tag { - tag if Self::super_member(tag.as_member_expression()).is_some() => { - if let Some(m) = tag.as_member_expression() { - self.super_get(m, true)?; - } - } + match &t.tag { Expression::StaticMemberExpression(m) => { self.expr(&m.object)?; let a = self.atom(m.property.name.as_str()); @@ -4315,11 +3914,7 @@ impl<'a, 's> Compiler<'a, 's> { /// `delete`: a member expression deletes, optionally; an identifier fails when it runs, as in the reference; /// anything else is evaluated and gives true. fn delete(&mut self, argument: &'a Expression<'a>) -> R<()> { - let argument = if self.typescript { - strip_ts_expr(argument) - } else { - argument.without_parentheses() - }; + let argument = argument.without_parentheses(); if let Expression::Identifier(id) = argument { let msg = self.str_const("Only data fields may be deleted."); self.pos = id.span.start; @@ -4327,12 +3922,7 @@ impl<'a, 's> Compiler<'a, 's> { return Ok(()); } let member = match argument { - Expression::ChainExpression(c) => match &c.expression { - ChainElement::TSNonNullExpression(x) if self.typescript => { - strip_ts_expr(&x.expression).as_member_expression() - } - other => other.as_member_expression(), - }, + Expression::ChainExpression(c) => c.expression.as_member_expression(), other => other.as_member_expression(), }; let Some(member) = member else { @@ -4414,12 +4004,7 @@ impl<'a, 's> Compiler<'a, 's> { _ => {} } } - let callee = if self.typescript { - strip_ts_expr(&c.callee) - } else { - &c.callee - }; - match callee { + match &c.callee { callee if Self::super_member(callee.as_member_expression()).is_some() => { if let Some(m) = callee.as_member_expression() { self.super_get(m, true)?; @@ -4480,12 +4065,7 @@ impl<'a, 's> Compiler<'a, 's> { fn unary(&mut self, u: &'a UnaryExpression<'a>) -> R<()> { match u.operator { UnaryOperator::Typeof => { - let arg = if self.typescript { - strip_ts_expr(&u.argument) - } else { - &u.argument - }; - if let Expression::Identifier(id) = arg + if let Expression::Identifier(id) = &u.argument && self.ident_symbol(id).is_none() && id.name.as_str() != "undefined" && id.name.as_str() != "arguments" @@ -4523,48 +4103,40 @@ impl<'a, 's> Compiler<'a, 's> { } fn assignment(&mut self, a: &'a AssignmentExpression<'a>) -> R<()> { - let op = a.operator; - if op == AssignmentOperator::Assign - && matches!( - a.left, - AssignmentTarget::ArrayAssignmentTarget(_) - | AssignmentTarget::ObjectAssignmentTarget(_) - ) - { - self.expr(&a.right)?; - self.emit(Op::Dup); - return self.assign_target(&a.left); - } - let Some(target) = self.resolve_assign_target(&a.left) else { - return Err(unsupported("This assignment target", a.left.span())); - }; - if let ResolvedTarget::Super(m) = target { + if let Some(m) = Self::super_member(a.left.as_member_expression()) { return self.super_assign(m, a); } + let op = a.operator; if op == AssignmentOperator::Assign { - return match target { - ResolvedTarget::Ident(id) => { + match &a.left { + AssignmentTarget::AssignmentTargetIdentifier(id) => { self.expr_named(&a.right, Some(id.name.as_str()))?; self.emit(Op::Dup); - self.store_ident(id) + return self.store_ident(id); } - ResolvedTarget::Static(m) => { + AssignmentTarget::StaticMemberExpression(m) => { self.expr(&m.object)?; self.expr(&a.right)?; let at = self.atom(m.property.name.as_str()); self.emit_member(Op::SetProp(at), &m.object, None); - Ok(()) + return Ok(()); } - ResolvedTarget::Computed(m) => { + AssignmentTarget::ComputedMemberExpression(m) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); self.expr(&a.right)?; self.emit_member(Op::SetElem, &m.object, Some(&m.expression)); - Ok(()) + return Ok(()); } - ResolvedTarget::Super(_) => unreachable!(), - }; + AssignmentTarget::ArrayAssignmentTarget(_) + | AssignmentTarget::ObjectAssignmentTarget(_) => { + self.expr(&a.right)?; + self.emit(Op::Dup); + return self.assign_target(&a.left); + } + other => return Err(unsupported("This assignment target", other.span())), + } } let logical = match op { AssignmentOperator::LogicalAnd => Some(Op::JumpIfFalseKeep(0)), @@ -4572,8 +4144,8 @@ impl<'a, 's> Compiler<'a, 's> { AssignmentOperator::LogicalNullish => Some(Op::JumpIfNotNullishKeep(0)), _ => None, }; - match target { - ResolvedTarget::Ident(id) => { + match &a.left { + AssignmentTarget::AssignmentTargetIdentifier(id) => { if let Some(jop) = logical { self.load_ident(id)?; let j = self.emit(jop); @@ -4589,7 +4161,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Dup); self.store_ident(id) } - ResolvedTarget::Static(m) => { + AssignmentTarget::StaticMemberExpression(m) => { let at = self.atom(m.property.name.as_str()); self.expr(&m.object)?; self.emit(Op::Dup); @@ -4610,7 +4182,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit_member(Op::SetProp(at), &m.object, None); Ok(()) } - ResolvedTarget::Computed(m) => { + AssignmentTarget::ComputedMemberExpression(m) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -4633,15 +4205,12 @@ impl<'a, 's> Compiler<'a, 's> { self.emit_member(Op::SetElem, &m.object, Some(&m.expression)); Ok(()) } - ResolvedTarget::Super(_) => unreachable!(), + other => Err(unsupported("This assignment target", other.span())), } } fn update(&mut self, u: &'a UpdateExpression<'a>) -> R<()> { - let Some(target) = self.resolve_simple_target(&u.argument) else { - return Err(unsupported("This update target", u.argument.span())); - }; - if let ResolvedTarget::Super(m) = target { + if let Some(m) = Self::super_member(u.argument.as_member_expression()) { return self.super_update(m, u); } let step = if u.operator == UpdateOperator::Increment { @@ -4649,8 +4218,8 @@ impl<'a, 's> Compiler<'a, 's> { } else { Op::Dec }; - match target { - ResolvedTarget::Ident(id) => { + match &u.argument { + SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => { self.load_ident(id)?; if u.prefix { self.emit(step); @@ -4662,7 +4231,7 @@ impl<'a, 's> Compiler<'a, 's> { } self.store_ident(id) } - ResolvedTarget::Static(m) => { + SimpleAssignmentTarget::StaticMemberExpression(m) => { let at = self.atom(m.property.name.as_str()); self.expr(&m.object)?; self.emit(Op::Dup); @@ -4680,7 +4249,7 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } - ResolvedTarget::Computed(m) => { + SimpleAssignmentTarget::ComputedMemberExpression(m) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -4701,7 +4270,7 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } - ResolvedTarget::Super(_) => unreachable!(), + other => Err(unsupported("This update target", other.span())), } } } @@ -4938,10 +4507,7 @@ impl<'a, 's> Compiler<'a, 's> { struct Fields(Vec); impl<'a> Visit<'a> for Fields { fn visit_property_definition(&mut self, it: &PropertyDefinition<'a>) { - if !it.declare - && it.r#type != PropertyDefinitionType::TSAbstractPropertyDefinition - && let Some(v) = &it.value - { + if let Some(v) = &it.value { self.0.push(v.span()); } walk::walk_property_definition(self, it); @@ -5044,11 +4610,7 @@ impl<'a, 's> Compiler<'a, 's> { } fn class_declaration(&mut self, c: &'a Class<'a>) -> R<()> { - if c.body - .body - .iter() - .any(|m| !(self.typescript && is_erased_class_element(m)) && !supported_member(m)) - { + if c.body.body.iter().any(|m| !supported_member(m)) { return self.compile_class(c, None); } self.compile_class(c, None)?; @@ -5064,12 +4626,7 @@ impl<'a, 's> Compiler<'a, 's> { /// A class definition, which leaves its constructor on the stack (see `classes.rs`). `name` is an anonymous /// class's NamedEvaluation name. fn compile_class(&mut self, c: &'a Class<'a>, name: Option<&str>) -> R<()> { - if let Some(m) = c - .body - .body - .iter() - .find(|m| !(self.typescript && is_erased_class_element(m)) && !supported_member(m)) - { + if let Some(m) = c.body.body.iter().find(|m| !supported_member(m)) { return self.throw_syntax(class_syntax_name(m), m.span()); } let saved_pos = self.pos; @@ -5091,9 +4648,6 @@ impl<'a, 's> Compiler<'a, 's> { }; // A computed field's key is evaluated once, in order, into a binding of its own. for m in &c.body.body { - if self.typescript && is_erased_class_element(m) { - continue; - } if let ClassElement::PropertyDefinition(p) = m && p.computed { @@ -5108,10 +4662,7 @@ impl<'a, 's> Compiler<'a, 's> { self.expr(sc)?; } let ctor = c.body.body.iter().find_map(|m| match m { - ClassElement::MethodDefinition(d) - if d.kind == MethodDefinitionKind::Constructor - && (!self.typescript || d.value.body.is_some()) => - { + ClassElement::MethodDefinition(d) if d.kind == MethodDefinitionKind::Constructor => { Some(d) } _ => None, @@ -5121,11 +4672,7 @@ impl<'a, 's> Compiler<'a, 's> { .body .iter() .filter_map(|m| match m { - ClassElement::PropertyDefinition(p) - if !p.r#static && !(self.typescript && is_erased_class_element(m)) => - { - Some(&**p) - } + ClassElement::PropertyDefinition(p) if !p.r#static => Some(&**p), _ => None, }) .collect(); @@ -5134,11 +4681,7 @@ impl<'a, 's> Compiler<'a, 's> { .body .iter() .filter_map(|m| match m { - ClassElement::PropertyDefinition(p) - if p.r#static && !(self.typescript && is_erased_class_element(m)) => - { - Some(&**p) - } + ClassElement::PropertyDefinition(p) if p.r#static => Some(&**p), _ => None, }) .collect(); @@ -5189,9 +4732,6 @@ impl<'a, 's> Compiler<'a, 's> { let at = heritage.map_or(c.span.start, |s| s.without_parentheses().span().start); self.emit_at(at, Op::Class(derived)); for m in &c.body.body { - if self.typescript && is_erased_class_element(m) { - continue; - } match m { ClassElement::PropertyDefinition(p) if p.computed => { let Some(e) = p.key.as_expression() else { diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index d92e8548..b75112e0 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -695,7 +695,7 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) { } Settlement::Lost(message, site) => { let e = vm.type_error(&message); - locate_settled(vm, &e, site.as_ref(), Some(p)); + locate_settled(vm, &e, site, Some(p)); vm.reject(p, e); } Settlement::Host(settled) => { @@ -712,14 +712,14 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) { Ok(v) => vm.fulfill(p, v), Err(e) => { // The reference converts the value at the call, so its errors point there. - locate_settled(vm, &e, site.as_ref(), Some(p)); + locate_settled(vm, &e, site, Some(p)); vm.reject(p, e) } } } Err(HostValue::Interrupt) => interrupt(vm), Err(thrown) => { - let e = thrown_value(vm, &thrown, &label, site.as_ref(), Some(p)); + let e = thrown_value(vm, &thrown, &label, site, Some(p)); vm.reject(p, e); } } @@ -733,7 +733,7 @@ fn thrown_value( vm: &mut Vm, thrown: &HostValue, label: &str, - site: Option<&crate::bytecode::CallSite>, + site: Option, settled: Option, ) -> Value { match thrown { @@ -759,7 +759,7 @@ fn thrown_value( ); // Made at the call: its `stack` is the program's there. if let (Value::Obj(id), Some(s)) = (e, site) { - vm.host_failure_stack(id, s.offset, s.source.as_ref(), settled); + vm.host_failure_stack(id, s.offset(), s.source(), settled); } e } @@ -768,7 +768,7 @@ fn thrown_value( } /// 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<&crate::bytecode::CallSite>) { +pub(crate) fn locate_at(vm: &mut Vm, e: &Value, site: Option) { locate_settled(vm, e, site, None); } @@ -776,7 +776,7 @@ pub(crate) fn locate_at(vm: &mut Vm, e: &Value, site: Option<&crate::bytecode::C fn locate_settled( vm: &mut Vm, e: &Value, - site: Option<&crate::bytecode::CallSite>, + site: Option, settled: Option, ) { if let Value::Obj(id) = e @@ -784,10 +784,10 @@ fn locate_settled( && f.offset.is_none() && let Some(s) = site { - f.offset = Some(s.offset); - f.source = s.source.clone(); + f.offset = Some(s.offset()); + f.source = s.source(); let id = *id; - vm.locate_stack_settled(id, s.offset, s.source.as_deref(), settled); + vm.locate_stack_settled(id, s.offset(), s.source(), settled); } } @@ -838,7 +838,7 @@ pub fn call_namespace(vm: &mut Vm, id: Id, args: &[Value], callee: Value) -> Res Resolved::Missing(f) => { let e = failure_value(vm, DiagnosticKind::named(&f.kind), f.message, f.suggestions); if let (Value::Obj(id), Some(s)) = (e, vm.call_location()) { - vm.host_failure_stack(id, s.offset, s.source.as_ref(), None); + vm.host_failure_stack(id, s.offset(), s.source(), None); } return Err(e); } @@ -955,7 +955,7 @@ fn call_host( let crossed = match crossed { Err(e) => { let site = vm.call_location(); - locate_at(vm, &e, site.as_ref()); + locate_at(vm, &e, site); Err(e) } ok => ok, @@ -1020,13 +1020,7 @@ fn call_host( let call_site = vm.call_location(); let call = vm .host - .call( - call_id, - call_site.map(|s| { - let code = s.source.map_or_else(|| vm.code.clone(), |m| m.code.clone()); - (s.offset, code) - }), - ) + .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(); @@ -1071,26 +1065,19 @@ fn sync_result( Returned::Now(Ok(v)) => { 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.as_ref()))?; + .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_location(); - Err(thrown_value( - vm, - &thrown, - &target.label, - site.as_ref(), - None, - )) + Err(thrown_value(vm, &thrown, &target.label, site, None)) } Returned::Pending(work) => { let site = vm.call_location(); let p = vm.new_promise(); let (label, owner) = (target.label.clone(), target.owner.clone()); - let future_site = site.clone(); let future: BoxFuture<'_, Settlement> = - Box::pin(async move { Settlement::host(work.await, label, owner, future_site) }); + Box::pin(async move { Settlement::host(work.await, label, owner, site) }); let in_flight = InFlight { promise: p, call: call_id, @@ -1255,20 +1242,11 @@ 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.as_ref().map(|s| { - let code = s - .source - .as_ref() - .map_or_else(|| vm.code.clone(), |m| m.code.clone()); - (s.offset, code) - }), - ) + .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)); - let (label, owner, site) = (r.label.clone(), r.owner.clone(), r.site.clone()); + let (label, owner, site) = (r.label.clone(), r.owner.clone(), r.site); let (kind, future): (CallKind, BoxFuture<'static, Settlement>) = match f { Callee::Fn(f) => { let Body::Async(body) = &f.body else { @@ -2716,7 +2694,7 @@ fn import_native(vm: &mut Vm, _this: Value, args: &[Value], _callee: Id) -> Res // The rejection reports the `import()`, as the reference locates it. Err(e) => { let site = vm.call_location(); - locate_at(vm, &e, site.as_ref()); + locate_at(vm, &e, site); vm.reject(p, e) } } @@ -2747,6 +2725,6 @@ 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_location(); - thrown_value(vm, &thrown, &label, site.as_ref(), None) + thrown_value(vm, &thrown, &label, site, None) }) } diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index 89b4a9c2..9494b619 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -54,7 +54,7 @@ mod time; mod value; mod vm; -pub use compiler::{CompileOptions, DEFAULT_MAX_SOURCE_BYTES}; +pub use compiler::DEFAULT_MAX_SOURCE_BYTES; pub use convert::MAX_VALUE_DEPTH_LIMIT; pub use data::Data; pub use diagnostic::{Clock, Diagnostic, DiagnosticKind, Interrupted, Limits}; diff --git a/rust/crates/psychoscript/src/native.rs b/rust/crates/psychoscript/src/native.rs index a62ef285..1aa2f896 100644 --- a/rust/crates/psychoscript/src/native.rs +++ b/rust/crates/psychoscript/src/native.rs @@ -167,7 +167,7 @@ pub fn proto() -> FuncProto { callees: Vec::new(), sites: Vec::new(), text: None, - source: 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 84aff863..f92ef154 100644 --- a/rust/crates/psychoscript/src/object.rs +++ b/rust/crates/psychoscript/src/object.rs @@ -302,8 +302,8 @@ pub struct Failure { pub message: String, /// Source offset of the instruction that raised it, filled in when first thrown. pub offset: Option, - /// Module source `offset` belongs to when raised in a named module (`None` uses `Vm::code`). - pub source: 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 @@ -318,6 +318,7 @@ pub struct Failure { #[derive(Clone, Debug, Default)] pub struct Thrown { pub offset: Option, + pub source: u32, pub trace: Option, } @@ -343,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 d0229fa9..3b5d3ce6 100644 --- a/rust/crates/psychoscript/src/reach.rs +++ b/rust/crates/psychoscript/src/reach.rs @@ -45,12 +45,12 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { } if !measuring { // Built-in code (`Array.fromAsync`, no positions) and dynamically loaded named modules - // (`p.source.is_some()`) intern atoms after the permanent base, so they live by their - // code without double-billing the run's heap limit. + // (`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.is_some()) + .filter(|p| p.pos.is_empty() || p.source() != 0) { for a in p.atoms() { t.atom(a); diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index ea555174..dc5f30fc 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -4,7 +4,7 @@ use std::panic::AssertUnwindSafe; use std::sync::Arc; use crate::bytecode::{ModuleSource, Program}; -use crate::compiler::{self, CompileError, CompileOptions}; +use crate::compiler::{self, CompileError}; use crate::convert; use crate::host::{self, RunHost}; use crate::nesting; @@ -45,7 +45,6 @@ struct CompiledProgram { code: Arc, program: Program, atoms: Strings, - typescript: bool, } impl Compiled { @@ -88,9 +87,9 @@ impl<'a> From<&'a Compiled> for Code<'a> { } } -/// A synchronous named module compiled once off-thread to be merged and executed in any -/// [`Session`](crate::Session) without re-parsing or re-compiling. Cheap to clone, immutable, and -/// `Send + Sync`. +/// 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); @@ -111,6 +110,10 @@ impl CompiledModule { &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) } @@ -125,68 +128,43 @@ impl std::fmt::Debug for CompiledModule { } } -/// Parses and compiles a program with [`CompileOptions`], or returns the compile diagnostic. -pub fn compile_program_with(code: &str, options: &CompileOptions) -> Result { +/// 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 code_arc: Arc = Arc::from(code); - let module_source = options.module_name.as_deref().map(|name| { - Arc::new(ModuleSource { - name: Arc::from(name), - code: code_arc.clone(), - }) - }); - let program = compile_with(code, &mut atoms, options, false, module_source) - .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: code_arc, + code: Arc::from(code), program, atoms, - typescript: options.typescript.unwrap_or(false), }))) } -/// Parses and compiles a synchronous named module once, tagging every function prototype with -/// `ModuleSource { name, code }` and compiling the entry as a synchronous function so `return` -/// produces the module value directly. -pub fn compile_module_with( - code: &str, - name: &str, - options: &CompileOptions, -) -> Result { - compile_module_inner(code, name, options, false) -} - -/// Compiles a synchronous named module while already nested inside a running VM (`native_depth > 0`). -/// On non-wasm targets this compiles on a scoped thread with a fresh stack so deeply nested `require()` -/// chains cannot overflow a small caller stack (e.g. 1 MiB on Windows). -pub(crate) fn compile_module_in_call( +/// 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, - options: &CompileOptions, + max_source_bytes: usize, ) -> Result { - compile_module_inner(code, name, options, true) + compile_module_with_budget(code, name, max_source_bytes, RUN_STACK_BUDGET) + .map_err(|e| compile_diagnostic(code, Some(name), e)) } -fn compile_module_inner( +/// 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, - options: &CompileOptions, - force_off_thread: bool, -) -> Result { + 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), }); - let program = compile_with_stack( - code, - &mut atoms, - options, - true, - Some(source.clone()), - force_off_thread, - ) - .map_err(|e| compile_diagnostic(code, e))?; Ok(CompiledModule(Arc::new(CompiledModuleInner { source, program, @@ -194,9 +172,21 @@ fn compile_module_inner( }))) } -fn compile_diagnostic(code: &str, e: CompileError) -> Diagnostic { +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(), @@ -215,37 +205,24 @@ 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. -#[cfg(test)] +/// 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 { - let opts = CompileOptions::new().max_source_bytes(max_source_bytes); - compile_with(code, atoms, &opts, false, None) + compile_with_budget(code, atoms, max_source_bytes, RUN_STACK_BUDGET, false) } -pub(crate) fn compile_with( +fn compile_with_budget( code: &str, atoms: &mut Strings, - options: &CompileOptions, - sync_module: bool, - module_source: Option>, -) -> Result { - compile_with_stack(code, atoms, options, sync_module, module_source, false) -} - -fn compile_with_stack( - code: &str, - atoms: &mut Strings, - options: &CompileOptions, + max_source_bytes: usize, + budget: usize, sync_module: bool, - module_source: Option>, - force_off_thread: bool, ) -> Result { - let max_source_bytes = options - .max_source_bytes - .unwrap_or(crate::DEFAULT_MAX_SOURCE_BYTES); if code.len() > max_source_bytes { return Err(CompileError { kind: DiagnosticKind::ParseError, @@ -253,21 +230,27 @@ fn compile_with_stack( 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), }; - #[cfg(target_arch = "wasm32")] - let off_thread = { - let _ = force_off_thread; - need > RUN_STACK_BUDGET - }; - #[cfg(not(target_arch = "wasm32"))] - let off_thread = force_off_thread || need > RUN_STACK_BUDGET; - if !off_thread { - return compiler::compile_with(code, atoms, options, sync_module, module_source); + 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 { @@ -291,9 +274,7 @@ fn compile_with_stack( std::thread::scope(|s| { std::thread::Builder::new() .stack_size(stack_size) - .spawn_scoped(s, || { - compiler::compile_with(code, atoms, options, sync_module, module_source) - }) + .spawn_scoped(s, || run_compile(code, atoms)) .map_err(|_| CompileError { kind: DiagnosticKind::ExecutionFailure, message: @@ -338,30 +319,21 @@ pub fn start( code: Code<'_>, options: &ProgramOptions, ) -> Result, Box> { - let setup = rt.setup(); - let (code, mut program, atoms, typescript) = match code { - Code::Compiled(c) => ( - c.0.code.clone(), - c.0.program.clone(), - c.0.atoms.clone(), - c.0.typescript || setup.typescript, - ), + let (code, mut program, atoms) = match code { + Code::Compiled(c) => (c.0.code.clone(), c.0.program.clone(), c.0.atoms.clone()), Code::Source(code) => { let mut atoms = Strings::fresh(); - let opts = CompileOptions::new() - .typescript(setup.typescript) - .max_source_bytes(setup.limits.source_limit()); - match compile_with(code, &mut atoms, &opts, false, None) { - Ok(p) => (Arc::from(code), p, atoms, setup.typescript), - Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))), + 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, None, e)))), } } }; + let setup = rt.setup(); let run = Run::new(options.run_id.clone(), Data::Null); let globals = setup.globals_for(&run); let host = RunHost::new(globals, setup.modules.clone(), setup.translate, run); let mut vm = Vm::new(host, setup.limits, atoms); - vm.typescript = typescript; vm.start_cpu_meter(); vm.setup(); crate::builtins::ensure_program(&mut vm, &program); @@ -396,13 +368,9 @@ pub fn start_for_resume( restored: crate::snapshot::Restored, ) -> Result { let code = restored.code; - let typescript = restored.typescript; let mut atoms = Strings::fresh(); // The run that saved the state accepted its source: it compiles again whatever its size. - let opts = CompileOptions::new() - .typescript(typescript) - .max_source_bytes(code.len()); - let mut program = compile_with(&code, &mut atoms, &opts, false, None).map_err(|_| { + let mut program = compile(&code, &mut atoms, code.len()).map_err(|_| { crate::snapshot::SnapshotError::new( "Source main does not compile in this build, so it can't resume.", ) @@ -418,7 +386,6 @@ pub fn start_for_resume( } let host = RunHost::new(globals, setup.modules.clone(), setup.translate, run); let mut vm = Vm::new(host, restored.limits, atoms); - vm.typescript = typescript; vm.start_cpu_meter(); vm.setup(); crate::builtins::ensure_program(&mut vm, &program); @@ -622,18 +589,16 @@ fn diagnose_text(vm: &mut Vm, e: &Value, code: &str) -> Diagnosed { { let id = *id; if let Some(f) = failure.clone() { - let src_code: &str = match &f.source { - Some(src) => &src.code, - None => code, + 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(|| match (&f.source, location) { - (Some(src), Some((line, col))) => format!("\n at {}:{line}:{col}", src.name), - _ => frame_line(location), - }); + .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}"), @@ -664,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, @@ -694,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}"), @@ -704,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; diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 7e587596..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, CompileOptions, Compiled, CompiledModule, 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. @@ -223,7 +223,6 @@ pub(crate) struct Setup { pub locale: Option>, pub measure_heap: bool, pub offload: bool, - pub typescript: bool, } impl Default for Setup { @@ -237,7 +236,6 @@ impl Default for Setup { locale: None, measure_heap: false, offload: true, - typescript: false, } } } @@ -372,18 +370,6 @@ impl Runtime { self } - /// Enables or disables opt-in erasable TypeScript type-stripping (default: `false`). - /// - /// When enabled, `execute`, `session`, `compile`, `compile_with` (unless overridden), - /// `compile_module`, `compile_module_with` (unless overridden), and `eval_module` accept - /// erasable TypeScript syntax and strip type-only constructs at compile time. Note that - /// TypeScript grammar changes the parse of ambiguous JavaScript expressions such as - /// `f(a < b, c > (d))` (parsed as generic type arguments in TypeScript). - pub fn typescript(mut self, enabled: bool) -> Self { - Arc::make_mut(&mut self.setup).typescript = enabled; - self - } - /// Parses, compiles and runs `code` on the calling thread, blocking on asynchronous host work. An interrupted /// run ends with an `ExecutionFailure` saying so; [`Program::run`] tells the two apart. pub fn execute<'c>(&self, code: impl Into>) -> Outcome { @@ -433,58 +419,16 @@ impl Runtime { /// without doing it again; or the diagnostic a run of it would fail with first (an empty program, a syntax /// error). Unsupported syntax still fails where it runs, as from source. A compiled program runs in any runtime. pub fn compile(&self, code: &str) -> Result { - let opts = CompileOptions::new() - .typescript(self.setup.typescript) - .max_source_bytes(self.setup.limits.source_limit()); - crate::run::compile_program_with(code, &opts) - } - - /// Parses and compiles a program once with explicit [`CompileOptions`] (e.g. a module name for - /// stack traces, opt-in TypeScript stripping, or a custom source size limit). When - /// `options.typescript` or `options.max_source_bytes` is `None`, it inherits from this - /// runtime's configuration. - pub fn compile_with( - &self, - code: &str, - options: &CompileOptions, - ) -> Result { - let mut resolved = options.clone(); - if resolved.typescript.is_none() { - resolved.typescript = Some(self.setup.typescript); - } - if resolved.max_source_bytes.is_none() { - resolved.max_source_bytes = Some(self.setup.limits.source_limit()); - } - crate::run::compile_program_with(code, &resolved) + crate::run::compile_program(code, self.setup.limits.source_limit()) } - /// Parses and compiles a synchronous named module once off-thread into an immutable, `Send + Sync` + /// 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). + /// [`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 { - let opts = CompileOptions::new() - .typescript(self.setup.typescript) - .max_source_bytes(self.setup.limits.source_limit()); - crate::run::compile_module_with(source, name, &opts) - } - - /// [`Runtime::compile_module`] with explicit [`CompileOptions`]. When `options.typescript` or - /// `options.max_source_bytes` is `None`, it inherits from this runtime's configuration. - pub fn compile_module_with( - &self, - source: &str, - name: &str, - options: &CompileOptions, - ) -> Result { - let mut resolved = options.clone(); - if resolved.typescript.is_none() { - resolved.typescript = Some(self.setup.typescript); - } - if resolved.max_source_bytes.is_none() { - resolved.max_source_bytes = Some(self.setup.limits.source_limit()); - } - crate::run::compile_module_with(source, name, &resolved) + 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 diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs index 552f910c..7fb9200d 100644 --- a/rust/crates/psychoscript/src/session.rs +++ b/rust/crates/psychoscript/src/session.rs @@ -12,8 +12,8 @@ use crate::program::Program; use crate::value::Value; use crate::vm::Vm; use crate::{ - Code, CompileOptions, CompiledModule, Data, Outcome, ProgramOptions, Runtime, Snapshot, - SnapshotError, SuspendError, + Code, CompiledModule, Data, Outcome, ProgramOptions, Runtime, Snapshot, SnapshotError, + SuspendError, }; /// What a session's run keeps: the value its top level returned, once it has. @@ -54,7 +54,8 @@ impl Session { } /// Merges a precompiled [`CompiledModule`] into this session and executes it through the session - /// driver without re-compiling. + /// 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. @@ -63,33 +64,26 @@ impl Session { .drive_session(|vm| eval_compiled_in_session(vm, module)) } - /// Compiles `source` as a synchronous named module and executes it in this session. + /// 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 { - if let Some(vm) = self.program.session_vm() - && vm.fatal.is_some() - { + let Some(vm) = self.program.session_vm() else { + return self.program.drive_session(|_| {}); + }; + if vm.fatal.is_some() { return self.program.drive_session(|_| {}); } - let (typescript, max_source_bytes) = self - .program - .session_vm() - .map(|vm| (vm.typescript, vm.limits.source_limit())) - .unwrap_or((false, crate::DEFAULT_MAX_SOURCE_BYTES)); - let opts = CompileOptions::new() - .typescript(typescript) - .max_source_bytes(max_source_bytes); - match crate::run::compile_module_with(source, name, &opts) { + 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: self - .program - .session_vm() - .map(|vm| vm.host.run.metadata()) - .unwrap_or(Data::Null), + metadata, }, } } @@ -504,7 +498,7 @@ impl<'a> HostCtx<'a> { /// 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. + /// 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. @@ -517,21 +511,31 @@ impl<'a> HostCtx<'a> { self.call(Val::of(entry), Val::undefined(), &[]) } - /// Compiles `source` as a synchronous named module and executes it in this live VM. + /// 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 opts = CompileOptions::new() - .typescript(self.vm.typescript) - .max_source_bytes(self.vm.limits.source_limit()); - let compiled = crate::run::compile_module_in_call(source, name, &opts); + 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(d) => { - let raw = d.message_lossy(); - let msg = raw.strip_prefix("SyntaxError: ").unwrap_or(&raw); - return Err(Val::of(self.vm.syntax_error(msg))); + 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) diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index f05c279a..43d1e184 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.")); @@ -564,17 +579,9 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { let state = enc.state(c).map_err(|e| Refusal::Other(e.message))?; let base = vm.snapshot_base; // The run accepted its source when it started: it compiles again whatever its size. - let opts = crate::CompileOptions::new() - .typescript(vm.typescript) - .max_source_bytes(c.code.len()); - let program = crate::run::compile_with( - c.code, - &mut crate::strings::Strings::fresh(), - &opts, - false, - None, - ) - .map_err(|e| Refusal::Other(e.message))?; + let fresh = &mut crate::strings::Strings::fresh(); + let program = + crate::run::compile(c.code, fresh, c.code.len()).map_err(|e| Refusal::Other(e.message))?; let limits = *vm.limits; // Deep metadata is saved flat: as plain JSON, it would pass the nesting limit of the JSON reader in `from_bytes`. let (metadata, metadata_data) = vm.host.run.update_metadata(|m| { @@ -623,9 +630,6 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { if let Some(n) = limits.max_value_depth { header["limits"]["maxValueDepth"] = json!(n); } - if vm.typescript { - header["source"]["typescript"] = json!(true); - } Ok(Snapshot( json!({ "format": FORMAT, "header": header, "state": state }), )) @@ -696,6 +700,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) } @@ -768,7 +785,7 @@ impl Enc<'_> { call.path.as_deref().map(texts), args, call.owner, - call.site.as_ref().map(|s| s.offset) + 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) { @@ -838,7 +855,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 { @@ -847,7 +877,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)]), @@ -1039,9 +1069,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.as_ref().map(|s| s.offset)]) - } + Settlement::Lost(message, site) => json!([p, "lost", message, call_site(site)]), Settlement::Host(h) => { let Settled { result, @@ -1066,7 +1094,7 @@ 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.as_ref().map(|s| s.offset)])); + return Ok(json!([p, "lost", message, call_site(site)])); } json!([ p, @@ -1076,7 +1104,7 @@ impl Enc<'_> { owner, hooked, host_value(data), - site.as_ref().map(|s| s.offset) + call_site(site) ]) } Settlement::Interrupted => json!([p, "interrupted"]), @@ -1178,10 +1206,7 @@ fn hex_bytes(s: &str) -> R> { /// Each object of a fresh run's base, encoded, to see which ones the run changed. fn baseline(vm: &Vm, code: &str) -> R> { let mut atoms = crate::strings::Strings::fresh(); - let opts = crate::CompileOptions::new() - .typescript(vm.typescript) - .max_source_bytes(code.len()); - let program = crate::run::compile_with(code, &mut atoms, &opts, false, None) + let program = crate::run::compile(code, &mut atoms, code.len()) .map_err(|e| SnapshotError::new(e.message))?; let h = &vm.host; let host = host::RunHost::new( @@ -1875,9 +1900,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 { @@ -2295,10 +2363,10 @@ impl Dec<'_> { kind: kind_named(&string(at(e, 0)?)?)?, message: string(at(e, 1)?)?, offset: opt_u32(at(e, 2)?)?, - source: None, + 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" => { @@ -2315,8 +2383,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, @@ -2522,7 +2590,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)?)?, @@ -2545,7 +2613,6 @@ fn pairs(j: &J) -> R> { /// A saved state, checked against this runtime and ready to resume. pub struct Restored { pub code: String, - pub typescript: bool, pub run_id: Option, pub metadata: crate::Data, /// The shape of the host globals it was saved with (`hosts_id`). @@ -2587,10 +2654,6 @@ pub fn header(snapshot: &Snapshot) -> R { }; Ok(Restored { code, - typescript: source - .get("typescript") - .and_then(J::as_bool) - .unwrap_or(false), run_id: field(header, "runId")?.as_str().map(str::to_owned), metadata: match header.get("metadataData") { Some(saved) if !saved.is_null() => data_from(saved)?, @@ -2680,13 +2743,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() { @@ -2699,6 +2816,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 { @@ -2864,6 +2982,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")?; @@ -2889,13 +3010,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| crate::bytecode::CallSite { - offset: s as u32, - source: None, - }); + 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)?; @@ -2904,15 +3019,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| crate::bytecode::CallSite { - offset: s as u32, - source: None, - }), - ), + 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.")), }; @@ -3046,10 +3153,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| crate::bytecode::CallSite { - offset: s as u32, - source: None, - }), + 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 fe5e0eeb..fdc0c200 100644 --- a/rust/crates/psychoscript/src/stack.rs +++ b/rust/crates/psychoscript/src/stack.rs @@ -3,7 +3,6 @@ //! access, so a subclass constructor that sets `this.name` is in the header). Until then the property holds the lines //! alone and has `PENDING_STACK` among its flags; any read formats it (`Vm::fix_stack`), a write replaces it. -use crate::bytecode::ModuleSource; use crate::object::*; use crate::value::{Id, Value}; use crate::vm::{FrameKind, Vm}; @@ -26,21 +25,13 @@ pub(crate) fn same_value(a: &Value, b: &Value) -> bool { } } -fn same_source(a: Option<&ModuleSource>, b: Option<&ModuleSource>) -> bool { - match (a, b) { - (None, None) => true, - (Some(x), Some(y)) => std::ptr::eq(x, y), - _ => false, - } -} - impl Vm { /// The program frames on the stack as `stack` lines, innermost first: a function's by its `name` (or /// ``), the program's own without one, each at the site it is at. Native frames are left out, and with /// `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, 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 @@ -50,7 +41,7 @@ impl Vm { pub(crate) fn stack_trace_at( &mut self, top: Option, - top_source: Option<&ModuleSource>, + top_source: u32, settled: Option, ) -> String { let mut trace = String::new(); @@ -66,11 +57,10 @@ impl Vm { let f = &self.frames[i]; let site = self.frame_site(f); let Some(site) = site else { continue }; - let source = f.func.source.clone(); + let source = f.func.source(); if shown == 0 && let Some(top) = top - && (!same_source(source.as_deref(), top_source) - || !self.frame_encloses(i, top)) + && (source != top_source || !self.frame_encloses(i, top)) { return self.stack_line(top, None, top_source); } @@ -80,12 +70,7 @@ impl Vm { site }; let name = self.frame_name(i); - trace.push_str(&self.stack_line_as( - at, - name.as_deref(), - false, - source.as_deref(), - )); + trace.push_str(&self.stack_line_as(at, name.as_deref(), false, source)); shown += 1; } root = match self.frames.first().map(|f| &f.kind) { @@ -96,16 +81,16 @@ impl Vm { Some(p) => { if let (Some(top), Some(c)) = (top, self.awaiter(p)) && let Some((func, pc, callee)) = self.parked_frame(c) - && same_source(func.source.as_deref(), top_source) + && func.source() == top_source && func.pos.get(pc.wrapping_sub(2)) == Some(&top) { - if func.source.is_some() || 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, - func.source.as_deref(), + func.source(), )); shown += 1; } @@ -125,15 +110,10 @@ impl Vm { break; }; if let Some(&site) = func.pos.get(pc.wrapping_sub(1)) - && (func.source.is_some() || 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, - func.source.as_deref(), - )); + trace.push_str(&self.stack_line_as(site, name.as_deref(), true, func.source())); shown += 1; } } @@ -150,7 +130,7 @@ impl Vm { return None; } let site = f.func.pos.get(f.pc.saturating_sub(1)).copied()?; - (f.func.source.is_some() || 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 @@ -229,12 +209,7 @@ impl Vm { } /// 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: Option<&ModuleSource>, - ) -> String { + pub(crate) fn stack_line(&self, offset: u32, name: Option<&str>, source: u32) -> String { self.stack_line_as(offset, name, false, source) } @@ -245,12 +220,9 @@ impl Vm { offset: u32, name: Option<&str>, awaiting: bool, - source: Option<&ModuleSource>, + source: u32, ) -> String { - let (file, code): (&str, &str) = match source { - Some(src) => (&src.name, &src.code), - None => ("", &self.code), - }; + let (file, code) = self.source_info(source); let (line, column) = crate::run::line_col(code, offset); let at = if awaiting { "async " } else { "" }; match name { @@ -284,13 +256,13 @@ impl Vm { &mut self, id: Id, offset: u32, - source: Option<&std::sync::Arc>, + source: u32, settled: Option, ) { - let line = self.stack_trace_at(Some(offset), source.map(|s| s.as_ref()), settled); + 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.cloned(); + f.source = source; f.trace = Some(line.clone()); } let sk = self.names.stack; @@ -304,13 +276,13 @@ impl Vm { /// A value that is not an Error gets the program's stack there; an Error made with no `stack` lines (a host's) /// gets them as its `stack`. pub(crate) fn see_thrown(&mut self, e: Value) { - let site = self.call_location(); if !matches!(self.thrown.as_deref(), Some((v, _)) if same_value(v, &e)) { - let offset = site.as_ref().map(|s| s.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, }, ))); @@ -319,18 +291,15 @@ impl Vm { return; }; let Some(offset) = t.offset else { return }; - let source = site - .as_ref() - .filter(|s| s.offset == offset) - .and_then(|s| s.source.clone()); + 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, source.as_deref()); + self.locate_stack(id, offset, source); } } _ if t.trace.is_none() => { - let trace = self.stack_trace_at(Some(offset), source.as_deref(), None); + let trace = self.stack_trace_at(Some(offset), source, None); if let Some((_, t)) = self.thrown.as_deref_mut() { t.trace = Some(trace); } @@ -356,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, None, 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, None, 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, }) } @@ -402,20 +373,20 @@ impl Vm { return; } let f = &self.frames[fi]; - let source = f.func.source.clone(); + 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, source.as_deref())) + .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, source: Option<&ModuleSource>) { + pub(crate) fn locate_stack(&mut self, id: Id, offset: u32, source: u32) { self.locate_stack_settled(id, offset, source, None); } @@ -424,7 +395,7 @@ impl Vm { &mut self, id: Id, offset: u32, - source: Option<&ModuleSource>, + source: u32, settled: Option, ) { let sk = self.names.stack; diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 83dd8e06..f30c92c4 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -368,8 +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>, - /// Whether this VM's runtime enables opt-in erasable TypeScript type-stripping for `eval_module`. - pub(crate) typescript: bool, + /// 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 { @@ -518,7 +527,7 @@ impl Vm { slice: None, console: None, session: None, - typescript: false, + loaded_code: None, } } @@ -549,6 +558,80 @@ 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`. @@ -563,7 +646,7 @@ impl Vm { // 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. `Session::set_global("console", ...)`, `"Map"`, `"require"`). + // `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 = @@ -581,7 +664,9 @@ impl Vm { } for &(k, v) in &saved_globals { self.gc_shade_atom(k); - self.gc_shade(v); + if self.heap.marking { + self.gc_shade_value(v); + } self.global_map.insert(k, v); } for &a in &program.globals { @@ -600,42 +685,119 @@ impl Vm { // 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), Some(const_base), Some(global_base), Some(template_base)) = ( - u32::try_from(self.protos.len()).ok(), - u32::try_from(self.consts.len()).ok(), - u32::try_from(self.globals.len()).ok(), - u32::try_from(self.templates.len()).ok(), - ) else { + 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.")); }; - let fits = u32::try_from(program.protos.len()) - .ok() - .and_then(|n| proto_base.checked_add(n)) - .is_some() - && u32::try_from(program.consts.len()) - .ok() - .and_then(|n| const_base.checked_add(n)) - .is_some() - && u32::try_from(program.globals.len()) - .ok() - .and_then(|n| global_base.checked_add(n)) - .is_some() - && u32::try_from(program.templates.len()) - .ok() - .and_then(|n| template_base.checked_add(n)) - .is_some(); - if !fits { - return Err(self.range_error("Module exceeds VM bytecode table capacity.")); - } if self.atoms.bufs.len() >= MAX_STRINGS { - self.strings_full(); - if self.fatal.is_some() { - return Err(Value::Undef); - } + 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 { @@ -644,22 +806,27 @@ impl Vm { if let Some(&mapped) = atom_cache.get(&a) { return mapped; } - if vm.atoms.bufs.len() >= MAX_STRINGS { - vm.strings_full(); + if live && vm.atoms.bufs.len() >= MAX_STRINGS { + vm.out_of_memory(); } let mapped = vm.atoms.intern(module_atoms.text(a)); - vm.gc_shade_atom(mapped); + if live { + vm.gc_shade_atom(mapped); + } atom_cache.insert(a, mapped); mapped }; - // Append remapped constants and materialize BigInt constants. + // 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()); - self.gc_shade(sv); + if live && self.heap.marking { + self.gc_shade_value(sv); + } sv } other => other, @@ -667,9 +834,7 @@ impl Vm { self.consts.push(mapped); } for (i, n) in &program.bigints { - let bv = self.big_val(n.clone()); - self.gc_shade(bv); - self.consts[(const_base + *i) as usize] = bv; + pending_bigints.push(((const_base + *i) as usize, n.clone())); } // Append remapped tagged template sites. @@ -683,7 +848,9 @@ impl Vm { opt.map(|v| match v { Value::Str(s) => { let sv = self.string_val(module_atoms.get(s).to_owned()); - self.gc_shade(sv); + if live && self.heap.marking { + self.gc_shade_value(sv); + } sv } other => other, @@ -696,7 +863,9 @@ impl Vm { .map(|&v| match v { Value::Str(s) => { let sv = self.string_val(module_atoms.get(s).to_owned()); - self.gc_shade(sv); + if live && self.heap.marking { + self.gc_shade_value(sv); + } sv } other => other, @@ -712,22 +881,32 @@ impl Vm { self.globals.reserve(program.globals.len()); for &a in &program.globals { let mapped = remap_atom(self, a); - let v = self - .global_map - .get(&mapped) - .copied() - .unwrap_or(Value::Uninit); - self.gc_shade(v); - self.gc_shade_atom(mapped); + 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, @@ -737,16 +916,12 @@ impl Vm { template_base, &mut |a| remap_atom(self, a), ) { - return Err(self.range_error("Module exceeds VM bytecode table capacity.")); + return false; } } self.protos.push(Arc::new(p)); } - - if self.fatal.is_some() { - return Err(Value::Undef); - } - Ok(proto_base as usize) + true } // ---------- allocation ---------- @@ -952,7 +1127,7 @@ impl Vm { kind, message: msg.to_owned(), offset: None, - source: None, + source: 0, site: Default::default(), host: false, trace: None, @@ -2144,10 +2319,13 @@ 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 { - self.call_location().map(|s| s.offset) + 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 @@ -2155,20 +2333,24 @@ impl Vm { .rev() .find(|f| !matches!(f.kind, FrameKind::Native(..)))?; let offset = frame.func.pos.get(frame.pc.wrapping_sub(1)).copied()?; - if frame.func.source.is_some() { - return Some(crate::bytecode::CallSite { + if self.program.is_none() { + return Some(crate::bytecode::CallSite::from_tag( + frame.func.source_tag, offset, - source: frame.func.source.clone(), - }); + )); } - let offset = match self.program { - Some(_) if !self.in_program(offset) => self.program_site().unwrap_or(offset), - _ => 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 }; - Some(crate::bytecode::CallSite { - offset, - source: None, - }) + crate::bytecode::CallSite::new(offset, source) } /// Whether `offset` is in the program's own lines (`Runtime::program_lines`; every offset without them). @@ -2182,7 +2364,7 @@ impl Vm { self.frames .iter() .rev() - .filter(|f| !matches!(f.kind, FrameKind::Native(..)) && f.func.source.is_none()) + .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)) } @@ -2334,19 +2516,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.is_none() + && 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, 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: None, + source: 0, site: Default::default(), host: false, trace, @@ -2367,7 +2549,7 @@ 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.clone(); + 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. @@ -2384,11 +2566,11 @@ impl Vm { && let Kind::Error(Some(f)) = &mut self.heap[*id as usize].kind { f.offset = Some(o as u32); - f.source = None; + 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.is_none() + && f.source == 0 && let Some(o) = f.offset && !self.in_program(o) && let Some(p) = self.program_site() @@ -2401,8 +2583,8 @@ impl Vm { }; if let Some(o) = f.offset { let id = *id; - let source = f.source.clone(); - self.locate_stack(id, o, source.as_deref()); + 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); +} diff --git a/rust/crates/psychoscript/tests/modules_and_ts.rs b/rust/crates/psychoscript/tests/modules_and_ts.rs deleted file mode 100644 index 93accfff..00000000 --- a/rust/crates/psychoscript/tests/modules_and_ts.rs +++ /dev/null @@ -1,991 +0,0 @@ -use std::collections::HashMap; -use std::sync::{Arc, Mutex}; - -use psychoscript::{ - CompileOptions, CompiledModule, Data, DiagnosticKind, HostError, HostFunction, HostValue, - ProgramOptions, RunOutcome, Runtime, Val, 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_with(init_src, &CompileOptions::new().module_name("init.js")) - .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 init.js 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 (init.js:4:9)"), - "missing init 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. - 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}"); - - // 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_size_options() { - 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"); - - // Repeated calls run gc_idle() between turns and incremental GC during churn, verifying - // dynamically loaded module atoms and constants remain rooted. - for _ in 0..3 { - let v = sess - .call("churnAndRead", &[]) - .json() - .expect("call after GC"); - assert_eq!(v, serde_json::json!("hello-dynamic-gc")); - } - - // Session::eval_module convenience helper works directly and returns ParseError on bad syntax - // without poisoning the session. - 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); - // Session remains healthy after a compile error in eval_module. - assert_eq!( - sess.call("churnAndRead", &[]) - .json() - .expect("session still healthy"), - serde_json::json!("hello-dynamic-gc") - ); - - // Synchronous module rejects top-level await cleanly. - 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); - - // Default 256 KiB source size cap stays intact, while CompileOptions::max_source_bytes overrides it. - let huge = format!( - "const pad = '{}'; return pad.length;", - "a".repeat(260 * 1024) - ); - let too_big = rt - .compile(&huge) - .expect_err("default 256 KiB cap must reject >256 KiB source"); - assert_eq!(too_big.kind, DiagnosticKind::ParseError); - - let ok_compiled = rt - .compile_with(&huge, &CompileOptions::new().max_source_bytes(512 * 1024)) - .expect("custom max_source_bytes should accept >256 KiB source"); - let outcome = rt.execute(&ok_compiled); - assert_eq!( - outcome.json().expect("run large compiled"), - serde_json::json!(260 * 1024) - ); -} - -#[test] -fn opt_in_typescript_stripping_works_and_default_js_mode_rejects_ts() { - // 1. Default Runtime (typescript: false) still rejects TypeScript syntax. - let js_rt = Runtime::make(); - for snippet in [ - "const x: number = 1; return x;", - "type Foo = number; return 1;", - "interface Bar { a: string } return 1;", - "const v = 1 as number; return v;", - ] { - let res = js_rt.compile(snippet); - assert!( - res.is_err(), - "typescript: false should reject TS syntax: {snippet}" - ); - assert_eq!(res.unwrap_err().kind, DiagnosticKind::ParseError); - } - - // 2. Opt-in TypeScript runtime strips erasable TS syntax cleanly. - let ts_rt = Runtime::make() - .typescript(true) - .globals(|_| vec![("hostBase", HostValue::Number(100.0))]); - - let ts_program = r#" - import type { Ghost } from "ghost-types"; - export type LocalId = string | number; - export interface Boxed { - value: T; - } - export type * from "ghost-types"; - - declare const hostBase: number; - declare function unusedAmbient(x: number): void; - declare class AmbientOnly { x: number } - - type Pair = { first: A; second: B }; - interface Named { name: string } - - function add(a: number, b: number): number; - function add(a: string, b: string): string; - function add(a: any, b: any): any { - return a + b; - } - - function withThis(this: { n: number }, delta?: number): number { - return this.n + (delta ?? 1); - } - - const identity = (x: T): T => x; - const numIdentity = identity; - - class Counter implements Boxed { - [key: string]: any; - declare ghostField: string; - readonly value: T; - private step: number = 2; - - constructor(initial: T); - constructor(initial: T) { - this.value = initial; - } - - inc(times?: number): number; - inc(times: number = 1): number { - return (this.value as number) + this.step * times; - } - } - - const pair = { first: hostBase, second: 23 } satisfies Pair; - const maybeStr: string | null = "hello"; - const len = maybeStr!.length; - const castVal = 7; - const box = { n: 10 }; - const holder: { x?: number } = {}; - holder.x! = 9; - const counter = new Counter(5); - - return { - sum: add(pair.first, pair.second), - concat: add("a", "b"), - thisRes: withThis.call(box, 4), - idRes: numIdentity(42), - len, - castVal, - assigned: holder.x, - counterInc: counter.inc(3), - }; - "#; - - let outcome = ts_rt.execute(ts_program); - let val = outcome.json().expect("TS program should execute"); - assert_eq!( - val, - serde_json::json!({ - "sum": 123, - "concat": "ab", - "thisRes": 14, - "idRes": 42, - "len": 5, - "castVal": 7, - "assigned": 9, - "counterInc": 11, - }) - ); - - // 3. TypeScript precompiled module with accurate .ts stack traces. - let ts_mod = ts_rt - .compile_module( - r#" -type Input = { x: number }; -function compute(v: Input): number { - throw new Error("ts boom: " + v.x); -} -return { compute }; -"#, - "math.ts", - ) - .expect("compile_module TS"); - - let ts_sess_rt = Runtime::make().typescript(true).globals({ - let ts_mod = ts_mod.clone(); - move |_| { - let ts_mod = ts_mod.clone(); - vec![ - ( - "loadMath", - HostValue::Function(HostFunction::direct(move |ctx, _| { - ctx.eval_compiled(&ts_mod) - })), - ), - ( - "loadInlineTs", - HostValue::Function(HostFunction::direct(|ctx, _| { - ctx.eval_module( - "const greet = (who: string): string => 'hello ' + who; return greet('ts');", - "inline.ts", - ) - })), - ), - ] - } - }); - - let (mut sess, init) = ts_sess_rt.session( - "const m = loadMath(); return { run: (x: number) => m.compute({ x }), inline: () => loadInlineTs() };", - &ProgramOptions::new(), - ); - init.json().expect("TS session"); - let err = sess - .call("run", &[Data::from(serde_json::json!(99))]) - .result - .expect_err("expected TS runtime error"); - let err_msg = err.message_lossy(); - assert!( - err_msg.contains("at compute (math.ts:4:11)"), - "expected math.ts:4:11 frame, got: {err_msg}" - ); - - // 4. HostCtx::eval_module inherits session's typescript setting. - assert_eq!( - sess.call("inline", &[]) - .json() - .expect("HostCtx::eval_module TS"), - serde_json::json!("hello ts") - ); - - // 5. Non-erasable TypeScript constructs fail with clear ParseError. - for (label, bad_ts) in [ - ("enum", "enum Color { Red, Green } return Color.Red;"), - ("const enum", "const enum Dir { Up = 1 } return Dir.Up;"), - ( - "namespace", - "namespace Foo { export const x = 1; } return Foo.x;", - ), - ( - "parameter property", - "class A { constructor(public x: number) {} } return new A(1).x;", - ), - ( - "readonly parameter property", - "class A { constructor(readonly x: number) {} } return new A(1).x;", - ), - ("import =", "import x = require('foo'); return x;"), - ("export =", "const x = 1; export = x;"), - ] { - let err = ts_rt - .compile(bad_ts) - .expect_err(&format!("{label} must be rejected")); - assert_eq!( - err.kind, - DiagnosticKind::ParseError, - "{label} should return ParseError" - ); - let msg = err.message_lossy(); - assert!( - msg.contains("erasable TypeScript"), - "{label} error should mention erasable TypeScript, got: {msg}" - ); - } -} - -#[test] -fn ts_wrappers_preserve_this_delete_typeof_compound_assign_update_and_ambient_syntax() { - let ts_rt = Runtime::make().typescript(true); - - // 1. Call & tagged-template `this` preservation, plus `(0, o.m)()` still dropping `this`. - let calls_out = ts_rt - .execute( - r#" - class Base { - tag: string = "base"; - who(): string { return this.tag; } - } - class Sub extends Base { - tag: string = "sub"; - callSuper(): string { return super.who!(); } - } - const o: any = { - tag: "obj", - m(): string { return this ? this.tag : "undef"; }, - t(parts: TemplateStringsArray, v: number): string { - return this.tag + ":" + parts[0] + v; - }, - }; - const maybe: any = o; - const nil: any = null; - const indirect = (0, o.m)(); - return { - bang: o.m!(), - asAny: (o.m as any)(), - optBang: maybe?.m!(), - optNil: nil?.m!() === undefined, - superBang: new Sub().callSuper(), - tagged: o.t!`v=${7}`, - indirect, - }; - "#, - ) - .json() - .expect("TS call/tagged-template preservation"); - assert_eq!( - calls_out, - serde_json::json!({ - "bang": "obj", - "asAny": "obj", - "optBang": "obj", - "optNil": true, - "superBang": "sub", - "tagged": "obj:v=7", - "indirect": "undef", - }) - ); - - // 2. delete with TS wrappers and optional chaining. - let del_out = ts_rt - .execute( - r#" - const o: any = { a: 1, b: 2, c: 3 }; - const nil: any = null; - const d1 = delete o.a!; - const d2 = delete (o.b as any); - const d3 = delete o?.c!; - const d4 = delete nil?.x!; - return { - d1, d2, d3, d4, - hasA: "a" in o, - hasB: "b" in o, - hasC: "c" in o, - }; - "#, - ) - .json() - .expect("TS delete"); - assert_eq!( - del_out, - serde_json::json!({ - "d1": true, - "d2": true, - "d3": true, - "d4": true, - "hasA": false, - "hasB": false, - "hasC": false, - }) - ); - - // 3. Compound/logical assignments, update expressions, and super targets with TS wrappers. - let mut_out = ts_rt - .execute( - r#" - let x: number | null = 10; - (x as number) += 2; - const pre = ++x!; - - const o: any = { x: 5, c: 20 }; - o.x! += 1; - o.y! ??= 99; - o.x! ??= 777; - const post = o.c!++; - - class Parent { - _v: number = 0; - get val(): number { return this._v; } - set val(v: number) { this._v = v; } - } - class Child extends Parent { - run(): number { - super.val! = 3; - super.val! += 4; - return this._v; - } - forSuper(): string { - try { - for (super.val! of [1]) {} - return "no-throw"; - } catch (e: any) { - return e.name; - } - } - } - const ch = new Child(); - return { - x, - pre, - ox: o.x, - oy: o.y, - oc: o.c, - post, - superVal: ch.run(), - forSuper: ch.forSuper(), - }; - "#, - ) - .json() - .expect("TS compound/update/super"); - assert_eq!( - mut_out, - serde_json::json!({ - "x": 13, - "pre": 13, - "ox": 6, - "oy": 99, - "oc": 21, - "post": 20, - "superVal": 7, - "forSuper": "SyntaxError", - }) - ); - - // 4. typeof with TS wrappers on undeclared globals. - let typeof_out = ts_rt - .execute( - r#" - return [typeof undeclaredVar!, typeof (undeclaredVar as any)]; - "#, - ) - .json() - .expect("TS typeof"); - assert_eq!(typeof_out, serde_json::json!(["undefined", "undefined"])); - - // 5. Ambient/type-only TS edge cases: export {}, export default interface, declare enum, - // declare class, declare global, abstract accessor. - let ambient_out = ts_rt - .execute( - r#" - export {}; - export default interface DefaultIface { id: string } - declare enum ExternalStatus { Ok = 1, Fail = 2 } - declare class ExternalClass { - readonly x: number; - constructor(x: number); - } - declare global { - enum GlobalAmbientEnum { A } - } - abstract class AbstractHolder { - abstract accessor label: string; - ping(): string { return "ok"; } - } - class ConcreteHolder extends AbstractHolder { - getLabel(): string { return this.ping(); } - } - return new ConcreteHolder().getLabel(); - "#, - ) - .json() - .expect("TS ambient & type-only edge cases"); - assert_eq!(ambient_out, serde_json::json!("ok")); - - // 6. CompileOptions::typescript = None inherits Runtime::typescript(true). - let inherited = ts_rt - .compile_with( - "const n: number = 41; return n + 1;", - &CompileOptions::new().module_name("inherited.ts"), - ) - .expect("compile_with should inherit Runtime::typescript(true)"); - assert_eq!( - ts_rt.execute(&inherited).json().unwrap(), - serde_json::json!(42) - ); - - let overridden = ts_rt.compile_with( - "const n: number = 41; return n + 1;", - &CompileOptions::new().typescript(false), - ); - assert!( - overridden.is_err(), - "explicit CompileOptions::typescript(false) must override Runtime::typescript(true)" - ); -} - -#[test] -fn typescript_program_suspends_and_resumes_via_snapshot() { - let ts_code = r#" - type Acc = { total: number }; - const state: Acc = { total: 0 }; - for (let i: number = 0; i < 2_000_000; i++) { - state.total! = ((state.total as number) + i) % 1_000_003; - } - return state.total; - "#; - - let rt = Runtime::make().typescript(true); - let expected = rt.execute(ts_code).json().expect("baseline TS run"); - let prog = rt.program(ts_code, &ProgramOptions::new()); - let suspender = prog.suspender(); - let (outcome, answer) = std::thread::scope(|s| { - let h = s.spawn(move || suspender.suspend(None)); - std::thread::sleep(std::time::Duration::from_millis(5)); - ( - prog.run_resumable().expect("run_resumable"), - h.join().unwrap(), - ) - }); - let suspended = match outcome { - RunOutcome::Suspended(s) => s, - RunOutcome::Done(o) => panic!("expected suspension, got complete: {:?}", o.result), - }; - assert!(matches!( - answer.expect("suspend answer"), - RunOutcome::Suspended(_) - )); - - let bytes = to_bytes(&suspended.state); - let decoded = from_bytes(&bytes).expect("from_bytes"); - let resumed = rt.resume(&decoded).expect("resume TS snapshot"); - let final_outcome = match resumed.run_resumable().expect("run resumed TS") { - RunOutcome::Done(o) => o, - RunOutcome::Suspended(_) => panic!("unexpected second suspend"), - }; - assert_eq!(final_outcome.json().expect("resumed result"), expected); -} - -#[test] -fn load_module_preserves_custom_globals_under_lazy_builtins_and_gc_stress() { - let compiler_rt = Runtime::make(); - // Module references `console`, `Map`, `URL`, `Uint8Array`, and `Set` (triggering lazy groups). - 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"); - - // Host overrides `console` (referenced at init) and `Map` (NOT referenced at init) via - // Runtime::globals; neither may be clobbered when loading a module that triggers lazy built-ins. - 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) - })), - ), - ( - "noop", - HostValue::Function(HostFunction::direct(|_, _| Ok(Val::undefined()))), - ), - ] - } - }); - - let (mut sess, init) = rt.session( - "const caller = loadCaller(); return { broken: () => loadBroken(), invoke: () => caller.invokeHost() };", - &ProgramOptions::new(), - ); - init.json().expect("session init"); - - // 1. HostCtx::eval_module syntax error must NOT double-prefix "SyntaxError: SyntaxError: ...". - 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}" - ); - - // 2. Host call inside a named module resolves Call::location() and Diagnostic.location against - // that module's source (line 3, col 5 in caller.js, NOT init.js). - 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}" - ); -}