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
4 changes: 3 additions & 1 deletion rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ Only Rust has:
- Located host errors: [`HostError::located`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs) (`HostValue::Located`), caught as a standard error at the call, with the host error's own fields.
- The program's own lines: [`Runtime::program_lines`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs); an error raised in the host's code around them (a prelude), or by a host function called from there, is located at the nearest frame of the program, as is [`Call::location`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs).
- Always-on typed arrays: `ArrayBuffer` and every standard typed array besides Uint8Array, as [`HostValue::TypedArray`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs): lent without a copy to sync host functions, copied for async and durable ones.
- Direct host functions: [`HostFunction::direct`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/session.rs) gets the program's own values, with no copy, through the call's `HostCtx` (read, write and call as the program does: getters and setters run, frozen objects refuse; a typed array's bytes in place) and returns its value or what it throws. The values are the call's only: nothing collects the heap during a host call, and a `Val` can't outlive it. It is a synchronous host call (its time is the host's, a suspend is refused while it runs), and runs where the run computes, which for a run driven as a future may be its worker.
- Sessions: [`Runtime::session`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/session.rs) runs a program whose top level returns an object of functions and keeps the run; `Session::call(name, args)` runs one as a run runs (its limits from the call, async host calls driven, its value crossing back as an `Outcome`), with the program's state kept from call to call. A failure that ends a run leaves the session failed. `Session::save` gives the state between calls as a suspended run's, and `Runtime::restore_session` continues it, also in another process of the same build.
- Lazy built-in groups: [`LAZY`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/builtins/mod.rs) sets up `RegExp`, `Date`, the typed arrays and the other groups only when a program uses them.
- Optional `locale` feature (`default = ["locale"]`): disable it with `default-features = false` to drop ICU4X's compiled CLDR tables (~5 MB) in lean embedded or `wasm32` builds. With `locale` off and no provider of the host's (below), `locales` and `options` are ignored: `Date.prototype.toLocale*String` returns UTC ISO-8601 strings (`YYYY-MM-DDTHH:mm:ss.sssZ`, date slice, or time slice, or `"Invalid Date"`), `Number`/`BigInt.prototype.toLocaleString` use decimal `toString`, and `String.prototype.localeCompare` compares NFC-normalized UTF-16 code units.
- A pluggable locale provider: [`Runtime::locale`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) sets the [`LocaleProvider`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/locale.rs) (`Send + Sync`) that formats dates for `toLocale*String`, numbers and BigInts for `toLocaleString`, and compares strings for `localeCompare`, in place of the default: `IcuLocale` with `locale`, `FallbackLocale` (the fallbacks above) without it. PsychoScript still reads and validates the locales and options and throws their errors, as with `locale`, so the provider gets the locale tags and the resolved options as plain Rust data and only formats or compares; it checks `timeZone` itself (PsychoScript's zone data checks it only for the defaults), and an `Err` it returns, for what only it can know, is thrown as a `RangeError`. It is host configuration like the globals, not saved with a run. A `wasm32` host without `locale` can hand them to the browser's `Intl` through `wasm-bindgen` (`js_sys::Intl::DateTimeFormat`, `NumberFormat`, `Collator`, or `toLocaleString` on a `js_sys::Date`), turning each option back into its `Intl` name.
Expand Down Expand Up @@ -123,7 +125,7 @@ reference, never from hand:
- `conformance/host.json` (`host.ts`), `boundary.json` (`boundary.ts`) and `streaming.json` (`streaming.ts`), replayed
by `crates/psychoscript/tests/`.
- Rust-only features have no reference: their expected results are written in Rust's own tests
(`crates/psychoscript/tests/heap.rs`, `clock.rs`, `typed.rs`, `host_recording.rs`, `value_depth.rs`; the programs
(`crates/psychoscript/tests/heap.rs`, `clock.rs`, `typed.rs`, `host_recording.rs`, `value_depth.rs`, `session.rs`; the programs
of `tests/cases/*.js` also run in round-trip mode).
- test262, both ways: `test262/rust-skipped.txt` (fails here, passes in the reference) and `test262/reference-gaps.txt`
(passes here, fails in the reference) are empty and may only stay so.
Expand Down
62 changes: 62 additions & 0 deletions rust/crates/psychoscript/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,68 @@ pub(crate) fn host_string(vm: &Vm, s: crate::strings::StrId) -> String {
vm.text(s).to_owned()
}

/// Host data as a fresh program value, bounded by `vm.value_depth()`, failing with a `TypeError` past it.
pub fn from_data_bounded(vm: &mut Vm, d: &crate::Data) -> Res {
from_data_at(vm, d, 0)
}

#[allow(clippy::question_mark)]
fn from_data_at(vm: &mut Vm, d: &crate::Data, depth: usize) -> Res {
use crate::Data;
if depth > vm.value_depth() {
let msg = format!(
"Value exceeds the maximum value depth of {}.",
vm.value_depth()
);
return Err(vm.type_error(&msg));
}
match d {
Data::Array(items) => array_from_data(vm, items, depth),
Data::Object(fields) => object_from_data(vm, fields, depth),
_ => Ok(leaf_from_data(vm, d)),
}
}

#[allow(clippy::question_mark)]
fn array_from_data(vm: &mut Vm, items: &[crate::Data], depth: usize) -> Res {
let mut vals = Vec::with_capacity(items.len());
for item in items {
match from_data_at(vm, item, depth + 1) {
Ok(v) => vals.push(v),
Err(e) => return Err(e),
}
}
Ok(vm.new_array(vals))
}

#[allow(clippy::question_mark)]
fn object_from_data(vm: &mut Vm, fields: &[(crate::HostString, crate::Data)], depth: usize) -> Res {
let id = vm.new_object();
for (k, v) in fields {
match from_data_at(vm, v, depth + 1) {
Ok(val) => {
let a = vm.atoms.intern(&k.to_run_text());
vm.define(id, a, val);
}
Err(e) => return Err(e),
}
}
Ok(Value::Obj(id))
}

#[cfg_attr(debug_assertions, inline(never))]
fn leaf_from_data(vm: &mut Vm, d: &crate::Data) -> Value {
use crate::Data;
match d {
Data::Null => Value::Null,
Data::FunctionMarker => Value::Undef,
Data::Bool(b) => Value::Bool(*b),
Data::Number(n) => Value::Num(n.as_f64().unwrap_or(f64::NAN)),
Data::String(s) => vm.string_val(s.to_run_text()),
Data::Array(_) | Data::Object(_) => Value::Undef,
}
}

/// Host data as a fresh program value, its strings exactly as the host gave them.
pub fn from_data(vm: &mut Vm, d: &crate::Data) -> Value {
use crate::Data;
Expand Down
15 changes: 15 additions & 0 deletions rust/crates/psychoscript/src/cross.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,14 @@ fn plain_scalar(vm: &Vm, v: &Value) -> Option<Json> {
/// The program returned `v`: its result once it has crossed.
pub fn program_result(vm: &mut Vm, v: Value) -> Result<(), Value> {
if !thenable(vm, &v) {
// A session's top level returns what its calls call, which stays in the run uncrossed (`session.rs`).
if let Some(s) = vm.session.as_deref_mut()
&& s.exports.is_none()
{
s.exports = Some(v);
vm.outcome = Some(Ok(Value::Undef));
return Ok(());
}
match fast(vm, &v) {
Ok(Fast::Json(j)) => {
vm.result_json = Some(j.unwrap_or(Json::Null));
Expand Down Expand Up @@ -712,6 +720,13 @@ fn run(vm: &mut Vm, c: &mut Cross, mut act: Act, mut root_awaited: bool) -> Resu
c.waiting = Waiting::Root;
return Ok(Pause::Await(root));
}
if let Some(s) = vm.session.as_deref_mut()
&& s.exports.is_none()
{
s.exports = Some(root);
c.crossed.push(Value::Undef);
return Ok(Pause::Done);
}
root_awaited = false;
// `$vmJsonVisitor(...)`, the root `visit` generator, and the first `next`.
vm.fuel(1);
Expand Down
20 changes: 16 additions & 4 deletions rust/crates/psychoscript/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ pub fn call_namespace(vm: &mut Vm, id: Id, args: &[Value], callee: Value) -> Res
path,
owner: None,
};
call_host(vm, &f, args, target, callee)
call_host(vm, &f, Value::Undef, args, target, callee)
}

/// The raw strings of a tagged template's strings array in the first argument: one of the template objects the program
Expand Down Expand Up @@ -889,7 +889,19 @@ struct Target {
/// async or durable function's call starts at once and the program gets its promise; a failure crossing rejects it.
/// A synchronous one is called now: its value crosses back at once, and work it left pending is a promise. When the
/// runtime awaits promises in arguments and one hasn't fulfilled, the call waits for them first.
fn call_host(vm: &mut Vm, f: &Callee, args: &[Value], target: Target, callee: Value) -> Res {
fn call_host(
vm: &mut Vm,
f: &Callee,
this: Value,
args: &[Value],
target: Target,
callee: Value,
) -> Res {
if let Callee::Fn(f) = f
&& let Body::Direct(body) = &f.body
{
return crate::session::call_direct(vm, body.clone(), this, args, &target.label);
}
let takes = matches!(f, Callee::Fn(f) if f.takes_functions);
let raw = template_raw(vm, args);
vm.lends.clear();
Expand Down Expand Up @@ -2418,7 +2430,7 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option<String
made
}

fn host_native(vm: &mut Vm, _this: Value, args: &[Value], callee: Id) -> Res {
fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res {
let Value::Num(index) = vm.native_data(callee) else {
return Ok(Value::Undef);
};
Expand Down Expand Up @@ -2451,7 +2463,7 @@ fn host_native(vm: &mut Vm, _this: Value, args: &[Value], callee: Id) -> Res {
path: entry.path.clone(),
owner: entry.owner.clone(),
};
call_host(vm, &f, args, target, Value::Obj(callee))
call_host(vm, &f, this, args, target, Value::Obj(callee))
}

// ---------- modules ----------
Expand Down
19 changes: 19 additions & 0 deletions rust/crates/psychoscript/src/host_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,8 @@ type AsyncFn = dyn Fn(Vec<HostValue>, Call) -> BoxFuture<'static, HostResult> +
pub(crate) enum Body {
Sync(Arc<SyncFn>),
Async(Arc<AsyncFn>),
/// A synchronous function working on the program's values in place (`session.rs`).
Direct(Arc<crate::session::DirectFn>),
/// A function a resumed run lost: calling it throws this message at the call.
Lost(Arc<str>),
/// A live response's state, read with no call of the host (the reference's `hostGetter`).
Expand Down Expand Up @@ -808,6 +810,23 @@ impl HostFunction {
Self::with_body(Body::Sync(Arc::new(move |args, call| f(args, call).into())))
}

/// A synchronous function that works on the program's own values, with no copy: it reads its receiver and
/// arguments ([`Args`](crate::Args)) and makes its value through the [`HostCtx`](crate::HostCtx) of the call, and
/// its `Err` is what the call throws. The values are the call's only (nothing collects them meanwhile). It runs
/// where the run computes, which for a run driven as a future may be the run's worker thread.
pub fn direct<F>(f: F) -> Self
where
F: for<'a> Fn(
&mut crate::HostCtx<'a>,
crate::Args<'a>,
) -> Result<crate::Val<'a>, crate::Val<'a>>
+ Send
+ Sync
+ 'static,
{
Self::with_body(Body::Direct(Arc::new(f)))
}

/// An asynchronous function: the program gets a promise at once.
pub fn new_async<F>(f: impl Fn(Vec<HostValue>, Call) -> F + Send + Sync + 'static) -> Self
where
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/psychoscript/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ mod promise;
mod reach;
mod run;
mod runtime;
mod session;
mod snapshot;
mod stack;
mod streaming;
Expand Down Expand Up @@ -71,6 +72,7 @@ pub use runtime::{
Outcome, ProgramOptions, Run, Runtime, Translate, TranslateFunctions, TranslatePromises,
};
pub use serde_json::Value as Json;
pub use session::{Args, HostCtx, Session, Val};
pub use snapshot::{Snapshot, SnapshotError, from_bytes, to_bytes};
pub use streaming::{HttpBody, StreamingResponse};

Expand Down
Loading