Files
vectorcraft/crates/js/src/realm.rs
T
dotCooCoo 1d6af09cff Scripts: a stop from end when show() fails ends the run
When show() failed (an answer that could not be read, a host call that
threw, or a handler that threw), the dialog's failure function called the
host's end and dropped its result, so an Abort from end did not stop the
run and the script could catch the error and finish. The failure function
now returns that stop, and the answer and call paths end the run with it
before the error reaches the script.
2026-11-30 17:59:40 -08:00

859 lines
40 KiB
Rust

//! The embedding API: a [`Realm`] holds a global object and its built-ins, runs scripts in them,
//! and enforces [`Limits`].
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::bytecode::CodeKind;
use crate::heap::{Func, HIDDEN, Object, Prop, key};
use crate::interp::{Abrupt, CompileError, Interp};
use crate::module::{LinkFail, ModuleLimits, ModuleLoader};
use crate::value::Value;
use crate::{Options, SyntaxError};
fn internal_error(message: &str) -> RunError {
RunError { kind: RunErrorKind::Internal, message: message.to_string(), line: 0, column: 0, authored: false }
}
/// The limits a run is held to. Reaching one ends the run with [`RunErrorKind::Limit`]; scripts
/// cannot catch it, and their `finally` blocks do not run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Limits {
/// Instructions a run may execute. Source that `eval`, `Function` or a host evaluator
/// compiles during the run also takes one unit for each UTF-16 code unit, before it is parsed.
pub fuel: u64,
/// Estimated bytes the heap (objects, environments and the strings they hold) may reach
/// after a collection. A string longer than a quarter of this many code units cannot be
/// made.
pub heap_bytes: usize,
/// Call frames that may be active at once.
pub frames: usize,
/// How deeply the interpreter may run again inside an operation (getters and setters,
/// conversions that call `valueOf` or `toString`, indirect `eval`).
pub reentry: usize,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for Limits {
fn default() -> Self {
Self { fuel: 1_000_000_000, heap_bytes: 512 << 20, frames: 10_000, reentry: 32 }
}
}
/// A wasm build has less memory and a smaller stack.
#[cfg(target_arch = "wasm32")]
impl Default for Limits {
fn default() -> Self {
Self { fuel: 250_000_000, heap_bytes: 128 << 20, frames: 2_000, reentry: 16 }
}
}
/// Which limit a run reached.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LimitKind {
Fuel,
Heap,
Frames,
Reentry,
/// The host set the interrupt flag.
Interrupted,
/// A getter, a callback of a built-in or another nested run spent [`MAX_UNBROKEN_FUEL`]
/// without returning to the point where a resumable run can pause.
Unbroken,
/// A host function ended the run ([`crate::HostError::Abort`]).
Host,
/// More promise jobs were waiting to run than a run may queue.
Jobs,
}
/// A promise the last run rejected that still had no rejection handler when the run ended
/// ([`Realm::unhandled_rejections`]). `line` and `column` are where it was rejected: the `throw`,
/// or the call to its reject function or `Promise.reject`; they are 0 when that is not known.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rejection {
/// The reason, described as an uncaught exception's message is.
pub message: String,
pub line: u32,
pub column: u32,
/// The source tag of the code `line` and `column` are in ([`Realm::error_tag`]).
pub tag: u32,
/// `message` is text the script supplied ([`RunError::authored`]).
pub authored: bool,
}
/// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an
/// evaluator's: code that `eval` or `Function` compiled, or an error with no place.
pub const UNKNOWN_SOURCE: u32 = u32::MAX;
/// The file and line that line `line` of the source with tag `tag` ([`Realm::error_tag`]) came
/// from, as `$.line` and `$.stack` give them ([`Realm::set_source_locator`]).
pub type SourceLocator = std::rc::Rc<dyn Fn(u32, u32) -> (String, u32)>;
/// The source tag after `tag`. Once the tags are used up, every later source gets
/// [`UNKNOWN_SOURCE`], so no two sources share a tag.
pub(crate) fn next_tag(tag: u32) -> u32 {
if tag >= UNKNOWN_SOURCE - 1 { UNKNOWN_SOURCE } else { tag + 1 }
}
/// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run
/// it cannot pause.
pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000;
/// How far a resumable run got.
#[derive(Clone, Debug, PartialEq)]
pub enum Progress {
/// The slice ended; call [`Realm::advance`] again.
Paused,
/// The script ended, with its completion value.
Done(JsValue),
}
/// A flag the host sets, from any thread, to stop the running script at its next instruction.
/// It stays set until [`Interrupt::clear`].
#[derive(Clone, Debug, Default)]
pub struct Interrupt(Arc<AtomicBool>);
impl Interrupt {
pub fn new() -> Self {
Self::default()
}
pub fn set(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub fn clear(&self) {
self.0.store(false, Ordering::Relaxed);
}
pub fn is_set(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
}
/// A value passed between a script and the host. An object is given by its class name, and a
/// Symbol by its description; a Symbol the host passes in is a new Symbol each time, and one a
/// host function returns in a realm without [`Options::es2015`] throws a `TypeError`.
#[derive(Clone, Debug, PartialEq)]
pub enum JsValue {
Undefined,
Null,
Bool(bool),
Number(f64),
String(String),
Object(String),
Symbol(Option<String>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RunErrorKind {
/// The source does not parse.
Syntax,
/// The script threw an exception it did not catch.
Thrown,
Limit(LimitKind),
/// The interpreter reached a state it never makes.
Internal,
}
/// Why a run did not complete. `line` and `column` count from 1 (the column in UTF-16 code units)
/// and give where the error was raised; they are 0 when that is not known.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunError {
pub kind: RunErrorKind,
pub message: String,
pub line: u32,
pub column: u32,
/// `message` is text the script supplied: a value it threw, or an error object it made or whose
/// name or message it changed. False for the interpreter's and host functions' own errors,
/// syntax errors and limits, even when a script caught one and threw it again.
pub authored: bool,
}
impl std::fmt::Display for RunError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} (line {}, column {})", self.message, self.line, self.column)
}
}
impl std::error::Error for RunError {}
impl From<SyntaxError> for RunError {
fn from(e: SyntaxError) -> Self {
RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column, authored: false }
}
}
/// A global environment with the built-ins, in which scripts run one after another.
pub struct Realm {
interp: Interp,
unbroken_fuel: u64,
/// The source tag of the script the last [`Realm::run`] or [`Realm::start`] compiled. Each
/// script gets a new one, and the sources an evaluator gives during its run get the ones after
/// it, so code that an earlier script defined keeps a tag of its own. [`UNKNOWN_SOURCE`]
/// before the first script, for a script the realm did not compile, and once the tags are used
/// up.
script_tag: u32,
/// The unhandled rejections of the last run that ended successfully, and how many there were.
rejections: (Vec<Rejection>, usize),
}
impl Default for Realm {
fn default() -> Self {
Self::new()
}
}
impl Realm {
pub fn new() -> Self {
Self::with_options(Options::default(), Limits::default())
}
/// A realm whose scripts (and the source given to `eval` and `Function`) are read with
/// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it
/// counted together.
pub fn with_options(options: Options, limits: Limits) -> Self {
Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE, rejections: (Vec::new(), 0) }
}
/// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default
/// [`MAX_UNBROKEN_FUEL`]).
pub fn set_unbroken_fuel(&mut self, fuel: u64) {
self.unbroken_fuel = fuel;
}
/// With `on`, the scripts run next (and the code they define and evaluate) throw a
/// `TypeError` when they assign to a read-only or getter-only property or add a property to
/// an object that is not extensible, as strict mode code does, without the rest of strict
/// mode. Off by default.
pub fn set_strict_writes(&mut self, on: bool) {
self.interp.strict_writes = on;
}
pub fn limits(&self) -> &Limits {
&self.interp.limits
}
/// Sets the limits for the next run. A heap that is already larger than the new
/// [`Limits::heap_bytes`] ends the next run with the heap limit unless a collection frees
/// enough of it.
pub fn set_limits(&mut self, limits: Limits) {
self.interp.limits = limits;
self.interp.reset_gc_threshold();
}
/// Gives a realm made without [`Options::es2015`] the `Promise` that option adds, for its next
/// runs; a realm that has it already is left as it is. It does not take it away again, and it
/// does not add the option's other built-ins (`Symbol` and the iterators). Call it between
/// runs.
pub fn add_es2015(&mut self) {
crate::builtins::promise::add_to(&mut self.interp);
}
/// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and
/// `const` names earlier runs declared stay visible when it is turned off. A run begun with
/// [`Realm::start`] that is still going keeps the language it started with for the code it
/// evaluates; the new one applies once it ends.
pub fn set_es2015(&mut self, es2015: bool) {
if self.is_running() || self.interp.waiting {
self.interp.next_es2015 = Some(es2015);
} else {
self.interp.next_es2015 = None;
self.interp.set_es2015(es2015);
}
}
/// The realm's interrupt flag. Setting it stops a running script, or the next one to start.
pub fn interrupt(&self) -> Interrupt {
Interrupt(self.interp.interrupt.clone())
}
/// Defines a global function that calls `f` with its arguments. An `Err` from `f` is thrown
/// to the script as an `Error` with that message.
pub fn define_function(&mut self, name: &str, f: impl Fn(&[JsValue]) -> Result<JsValue, String> + 'static) {
let interp = &mut self.interp;
let proto = interp.intrinsics.function_proto;
let func = Func::Host { f: std::rc::Rc::new(f), name: name.into() };
let o = interp.heap.alloc_object(Object::new(crate::heap::Class::Function(func), Some(proto)));
let global = interp.global;
let _ = interp.define(global, key(name), Prop::Data { value: Value::Object(o), flags: HIDDEN });
}
/// Runs `source` as a script in the global environment, then the promise jobs it queued, and
/// returns its completion value (the value of the last expression statement that ran). A realm
/// whose built-ins could not be installed runs nothing and gives an internal error.
/// A paused or waiting run ends first; its globals remain available.
pub fn run(&mut self, source: &str) -> Result<JsValue, RunError> {
let code = self.compile(source)?;
let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v));
self.outcome(result)
}
/// Compiles `source` and readies the realm for a run.
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
self.end();
self.reset_run()?;
let interp = &mut self.interp;
let strict = interp.options.strict;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
interp.source_tag = self.script_tag;
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
interp.source_tag = UNKNOWN_SOURCE;
match code {
Ok(code) => Ok(code),
Err(CompileError::Syntax(e)) => {
interp.error_tag = self.script_tag;
Err(e.into())
}
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
}
}
/// Begins a run of the module `key` with `source` (ECMA-262 2015 section 15.2), which
/// [`Realm::advance`] carries on as it does a script [`Realm::start`] began. `load` gives each
/// module a module imports ([`ModuleLoader`]). Every module is loaded, parsed and linked before
/// any runs, so a syntax error, an import of a missing or ambiguous export, a module `load`
/// cannot give or a module past `limits` ends the run here, with no code run. The first module
/// has [`Realm::script_tag`] as its source's tag, and each module loaded after it the next tag,
/// in the order `load` first gave their sources, as the sources an evaluator gives during a run
/// take theirs. A realm without [`Options::es2015`] runs no module: that is a syntax error.
/// A paused or waiting run ends before loading; its globals remain available.
pub fn start_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<(), RunError> {
self.end();
self.reset_run()?;
if !self.interp.options.es2015 {
let message = "modules need ECMAScript 2015; this script runs ECMAScript 5".to_string();
return Err(RunError { kind: RunErrorKind::Syntax, message, line: 0, column: 0, authored: false });
}
let interp = &mut self.interp;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
let marks = (interp.temp_envs_mark(), interp.temp_roots_mark(), interp.temp_codes_mark());
let linked = crate::module::link(interp, key, source, self.script_tag, limits, load);
let pushed = match linked {
Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run),
Err(fail) => Err(fail),
};
let interp = &mut self.interp;
interp.drop_temp_envs(marks.0);
interp.drop_temp_roots(marks.1);
interp.drop_temp_codes(marks.2);
match pushed {
Ok(()) => Ok(()),
Err(LinkFail::Syntax { tag, error }) => {
self.interp.error_tag = tag;
Err(error.into())
}
Err(LinkFail::At { tag, line, column, abrupt }) => {
let e = self.outcome(Err(abrupt)).err();
self.interp.error_tag = tag;
Err(e.map_or_else(|| internal_error("a module failed without an error"), |e| RunError { line, column, ..e }))
}
Err(LinkFail::Run(abrupt)) => self.outcome(Err(abrupt)).map(drop),
}
}
/// Runs the module `key` with `source` to its end ([`Realm::start_module`]), drains its queued
/// Promise jobs, and returns `undefined`.
pub fn run_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<JsValue, RunError> {
self.start_module(key, source, limits, load)?;
let result = self.interp.execute().and_then(|value| self.interp.drain_jobs(value));
self.outcome(result)
}
/// Readies the realm for a run: its state from the last run cleared and its fuel filled.
fn reset_run(&mut self) -> Result<(), RunError> {
self.script_tag = UNKNOWN_SOURCE;
self.rejections = (Vec::new(), 0);
let interp = &mut self.interp;
interp.end_jobs(false);
if let Some(message) = &interp.install_error {
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false });
}
interp.fuel = interp.limits.fuel;
interp.flattened_fuel.set(0);
interp.source_units = 0;
interp.throw_site = None;
interp.last_thrown = Value::Undefined;
interp.last_error = Value::Null;
interp.host_abort = None;
interp.waiting = false;
interp.waiting_hosted = false;
interp.answer_throws = false;
interp.constructing = false;
interp.resuming = None;
interp.again = None;
crate::scriptui::end_run(interp);
interp.error_tag = UNKNOWN_SOURCE;
interp.thrown_mark = None;
interp.finally_marks.clear();
interp.finally_sites.clear();
interp.error_mark = None;
// The first run with ECMAScript 2015 names the built-in functions; a run whose heap has no
// room for the names ends with the heap limit, and the next run tries again.
if interp.options.es2015
&& let Err(e) = crate::builtins::es2015_names(interp)
{
return match self.outcome(Err(e)) {
Err(e) => Err(e),
Ok(_) => Err(RunError {
kind: RunErrorKind::Internal,
message: "the built-in function names could not be set".into(),
line: 0,
column: 0,
authored: false,
}),
};
}
Ok(())
}
/// The end of a run: its completion value or error, with the interpreter's stacks emptied.
fn outcome(&mut self, result: Result<Value, Abrupt>) -> Result<JsValue, RunError> {
let interp = &mut self.interp;
let site = interp.throw_site.take();
interp.error_tag = site.as_ref().map_or(UNKNOWN_SOURCE, |(code, _)| code.source.tag);
let (line, column) = site.map_or((0, 0), |(code, pc)| code.line_column(pc));
interp.error_mark = interp.thrown_mark.take().filter(|_| matches!(result, Err(Abrupt::Throw(_) | Abrupt::Limit(LimitKind::Host))));
interp.finally_marks.clear();
interp.finally_sites.clear();
interp.stack.clear();
// A generator whose body was running when the run ended cannot go on.
let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect();
running.into_iter().for_each(|g| interp.end_generator(Some(g)));
interp.clear_frames();
interp.temp_roots.clear();
interp.join_stack.clear();
interp.waiting = false;
interp.waiting_hosted = false;
interp.answer_throws = false;
interp.constructing = false;
interp.resuming = None;
interp.again = None;
crate::scriptui::end_run(interp);
interp.passing = Value::Undefined;
interp.end_jobs(result.is_ok());
if let Some(es2015) = interp.next_es2015.take() {
interp.set_es2015(es2015);
}
match result {
Ok(v) => {
self.rejections = interp.take_unhandled();
Ok(interp.to_js_value(&v))
}
Err(Abrupt::Throw(v)) => {
let message = interp.describe(&v);
let authored = interp.thrown_by_script(&v);
interp.last_thrown = v;
Err(RunError { kind: RunErrorKind::Thrown, message, line, column, authored })
}
Err(Abrupt::Limit(LimitKind::Host)) => {
let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host));
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false })
}
Err(Abrupt::Limit(LimitKind::Jobs)) => {
let max = interp.promises.max_jobs;
let message = format!("limit reached: Jobs (more than {max} promise jobs were waiting to run)");
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Jobs), message, line, column, authored: false })
}
Err(Abrupt::Limit(kind)) => {
Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false })
}
Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column, authored: false }),
}
}
/// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it.
/// A paused or waiting run ends first; its globals remain available.
pub fn start(&mut self, source: &str) -> Result<(), RunError> {
let code = self.compile(source)?;
match self.interp.enter_global(code, false) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one
/// instruction), and pauses where it can resume: between two instructions of the script's own
/// code. A getter, a built-in's callback or another nested run has native frames under it, so
/// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. After the script's code
/// ends, the slices run the promise jobs it queued, pausing between jobs and inside a callback
/// written in JavaScript, and the run is done once the queue is empty. Once this has returned
/// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its
/// result ([`Realm::waits`]), the run does not advance: this gives an internal error.
pub fn advance(&mut self, slice: u64) -> Result<Progress, RunError> {
let interp = &mut self.interp;
if !interp.running() {
return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false });
}
if interp.waiting {
return Err(RunError {
kind: RunErrorKind::Internal,
message: "the run waits for a host function's result".into(),
line: 0,
column: 0,
authored: false,
});
}
let total = interp.fuel;
let cap = slice.saturating_add(self.unbroken_fuel).min(total);
interp.fuel = cap;
interp.in_slice = true;
let r = interp.execute_run_slice(cap - slice.min(cap));
interp.in_slice = false;
let used = cap - interp.fuel;
interp.fuel = total - used;
match r {
Ok(None) => Ok(Progress::Paused),
Ok(Some(v)) => self.outcome(Ok(v)).map(Progress::Done),
// The run's own fuel is not used up, so it was the allowance of this slice.
Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(Progress::Done),
Err(e) => self.outcome(Err(e)).map(Progress::Done),
}
}
/// Is a run begun with [`Realm::start`] still going?
pub fn is_running(&self) -> bool {
self.interp.running()
}
/// The promises the last run rejected that still had no rejection handler when it ended
/// successfully, in the order they were rejected: the first 20 of them. Empty after a run that
/// ended with an error, and until a run ends.
pub fn unhandled_rejections(&self) -> &[Rejection] {
&self.rejections.0
}
/// How many unhandled rejections the last run that ended successfully had, the ones
/// [`Realm::unhandled_rejections`] leaves out included.
pub fn unhandled_rejection_count(&self) -> usize {
self.rejections.1
}
/// Which source the code with tag `tag` is, as [`Realm::error_source`] gives it for an error.
pub fn source_of(&self, tag: u32) -> u32 {
match tag {
UNKNOWN_SOURCE => UNKNOWN_SOURCE,
tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE),
}
}
/// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's
/// result, as an interrupt would: its stacks are emptied, so the realm can start another run.
/// The globals the run set stay.
pub fn end(&mut self) {
if self.is_running() || self.interp.waiting {
let _ = self.outcome(Err(Abrupt::Limit(LimitKind::Interrupted)));
}
}
/// The flag a host function sets to end the current slice at the next point it can pause.
pub fn pause_flag(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
self.interp.pause.clone()
}
/// The flag that is set while a host function runs where it may return
/// [`crate::HostError::Wait`]: called by the script's own code in a run [`Realm::advance`]
/// carries on, and not from a getter, a conversion or a built-in's callback.
pub fn wait_flag(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
self.interp.can_wait.clone()
}
/// Does a host function's call wait for the result [`Realm::answer`] gives it?
pub fn waits(&self) -> bool {
self.interp.waiting
}
/// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next
/// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the
/// call, the built-in takes `d` first and gives its own result, and what it throws is thrown
/// at its call. A result that cannot be read as a value, such as one nested too deep, is
/// thrown at the call as an immediate result would be, and the built-in does not get it. A
/// result past the heap limit ends the run with that limit, and with no call waiting this gives
/// an internal error.
pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> {
let interp = &mut self.interp;
if !interp.waiting {
return Err(RunError {
kind: RunErrorKind::Internal,
message: "no host function waits for a result".into(),
line: 0,
column: 0,
authored: false,
});
}
interp.waiting = false;
// A member of a host class gets its answer as it gets an immediate result.
let hosted = std::mem::take(&mut interp.waiting_hosted);
// The value on top of the stack stood in for the result.
let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) };
let r = match written {
// An answer that cannot be read as a value (too deep, too many entries, a stale host
// reference) is thrown at the call, where the script can catch it, and a built-in
// that waited with the call does not get it: it fails as when its host call throws. A
// stop its failure gives (an Abort from the host) ends the run before the error is
// thrown.
Err(Abrupt::Throw(thrown)) => {
interp.stack.pop();
let stop = match interp.resuming.take() {
Some(r) => r.fail(interp, &thrown),
None => Ok(()),
};
stop.and_then(|()| {
interp.answer_throws = true;
interp.push(thrown)
})
}
written => written.and_then(|v| {
interp.stack.pop();
interp.push(v)
}),
};
match r {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Has this realm stop when `interrupt` is set, in place of its own flag.
pub fn share_interrupt(&mut self, interrupt: &Interrupt) {
self.interp.interrupt = interrupt.0.clone();
}
/// Has `$.line` give the line `locate` maps the running line to, and `$.stack` give each
/// frame's line that way, after the file `locate` names: `function@file:line`. Without a
/// locator they give the line of the compiled source, and `$.stack` names no file.
pub fn set_source_locator(&mut self, locate: SourceLocator) {
self.interp.locator = Some(locate);
}
/// Has `$.stack` start with a line `[name]` that names the running script, before its frames;
/// `None` leaves the line out.
pub fn set_script_name(&mut self, name: Option<String>) {
self.interp.script_name = name;
}
/// Which source the last error's `line` and `column` are in: 0 for the most recent script or
/// module entry source. Later sources are numbered from 1 as tags are assigned: modules in
/// load order, then sources a [`crate::HostItem::Evaluator`] gives. Module execution order
/// can differ from load order. A script run without modules numbers only evaluator sources.
/// [`UNKNOWN_SOURCE`] includes code from earlier runs and their module or evaluator sources.
pub fn error_source(&self) -> u32 {
self.source_of(self.interp.error_tag)
}
/// The source tag of the code the last error's `line` and `column` are in, which stays the same
/// from run to run: each script or module entry, each dependency loaded, and each source a
/// [`crate::HostItem::Evaluator`] gives gets the next tag, so a function an earlier script
/// defined has its script's tag. [`UNKNOWN_SOURCE`] for code that `eval` or `Function`
/// compiled, an error with no place, and sources given once the tags are used up.
pub fn error_tag(&self) -> u32 {
self.interp.error_tag
}
/// The source tag ([`Realm::error_tag`]) of the most recent script or module entry source.
/// Dependency modules receive subsequent tags in load order, followed by evaluator sources
/// as they are given. A script run without modules assigns subsequent tags only to evaluator
/// sources. [`UNKNOWN_SOURCE`] when no entry tag has been assigned or the tags are used up.
pub fn script_tag(&self) -> u32 {
self.script_tag
}
/// Tests: makes `tag` the last source tag given out.
#[cfg(test)]
pub(crate) fn set_last_tag(&mut self, tag: u32) {
self.interp.evaluated = tag;
}
/// The mark of the host error ([`crate::HostError::Marked`]) the last run ended with, when no
/// `catch` clause took that error's exception on its way out; `None` otherwise.
pub fn error_mark(&self) -> Option<u32> {
self.interp.error_mark
}
/// Fuel the run has left.
pub fn fuel_left(&self) -> u64 {
self.interp.fuel
}
/// Sets how much a value passed to or from a host function may carry.
pub fn set_data_limits(&mut self, limits: crate::DataLimits) {
self.interp.data_limits = limits;
}
/// Adds the frozen object `name`, with `items`, to the global environment. Scripts cannot add
/// to it, change it or replace it. A heap too small for it ends with the error the realm's
/// next run would give.
pub fn define_host_object(&mut self, name: &str, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> {
match self.interp.install_host_object(name, items) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds ScriptUI's global constructor `Window` ([`crate::scriptui`]), whose dialogs the host
/// functions in `items` show: `open` and `wait`, each given the dialog's description, and
/// `end`, given the result of `show()` and whether `show()` ended normally. A run that ends
/// while `show()` waits for `wait`'s answer, because it is stopped or the host does not resume
/// it, ends without a call to `end`: the host releases what it holds for the dialog when the run
/// ends, and does not wait for `end`.
pub fn define_script_ui(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> {
match crate::scriptui::install(&mut self.interp, items) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the global constructors `File` and `Folder`, whose file system work the host functions
/// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`,
/// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`,
/// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `setHidden`,
/// `createAlias`, `pick` (the file dialogs, where a run may wait), `encode`, `decode`,
/// `encodingAvailable`, `current` and `locations`, with the values `system` and `lineFeed` and
/// the messages `text.notOpen` and `text.badMode`. Each object keeps its path, its `error`
/// text, its open file's id, its encoding and its line feed in properties that are not
/// enumerable.
pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> {
match crate::file_classes::install(&mut self.interp, items) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the global `ExternalObject`. `new ExternalObject("lib:AdobeXMPScript")` defines the
/// globals `XMPMeta`, `XMPFile` and `XMPConst`; any other library name throws. `XMPFile` reads
/// and writes files through the host functions `xmpOpen` and `xmpWrite` of
/// [`Realm::define_file_classes`], which the host adds first; without `File` and `Folder`,
/// `XMPFile` throws. An `XMPFile` is open only in the run that opened it: each
/// [`Realm::reset_folder_current`] begins a new run for it, and [`Realm::run`] and
/// [`Realm::start`] do not. A successful close or a new file run releases its packet buffers.
/// Registered namespace storage counts toward the realm's heap limit.
/// After a successful installation, another call fails with an internal
/// error and preserves `ExternalObject` and registered namespaces. A failed installation can be retried.
pub fn define_external_object(&mut self) -> Result<(), RunError> {
match crate::xmp_classes::install(&mut self.interp) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose
/// prototype holds its members, and the global objects `instances`, each made from the
/// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be
/// replaced. A heap too small for them ends with the error the realm's next run would give.
pub fn define_host_classes(&mut self, classes: Vec<crate::HostClass>, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> {
match crate::host_classes::install(&mut self.interp, classes, instances) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the global properties `globals`: a name, the function that answers a read, and the
/// function that answers an assignment, each called with `undefined` as `this` (and the value
/// assigned). Assigning one without a setter keeps its value, and throws in strict mode code.
pub fn define_host_globals(&mut self, globals: Vec<(String, crate::HostFunction, Option<crate::HostFunction>)>) -> Result<(), RunError> {
match crate::host_classes::install_globals(&mut self.interp, globals) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has
/// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its
/// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught
/// exception and `$.error` are dropped first, as [`Realm::start`] drops them, so memory that only
/// they held is free for the reset.
pub fn reset_folder_current(&mut self) -> Result<(), RunError> {
self.interp.last_thrown = Value::Undefined;
self.interp.last_error = Value::Null;
match crate::file_classes::reset_current(&mut self.interp) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the script extensions: the global `localize(object, ...values)`, which gives a
/// localization object's text for the locale of [`Realm::localization`], the global
/// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text,
/// `Object.prototype.reflect`, which describes an object's properties and methods (a host
/// class's from its [`crate::HostClass`]), and the localized `Object.prototype.toString` while
/// [`crate::Localization::enabled`].
pub fn add_script_extensions(&mut self) -> Result<(), RunError> {
match crate::builtins::extensions::install(&mut self.interp) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the global constructor `UnitValue`, measurements with a magnitude and a unit, and has
/// the arithmetic, comparison and unary operators calculate with its objects
/// ([`crate::unit_value`]). A realm without it keeps the standard operators. A second call
/// after one that succeeded changes nothing; after one that failed, it installs everything
/// again.
pub fn add_unit_values(&mut self) -> Result<(), RunError> {
match crate::unit_value::install(&mut self.interp) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Defines the global function `name`, whose arguments arrive converted as `args` says
/// ([`crate::HostItem::Converted`]). Unlike a host object, a script may replace or delete it, as
/// it may a built-in function.
pub fn define_host_function(&mut self, name: &str, args: Vec<crate::Arg>, f: crate::HostFunction) -> Result<(), RunError> {
match self.interp.install_host_function(name, args, f) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// The locale `localize` reads, which the host's functions may change during a run.
pub fn localization(&self) -> std::rc::Rc<crate::Localization> {
self.interp.localization.clone()
}
/// Defines the global variable `name` holding the exception the last run did not catch
/// (`undefined` if there was none).
pub fn bind_last_thrown(&mut self, name: &str) {
let interp = &mut self.interp;
let v = interp.last_thrown.clone();
let global = interp.global;
let _ = interp.define(global, key(name), Prop::Data { value: v, flags: HIDDEN });
}
/// Sets the clock `Date.now()` and `new Date()` read: the current time in milliseconds since
/// 1970-01-01 UTC. By default it is the system clock; a wasm build has none, and its default
/// gives NaN.
pub fn set_clock(&mut self, clock: impl Fn() -> f64 + 'static) {
self.interp.date_host.clock = std::rc::Rc::new(clock);
}
/// Sets the time zone `Date` uses for local time: `offset` gives local time's offset from UTC
/// in milliseconds at a time value (milliseconds since 1970-01-01 UTC), so it can follow
/// daylight saving time. An offset that is not finite or is a day or more counts as 0. By
/// default local time is UTC.
pub fn set_time_zone(&mut self, offset: impl Fn(f64) -> f64 + 'static) {
self.interp.date_host.offset = std::rc::Rc::new(offset);
}
/// Calls `observe` with the text of each source the realm's scripts evaluate at run time, before
/// it is compiled: a string given to `eval` (direct or indirect), the parameters and body
/// `Function` joins, and a source an evaluator host function
/// ([`crate::HostItem::Evaluator`]) gives. Replaces an earlier observer.
pub fn observe_code(&mut self, observe: impl Fn(&[u16]) + 'static) {
self.interp.code_observer = Some(std::rc::Rc::new(observe));
}
/// Collects garbage now and returns the heap's estimated size in bytes afterwards.
pub fn collect_garbage(&mut self) -> usize {
self.interp.collect_garbage();
self.interp.heap.bytes
}
#[cfg(test)]
pub(crate) fn interp(&mut self) -> &mut Interp {
&mut self.interp
}
}