Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions rust/crates/psychoscript/src/builtins/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,8 +437,9 @@ fn array_from_async(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res
let fp = vm.realm.async_function_proto;
// Its `fields` hold where the program called it, where its failures point (see `Vm::locate`).
let origin = vm
.call_offset()
.map_or(Value::Undef, |o| Value::Num(o as f64));
.call_location()
.filter(|s| s.is_program())
.map_or(Value::Undef, |s| Value::Num(s.offset() as f64));
let f = vm.alloc(Obj::new(
Some(fp),
Kind::Closure(Box::new(Closure {
Expand Down Expand Up @@ -520,6 +521,7 @@ pub(crate) fn from_async_code(vm: &mut Vm, live: bool) -> Option<usize> {
vm.global_names.push(a);
vm.globals.push(v);
}
vm.record_from_async();
at
}

Expand Down
4 changes: 3 additions & 1 deletion rust/crates/psychoscript/src/builtins/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

Expand Down
10 changes: 6 additions & 4 deletions rust/crates/psychoscript/src/builtins/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1048,11 +1048,13 @@ fn function_to_string(vm: &mut Vm, this: Value, _: &[Value], _: Id) -> Res {
let Some(id) = this.as_obj() else {
return Err(vm.type_error("Function.prototype.toString called on incompatible receiver."));
};
let span = match &vm.heap[id as usize].kind {
Kind::Closure(c) => c.proto.text,
_ => None,
let (span, source) = match &vm.heap[id as usize].kind {
Kind::Closure(c) => (c.proto.text, c.proto.source()),
_ => (None, 0),
};
if let Some(text) = span.and_then(|[start, end]| vm.code.get(start as usize..end as usize)) {
if let Some(text) =
span.and_then(|[start, end]| vm.source_code(source).get(start as usize..end as usize))
{
let text = text.to_owned();
return Ok(vm.string_val(text));
}
Expand Down
251 changes: 251 additions & 0 deletions rust/crates/psychoscript/src/bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,248 @@ pub enum Capture {
pub const CLASS_BASE: u8 = 1;
pub const CLASS_DERIVED: u8 = 2;

/// Per-module source metadata attached to [`FuncProto`]s compiled as named modules.
#[derive(Clone, Debug)]
pub struct ModuleSource {
pub name: Arc<str>,
pub code: Arc<str>,
}

/// Source tag for `Vm::code` (`source == 0`), stored as `1` so `Option<CallSite>` uses niche `0`
/// and stays 8 bytes with `offset` uninitialized on `None` (matching `Option<u32>` 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<CallSite>` is 8 bytes, identical to `Option<u32>`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct CallSite {
pub(crate) tag: std::num::NonZeroU32,
pub(crate) offset: u32,
}

impl CallSite {
#[inline(always)]
pub(crate) fn new(offset: u32, source: u32) -> Self {
Self {
tag: std::num::NonZeroU32::new(source.saturating_add(1)).unwrap_or(PROGRAM_SOURCE_TAG),
offset,
}
}

#[inline(always)]
pub(crate) fn from_tag(tag: std::num::NonZeroU32, offset: u32) -> Self {
Self { tag, offset }
}

#[inline(always)]
pub(crate) fn is_program(self) -> bool {
self.tag == PROGRAM_SOURCE_TAG
}

#[inline(always)]
pub(crate) fn offset(self) -> u32 {
self.offset
}

#[inline(always)]
pub(crate) fn source(self) -> u32 {
self.tag.get() - 1
}
}

/// Rebases table indices and remaps interned atoms in a single instruction when merging a
/// precompiled module into a live VM. Returns `false` on `u32` table index overflow.
///
/// Intentionally exhaustive (no wildcard arm): adding a new [`Op`] variant forces classification
/// here so proto/const/global/template/atom operands can never be silently corrupted.
pub(crate) fn rebase_op(
op: &mut Op,
proto_base: u32,
const_base: u32,
global_base: u32,
template_base: u32,
remap_atom: &mut impl FnMut(Atom) -> Atom,
) -> bool {
match op {
// Proto index
Op::Closure(i) => {
let Some(next) = i.checked_add(proto_base) else {
return false;
};
*i = next;
}
// Constant pool index
Op::Const(i)
| Op::ThrowType(i)
| Op::ThrowUnsupported(i)
| Op::ThrowSyntax(i)
| Op::ThrowRange(i)
| Op::ThrowReference(i) => {
let Some(next) = i.checked_add(const_base) else {
return false;
};
*i = next;
}
// Global slot index
Op::GetGlobal(i) | Op::TypeofGlobal(i) => {
let Some(next) = i.checked_add(global_base) else {
return false;
};
*i = next;
}
// Tagged template site index
Op::Template(i) => {
let Some(next) = i.checked_add(template_base) else {
return false;
};
*i = next;
}
// Interned property/binding name atoms
Op::GetLocalChk(_, a)
| Op::GetCellChk(_, a)
| Op::GetUpvalChk(_, a)
| Op::ThrowConst(a)
| Op::ThrowRef(a)
| Op::GetProp(a)
| Op::SetProp(a)
| Op::DestructProp(a)
| Op::GetPropW(a)
| Op::GetMethod(a)
| Op::DelProp(a)
| Op::DefineField(a)
| Op::DefineAccessor(a, _)
| Op::DefineMethod(a, _)
| Op::GetSuper(a, _)
| Op::PutSuper(a, _)
| Op::DefineClassField(a, _) => *a = remap_atom(*a),
// Instructions carrying no table indices or atoms
Op::Nop
| Op::Pop
| Op::Dup
| Op::Dup2
| Op::Swap
| Op::Rot3
| Op::Rot3Back
| Op::Undef
| Op::Null
| Op::True
| Op::False
| Op::Uninit
| Op::Int(_)
| Op::GetLocal(_)
| Op::GetLocal2(_, _)
| Op::SetLocal(_)
| Op::NewCell(_)
| Op::GetCell(_)
| Op::SetCell(_)
| Op::GetUpval(_)
| Op::SetUpval(_)
| Op::This
| Op::Callee
| Op::Arguments
| Op::Rest(_)
| Op::GetElem
| Op::SetElem
| Op::DestructElem
| Op::WriteKey
| Op::DelElem
| Op::In
| Op::InstanceOf
| Op::DefineElem
| Op::DefineAccessorElem(_)
| Op::NameByKey(_)
| Op::Class(_)
| Op::SetFields
| Op::InitFields
| Op::InitStatic
| Op::SuperCall(_, _)
| Op::SuperBind
| Op::SetHome(_)
| Op::Home
| Op::CtorReturn(_)
| Op::NewObject(_)
| Op::NewArray(_)
| Op::ArrayPush
| Op::ArraySpread
| Op::ObjectSpread
| Op::ObjRest(_)
| Op::RequireCoercible
| Op::ToKey
| Op::Add
| Op::Sub
| Op::Mul
| Op::Div
| Op::Mod
| Op::Pow
| Op::BitAnd
| Op::BitOr
| Op::BitXor
| Op::Shl
| Op::Shr
| Op::UShr
| Op::Eq
| Op::Ne
| Op::StrictEq
| Op::StrictNe
| Op::Lt
| Op::Le
| Op::Gt
| Op::Ge
| Op::ArithI(_, _)
| Op::Neg
| Op::ToNumber
| Op::ToNumeric
| Op::Not
| Op::BitNot
| Op::Typeof
| Op::RegExp
| Op::Inc
| Op::Dec
| Op::ToStr
| Op::Concat(_)
| Op::AddLocal(_)
| Op::IncLocal(_)
| Op::Jump(_)
| Op::JumpIfFalse(_)
| Op::JumpIfTrue(_)
| Op::JumpUnless(_, _)
| Op::JumpUnlessI(_, _, _)
| Op::JumpIfFalseKeep(_)
| Op::JumpIfTrueKeep(_)
| Op::JumpIfNotNullishKeep(_)
| Op::JumpIfNotUndef(_)
| Op::OptChain(_)
| Op::OptCall(_)
| Op::Call(_)
| Op::CallSpread
| Op::New(_)
| Op::NewSpread
| Op::Return
| Op::GeneratorStart
| Op::Await
| Op::Yield(_)
| Op::YieldDrop(_)
| Op::YieldStar(_)
| Op::Throw
| Op::PushCatch(_)
| Op::PushFinally(_)
| Op::PopTry
| Op::GetIter(_, _)
| Op::IterNext(_, _)
| Op::DelegateCall(_, _, _)
| Op::DelegateResult(_, _)
| Op::GetAsyncIter(_, _)
| Op::AsyncClose(_, _)
| Op::CheckObject
| Op::IterStep(_)
| Op::IterRest(_)
| Op::IterClose(_)
| Op::IterCloseQuiet(_)
| Op::ForIn(_) => {}
}
true
}

#[derive(Clone, Debug)]
pub struct FuncProto {
pub name: Atom,
Expand All @@ -305,6 +547,8 @@ pub struct FuncProto {
pub is_generator: bool,
pub is_arrow: bool,
pub is_program: bool,
/// Top-level entry prototype of a synchronous [`CompiledModule`](crate::CompiledModule).
pub(crate) is_module_entry: bool,
/// A class constructor: `CLASS_BASE` or `CLASS_DERIVED`, else 0. Only `new` may call it.
pub class: u8,
/// An arrow that reads its method's home object (`super`): it takes it when it is made.
Expand All @@ -323,9 +567,16 @@ pub struct FuncProto {
/// Where the function's source text starts and ends in the program, as `Function.prototype.toString` returns
/// it; `None` for built-in or compiler-made code.
pub text: Option<[u32; 2]>,
/// Loaded module source tag (`1` = `Vm::code`, `source + 1` for a loaded module).
pub(crate) source_tag: std::num::NonZeroU32,
}

impl FuncProto {
/// Loaded module source index (`0` = `Vm::code`, `1..` = 1-based index into `Vm::loaded_code`).
#[inline(always)]
pub(crate) fn source(&self) -> u32 {
self.source_tag.get() - 1
}
/// The atoms the function's code names: its own name, and the keys and binding names of its instructions.
pub fn atoms(&self) -> impl Iterator<Item = Atom> + '_ {
std::iter::once(self.name).chain(self.code.iter().filter_map(|op| match *op {
Expand Down
8 changes: 8 additions & 0 deletions rust/crates/psychoscript/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1157,6 +1157,14 @@ impl Vm {
}
}

/// Shades an atom stored into VM root tables during an active GC cycle.
#[inline]
pub(crate) fn gc_shade_atom(&mut self, a: Atom) {
if self.gc.phase != Phase::Idle {
self.atoms.shade_atom(a);
}
}

/// A new closure cell at its limit, as `gc_alloc` does for objects.
#[cold]
#[inline(never)]
Expand Down
Loading