A Rust implementation of psychoscript: the same confined, JavaScript-like language as the TypeScript package in src/,
which is its reference. Programs run in a bytecode VM written in pure Rust, with no Bun, Node or other JavaScript
engine at build or run time, and reach only the host functions the embedder gives them.
Against dev's TypeScript: 34x faster to start, 4.3x faster per program on a 429-program corpus, 2.0x on the bench
programs (bench/TYPESCRIPT.md).
use psychoscript::{HostFunction, HostValue, Limits, Runtime};
let runtime = Runtime::make()
.globals(|_run| [("double", HostFunction::new(|args, _| HostValue::from(args[0].as_f64().unwrap_or(0.0) * 2.0)))])
.limits(Limits { timeout_ms: Some(5_000), ..Default::default() });
let outcome = runtime.execute("return double(21)");The API is the Rust form of src/index.ts; host work is a Future instead of an Effect, and values cross the
boundary as copies (HostValue, with strings as lossless HostStrings), except typed arrays.
Programs always have ArrayBuffer and the other standard typed arrays besides Uint8Array (Int8Array,
Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float16Array, Float32Array,
Float64Array, BigInt64Array, BigUint64Array), set up only when a program uses them. An ArrayBuffer or a typed array other than
Uint8Array crosses as HostValue::TypedArray(TypedArray). A synchronous
host function borrows the program's own bytes for the duration of the call, with no copy: read them in place with
with_bytes(|bytes: &[u8]| ..) (for instance to upload them to a GPU) or write them with with_bytes_mut; kind(),
len() and byte_len() describe the view. Once the call returns the handle is empty. An async or durable host
function gets a copy, as the program runs on meanwhile. Return TypedArray::new(TypedKind::F32, bytes), which takes
the Vec<u8> without copying and gives it to the program, or a handle the same call got, which is the program's buffer
again. Elements are little-endian. Inside the run, a typed array's bytes are a heap object its views reference by id,
so element access takes no lock.
use psychoscript::{HostFunction, HostValue, TypedArray, TypedKind};
let upload = HostFunction::new(|args, _| {
if let Some(HostValue::TypedArray(t)) = args.first() {
t.with_bytes(|bytes| queue_write_buffer(bytes)); // no copy
}
HostValue::Undefined
});
let mesh = HostFunction::new(|_, _| HostValue::TypedArray(TypedArray::from_f32(&[0.0, 1.0, 0.5])));Reference (src/index.ts) |
Rust (crates/psychoscript/src/lib.rs) |
|---|---|
Runtime.make({ globals, modules, limits, translate }) |
Runtime::make().globals(..).modules(..).limits(..).translate(..) |
Host.fn, Host.durableFn, Host.namespace |
HostFunction, DurableFunction, Namespace |
Host.fail, Host.missing |
Failure::new, Failure::missing |
properties of Host.fn, Host.durableFn |
HostFunction::properties, DurableFunction::properties |
runtime.execute, runtime.program, runtime.compile, runtime.resume |
execute/execute_async, program, compile, resume/resume_bytes |
toBytes, fromBytes |
to_bytes, from_bytes |
limits.timeoutMs, limits.maxOutputBytes, limits.maxValueDepth |
Limits::timeout_ms, Limits::max_output_bytes, Limits::max_value_depth |
a host tag's strings.raw |
Call::raw_strings |
translate: { functions, promises } |
Translate { functions, promises } |
Host.functionMarker (functions: "mark") |
HostValue::FunctionMarker, Data::FunctionMarker |
an AbortSignal |
dropping the future or the Program |
Only Rust has:
- A heap cap and live heap size:
Limits::max_heap_bytes, measured in the size model ofheap.rs; over it,MemoryLimitExceeded.Run::heap_bytesreturns the last measured reachable bytes of a live run without thegc-statsfeature. It is measured undermax_heap_bytes, or without a cap at the run's waits for the host withRuntime::measure_heap(true); otherwiseNone. A run that drops much of its heap without allocating keeps reporting the old size until it allocates again. - CPU-time budgets:
Limits::clockClock::ThreadCpufortimeout_ms(alsothread_clockfor hosts). - The interpreter slice:
Limits::slice_ms, the longest stretch between awaits of the host; past it,SliceExceeded. - A configurable source size limit:
Limits::max_source_bytes, defaulting toDEFAULT_MAX_SOURCE_BYTES(256 KiB). - Located host errors:
HostError::located(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; 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 isCall::location. - Always-on typed arrays:
ArrayBufferand every standard typed array besides Uint8Array, asHostValue::TypedArray: lent without a copy to sync host functions, copied for async and durable ones. - Direct host functions:
HostFunction::directgets the program's own values, with no copy, through the call'sHostCtx(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 aValcan'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::sessionruns 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 anOutcome), with the program's state kept from call to call. A failure that ends a run leaves the session failed.Session::savegives the state between calls as a suspended run's, andRuntime::restore_sessioncontinues it, also in another process of the same build. - Precompiled named modules:
Runtime::compile_modulecompiles a synchronous named module once into an immutable,Send + SyncCompiledModuleto run in any session viaSession::eval_compiled/Session::eval_moduleor from a direct host function viaHostCtx::eval_compiled/HostCtx::eval_module. Functions from named modules report per-modulefile:line:colstack traces (andCall::location) andFunction.prototype.toStringslices each module's own source. Loaded modules and their source metadata surviveSession::save/Runtime::restore_sessionand suspend/resume snapshots. - Lazy built-in groups:
LAZYsets upRegExp,Date, the typed arrays and the other groups only when a program uses them. - Optional
localefeature (default = ["locale"]): disable it withdefault-features = falseto drop ICU4X's compiled CLDR tables (~5 MB) in lean embedded orwasm32builds. Withlocaleoff and no provider of the host's (below),localesandoptionsare ignored:Date.prototype.toLocale*Stringreturns UTC ISO-8601 strings (YYYY-MM-DDTHH:mm:ss.sssZ, date slice, or time slice, or"Invalid Date"),Number/BigInt.prototype.toLocaleStringuse decimaltoString, andString.prototype.localeComparecompares NFC-normalized UTF-16 code units. - A pluggable locale provider:
Runtime::localesets theLocaleProvider(Send + Sync) that formats dates fortoLocale*String, numbers and BigInts fortoLocaleString, and compares strings forlocaleCompare, in place of the default:IcuLocalewithlocale,FallbackLocale(the fallbacks above) without it. PsychoScript still reads and validates the locales and options and throws their errors, as withlocale, so the provider gets the locale tags and the resolved options as plain Rust data and only formats or compares; it checkstimeZoneitself (PsychoScript's zone data checks it only for the defaults), and anErrit returns, for what only it can know, is thrown as aRangeError. It is host configuration like the globals, not saved with a run. Awasm32host withoutlocalecan hand them to the browser'sIntlthroughwasm-bindgen(js_sys::Intl::DateTimeFormat,NumberFormat,Collator, ortoLocaleStringon ajs_sys::Date), turning each option back into itsIntlname. - Owned runs that stay on the calling thread:
Runtimeclones cheaply,Programholds a clone so it is'static, andRuntime::offload(false)keeps a run driven as a future on the thread that polls it, without starting a worker thread, so CPU time counts there.
Only TypeScript has:
parseProgram, the program's ESTree AST; Rust'sRuntime::compileonly reports its errors.formatLocationandmoduleName, two small exported helpers.- Date's locale formatting through the host's ICU4C: Rust uses ICU4X, with recorded differences (see Parity).
- Number and BigInt
toLocaleStringthrough the host'sIntl.NumberFormat: Rust formats the decimal style with ICU4X, with recorded differences, and refuses with a RangeError what it doesn't format:style"percent","currency"or"unit", andnotation"scientific","engineering"or"compact"(socurrency,currencyDisplay,currencySign,unit,unitDisplayandcompactDisplayonly take effect in TypeScript; Rust validates them and leaves the decimal style as it is). - A host failure thrown inside a built-in the reference writes as bytecode with handlers (
Map.prototype.forEach, the iterator helpers) becomes an ordinary error there; Rust's native built-ins keep its host kind.
Run from rust/, after bun install at the repository root:
cargo fmt --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace # includes every conformance recording
cargo test --locked -p psychoscript --no-default-features --test locale_fallback
# on a Mac: --features psychoscript-gpu/metal (its GPU tests, else Vulkan)
PSYCHOSCRIPT_ROUNDTRIP=1 cargo test --locked -p psychoscript-bench --test conformance
bash test262/run.sh # test262, both ways
bash bench/compare.sh # against the reference, writes bench/RESULTS.mdAfter a change to the TypeScript reference, regenerate the recordings and commit them with the Rust change that makes them pass:
bun conformance/generate.ts && bun conformance/host.ts && bun conformance/boundary.ts && bun conformance/streaming.ts
bun conformance/date-locale.ts # the Date locale matrix, its expected output and its differences from ICU4X
bun conformance/number-locale.ts # the same for Number and BigInt toLocaleStringApart from the differences above, Rust matches dev's TypeScript. The expectations for that come only from the
reference, never from hand:
conformance/cases/*.js→.json(generate.ts), replayed bybench/tests/conformance.rs, also in round-trip mode, which saves and restores every run at each host stop and loop or call slice.conformance/host.json(host.ts),boundary.json(boundary.ts) andstreaming.json(streaming.ts), replayed bycrates/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,session.rs; the programs oftests/cases/*.jsalso run in round-trip mode). - test262, both ways:
test262/rust-skipped.txt(fails here, passes in the reference) andtest262/reference-gaps.txt(passes here, fails in the reference) are empty and may only stay so.
CI (check-rust) runs fmt, clippy and the tests without the GPU tests; ci.yml fails when the four TypeScript-only
generators leave a diff. The GPU tests run locally, not in CI. test262 runs on demand, through the test262-rust
workflow. The cases marked @platform "linux" depend on the system libm and are recorded only on Linux.
Known differences:
- A saved state resumes only in the implementation and build that saved it: the snapshot formats differ.
- A
DataViewreaches a host function as the typed arrays do, aHostValue::TypedArray(TypedKind::DataView) lent without a copy to a sync one; the reference passes aUint8Arraycopy of its bytes. - Date's
toLocaleString,toLocaleDateStringandtoLocaleTimeStringformat any locale andIntl.DateTimeFormatoptions through ICU4X rather than the host ICU4C: the common cases — and every error kind and message — match, and the rest render ICU4X's closest output. The differences are recorded byconformance/date-locale.tsinconformance/date-locale.differences.jsonand pinned bybench/tests/date_locale.rs; among them: a two-digit year inside a date, numeric dates where a locale'syMdpattern differs from its short style, a standalone minute or second (ICU4X prefixes the hour), flexible day periods (b/B), and the CJK separators and zone names whose data differs from ICU's. - Number and BigInt
toLocaleStringlikewise, in the decimal style: every option the reference honours there (integer, fraction and significant digits, the rounding modes, increments and priority,trailingZeroDisplay,useGrouping,signDisplay,numberingSystem), and every error kind and message, match.conformance/number-locale.tsrecords the differences inconformance/number-locale.differences.json, pinned bybench/tests/date_locale.rs: NaN isNaNin every locale (ICU4X has no localized name for it), a numbering system other than the locale's keeps the locale's separators, and a few regions whose CLDR data is newer in ICU4X (de-AT,fr-CH,bn-BD).
- A regular expression's backtracking can't be interrupted: one match (
/(a|a)*b/on a long run ofas) runs pasttimeout_msandslice_ms, as in the reference.regresshas no step budget; bound untrusted patterns or inputs. - A saved state changed since it was saved is refused (its header holds a hash of it), but resuming doesn't validate a forged one in full and may panic (in safe Rust): store saved states as you would code.
- The run drops what a host gives it without recursing, at any depth, but a
HostValuea host makes and drops itself drops recursively, like aserde_json::Value: one nested past about 10,000 levels is the host's to take apart. - On wasm32, a run driven as a future that waits on a host call notices its timeout only when it is next polled.
- The round-trip conformance run (
PSYCHOSCRIPT_ROUNDTRIP=1) failed once on a heavily loaded machine and didn't reproduce in 52 runs since; its quiet panic hook doesn't name the failing case.
- Threading: a run stays on the thread that drives it; as a future, compute past 1 ms moves to a worker of the
run's own (unless
Runtime::offload(false)keeps it on the calling thread) while host code is always handed back to the executor, in the same order. On wasm32, without threads, the run yields to its executor there instead, and a thread can't wait: a synchronous run waiting on host work that isn't ready, or a sync host function'sReturned::Blockwork, ends in anExecutionFailuresaying so. - Memory: an incremental, non-moving mark-sweep collector (
collector.rs) frees what a run can no longer reach, at safe points only (bench/GC.md).Limits::max_heap_bytescaps what a run can reach, in the size model ofheap.rs. - Time:
Limits::timeout_mscounts wall-clock time by default. WithLimits::clock: Clock::ThreadCpuit counts the CPU time of the threads while they run the program (cpu.rs), so a loaded machine never times out a program that is only waiting for a core. Host work isn't counted. Synchronous host calls are left out by their wall-clock duration (twoInstantreads, not the thread's clock), which can only count too little, never too much; the thread's CPU time with host calls ends the run at ten times the timeout, so what that misses stays bounded. Waits on host calls count on the wall clock, up to ten times the timeout. The check reads the thread's clock only when the wall time since its last reading could have used up the budget.Limits::slice_msbounds each stretch between awaits of the host the same way, also leaving out host calls, and stops the run withSliceExceeded, so a host needn't watch the run from outside. A suspend saves how far the stretch in progress had gone, and underThreadCputhe CPU time with host calls and the waits, so a resume goes on from there instead of starting them again. UnderThreadCpua stretch's CPU time is measured from when it has run a sixteenth of the slice, so it may run up to that much past it. On wasm32 the clocks areperformance.now()andDate.now()(web-time), andThreadCpucounts wall-clock time. - Compiling: the parser recurses once a level of syntax and has no guard of its own, so a program is parsed on a
thread with the stack its nesting needs, by a bound read from its bytes (
nesting.rs). A program bounded pastMAX_COMPILE_LEVELS(65,536; the bound takes each token of the longest item at each depth for a level, so it is far above the 2,000 levels the compiler takes) is refused before it is parsed: what a hostile source costs to refuse doesn't grow with its depth. A regular expression literal has its flags and its syntax checked, in time by its length, and is compiled where the program evaluates it, within that run's limits: a compile takes time by what a pattern holds, and nothing limits a program's compile. So a literal that is valid syntax and that the regex compiler refuses (more than 65,535 loops) throws itsSyntaxErrorwhen it is evaluated. - Layout:
crates/psychoscript(compiler onoxc_parser, VM, standard library, host functions, snapshots, andthread_clock: a thread's CPU time, read on it or from another thread, for hosts too),crates/psychoscript-gpu(GPU canvases: a program's WebGPU batches checked and replayed on a host'swgpudevice, itsREADME.md),crates/psychoscript-mobile(UniFFI bindings for iOS and Android, itsREADME.md),conformance/(generators and recordings),bench/,test262/.
Rules: pure Rust and few dependencies, no unsafe (outside the thread_clock module, whose blocks are each one
documented OS call; psychoscript-mobile's FFI, JNI and surfaces are its only other unsafe, each with its SAFETY
comment), never panic on user input, and unsupported syntax throws UnsupportedSyntax with a location where
it runs.