Skip to main content

quickjs/
lib.rs

1//! `quickjs` — an embeddable JavaScript engine written in pure Rust.
2//!
3//! The crate is being built as a drop-in replacement for
4//! [bellard/quickjs](https://github.com/bellard/quickjs); the language level
5//! tracked is the upstream release whose version string is
6//! [`COMPAT_VERSION`].
7//!
8//! # Current state (v0.15.3 — milestones M0–M12a)
9//!
10//! Source is parsed, compiled to bytecode and executed: [`Context::eval`] runs a
11//! script and returns its completion value, and [`Context::output`] holds whatever
12//! `print` wrote.
13//!
14//! ```
15//! let rt = quickjs::Runtime::new();
16//! let mut ctx = quickjs::Context::new(&rt);
17//! ctx.eval("print(1 + 1)").expect("runs");
18//! assert_eq!(ctx.output(), "2\n");
19//! ```
20//!
21//! The standard library covers `Object`, `Function`, `Array`, `String`, `Number`,
22//! `Math`, `JSON`, `Reflect`, `Date`, `RegExp`, `Symbol`, `Map`/`Set`, `BigInt`,
23//! TypedArray, `DataView`, the error classes and the `Iterator` helpers; the ES6+
24//! runtime is in place (class including private fields, destructuring, generators,
25//! `Proxy`, `Promise`/async, `for await`); and ES modules run through
26//! [`Context::eval_module`], or as precompiled bytecode through
27//! [`Context::eval_bytecode`] with no parser at hand.
28//!
29//! The host can call into the script and the script back into Rust:
30//! [`Context::set_global_function`], [`Context::set_global_constructor`],
31//! [`Context::call`], [`Context::new_object`], [`Context::set_property`].
32//!
33//! Resource limits are enforced rather than merely accepted:
34//! [`Runtime::set_memory_limit`] counts the payload *inside* containers (string
35//! encodings, array elements, `Map`/`Set` entries, `ArrayBuffer`), not just the GC
36//! boxes, and [`Runtime::set_stack_size`] bounds recursion by frame size. Both raise
37//! a catchable `InternalError` — `out of memory` and `stack overflow`, the
38//! reference's wording and class.
39//!
40//! # Not there yet
41//!
42//! Every gap below is a loud failure rather than a wrong answer:
43//!
44//! * `std`/`os` and the event loop live in `quickjs-host`, not here, so `setTimeout`
45//!   is undefined in a bare [`Context`]. The same goes for the other host-provided
46//!   globals — `queueMicrotask`, `structuredClone`, `performance` — and for `Intl`,
47//!   which is ECMA-402 rather than ECMA-262;
48//! * `Function.prototype.toString` answers with the original source for a function
49//!   written in source, but a *method* (`m(){}`, `get x(){}`) still reports the
50//!   `[native code]` form, and so does `TypedArray.prototype.toSpliced`, which the C
51//!   reference does not have either;
52//! * performance is **0.04×–0.18×** the C reference on the twelve measured cases
53//!   (`scripts/bench.sh` in the repository); there is no NaN boxing and no
54//!   superinstruction dispatch yet;
55//! * a handful of `Array` methods bound how many elements they will walk one at a time
56//!   (`MAX_ARRAY_LIKE`, `2^26`). The spec sets no such bound, but `{length: 2**53-1}` is
57//!   legal and a `fill`/`indexOf`/`copyWithin` over it would never return, so the range is
58//!   refused with a `RangeError` instead. Narrowing the range with `start`/`end` — which
59//!   is what test262's own near-integer-limit cases do — stays unaffected.
60//!
61//! Where the spec *does* set a bound, it is enforced and the error class matters:
62//! `push`, `unshift`, `splice` and `concat` throw a `TypeError` when the result length
63//! would pass `2^53 - 1` (§23.1.3.24 step 6 and siblings). Those checks were missing
64//! until v0.15.1, and their absence was not a wrong answer but a hang — `push` wrote a
65//! `length` past the exact-integer range and `unshift` fell into a `2^53`-iteration loop.
66//!
67//! Iteration is bounded where the spec has no bound, and the two cases are different:
68//! [`Interp::collect_iterable`] refuses past `MAX_ITEMS`, and `Array.from` counts as it
69//! walks. `Array.from` had neither until v0.15.2 — it drained the iterator into a `Vec`
70//! and only then ran the mapper, so `Array.from(neverEnding, () => { throw x })` hung
71//! instead of throwing `x`, and an endless iterator with no mapper hung outright.
72//! §23.1.2.1 interleaves the three steps for exactly this reason.
73//!
74//! One detail of the iterator protocol is easy to get wrong and worth naming: §7.4.3 reads
75//! `value` **only** when `done` is false. Reading it unconditionally ran a `value` getter on
76//! the terminal step, which made `AggregateError/errors-iterabletolist` collect three values
77//! where two exist and made every `Iterator.prototype` helper fail
78//! `next-method-returns-throwing-value-done`; fixing it cleared nineteen tests at once.
79//!
80//! See `docs/requirements.md` in the repository for the milestone plan and
81//! `docs/test262-status.md` for the measured language coverage.
82
83#![deny(unsafe_op_in_unsafe_fn)]
84#![warn(missing_docs)]
85
86pub use js_compile;
87pub use js_gc::{CollectStats, Gc, Heap, Trace, Tracer, WeakGc};
88pub use js_parse;
89
90mod bignum;
91
92pub mod bigint;
93pub mod builtins;
94pub mod insn;
95pub mod interp;
96pub mod memory;
97pub mod module;
98pub mod normalize;
99mod normalize_tables;
100pub mod object;
101/// The reference's `JS_PrintValue`, which lives in the *engine* (`quickjs.c`) and not in
102/// the host library. `std.__printObject` is a one-line wrapper over it, and so is the
103/// reporting of an uncaught exception — which is why this belongs here rather than in
104/// `quickjs-host`.
105pub mod print;
106// The engine lives in its own crate so that `quickjs-compile` can validate a `/…/u`
107// literal at parse time without depending on this one.
108pub use quickjs_regexp as regexp;
109mod tzif;
110pub mod value;
111
112pub use interp::{FdInterest, Interp, JsResult, Signal, Task, Turn};
113pub use memory::{ClassCensus, MemoryUsage};
114pub use object::{Callable, ClassDef, ClassId, Exotic, JsObject, ObjectKind, Opaque, Property};
115pub use value::{Cell, JsString, Value};
116
117/// Version string of the upstream QuickJS release this port tracks.
118pub const COMPAT_VERSION: &str = "2026-06-04";
119
120/// Why [`Context::eval_detailed`] failed, keeping the thrown value intact.
121///
122/// The distinction from [`Error`] is the whole reason this type exists: an embedding has to
123/// hand the thrown object back to its caller (the C API's `JS_GetException`), and once it
124/// has been turned into text that is no longer possible.
125#[derive(Debug, Clone)]
126pub enum EvalError {
127    /// The source did not compile. The text is already a rendered `SyntaxError`, because a
128    /// compile error has no object behind it — nothing ran, so there is nothing to throw.
129    Syntax(String),
130    /// The script threw this value.
131    Throw(Value),
132    /// The runtime ran out of memory.
133    OutOfMemory,
134}
135
136/// Error raised by the engine.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub enum Error {
139    /// The source did not parse, or did not compile.
140    Syntax(String),
141    /// The script threw, or the engine raised while running it.
142    Exception(String),
143    /// The feature/entry point exists in the API but is not implemented yet.
144    NotImplemented(&'static str),
145    /// The runtime exceeded its memory limit (`--memory-limit`).
146    OutOfMemory,
147    /// The runtime exceeded its stack limit (`--stack-size`).
148    StackOverflow,
149}
150
151impl Error {
152    /// A compile error, rendered the way the reference prints one.
153    ///
154    /// `SyntaxError: <message>` and, when the error has a position,
155    /// `    at <file>:<line>:<column>` on the next line. The reference gets this shape
156    /// from `js_std_dump_error` printing an exception object whose `stack` is those two
157    /// lines; we have no object yet (nothing has run), so the text is built directly.
158    ///
159    /// A parse error is not "`file: SyntaxError: L:C: message`", which is what the CLI
160    /// used to print: that put the file name where the reference puts nothing, and the
161    /// position where the reference puts the file name.
162    fn syntax(error: &js_parse::SyntaxError, file: &str) -> Error {
163        if error.positionless {
164            Error::Syntax(error.message.clone())
165        } else {
166            Error::Syntax(format!(
167                "{}\n    at {}:{}:{}",
168                error.message, file, error.span.start.line, error.span.start.column
169            ))
170        }
171    }
172}
173
174impl std::fmt::Display for Error {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match self {
177            Error::NotImplemented(what) => write!(f, "not implemented yet: {what}"),
178            // A compile error is a `SyntaxError` in the language, and saying so is not
179            // cosmetic: the conformance runner classifies a `negative:` test by the
180            // constructor name in the message, and the reference prints the same prefix.
181            Error::Syntax(what) => write!(f, "SyntaxError: {what}"),
182            Error::Exception(what) => write!(f, "{what}"),
183            Error::OutOfMemory => write!(f, "out of memory"),
184            Error::StackOverflow => write!(f, "stack overflow"),
185        }
186    }
187}
188
189impl std::error::Error for Error {}
190
191/// Convenience alias used throughout the crate.
192pub type Result<T> = std::result::Result<T, Error>;
193
194/// [`js_parse::is_module_source`], which is the rule `qjs` uses to decide module mode.
195///
196/// It lives in the parser because it is a question about source text, not about the
197/// engine: `qjsc` needs the same answer and has no business linking an interpreter to
198/// get it.
199pub use js_parse::is_module_source;
200
201/// A JavaScript runtime: one heap, one memory limit, one set of host hooks.
202///
203/// Mirrors the role of `JSRuntime` in the QuickJS C API.
204pub struct Runtime {
205    heap: Heap,
206    memory_limit: Option<usize>,
207    stack_size: Option<usize>,
208}
209
210impl Default for Runtime {
211    fn default() -> Self {
212        Self::new()
213    }
214}
215
216impl Runtime {
217    /// Create a runtime with default limits.
218    pub fn new() -> Runtime {
219        Runtime {
220            heap: Heap::new(),
221            memory_limit: None,
222            stack_size: None,
223        }
224    }
225
226    /// The runtime's object heap.
227    pub fn heap(&self) -> &Heap {
228        &self.heap
229    }
230
231    /// Equivalent of `JS_SetMemoryLimit`.
232    ///
233    /// Applied to the heap as well as recorded, because the heap is what enforces it and it
234    /// outlives every interpreter a context creates. Recording alone was a real bug: a host
235    /// that called `JS_SetMemoryLimit` *after* its first evaluation had no limit at all, and
236    /// `tests/c/embed.c` caught it by printing a 64 MiB array the limit should have refused.
237    pub fn set_memory_limit(&mut self, limit: Option<usize>) {
238        self.memory_limit = limit;
239        self.heap.set_memory_limit(limit);
240    }
241
242    /// Configured memory limit, if any.
243    pub fn memory_limit(&self) -> Option<usize> {
244        self.memory_limit
245    }
246
247    /// Equivalent of `JS_SetMaxStackSize`.
248    pub fn set_stack_size(&mut self, limit: Option<usize>) {
249        self.stack_size = limit;
250    }
251
252    /// Configured stack size limit, if any.
253    pub fn stack_size(&self) -> Option<usize> {
254        self.stack_size
255    }
256
257    /// Equivalent of `JS_RunGC`.
258    pub fn run_gc(&self) -> CollectStats {
259        self.heap.collect()
260    }
261}
262
263/// An execution context: a global object plus the builtins installed on it.
264///
265/// Mirrors the role of `JSContext` in the QuickJS C API.
266pub struct Context<'rt> {
267    runtime: &'rt Runtime,
268    /// The interpreter, created on first use.
269    interp: Option<Interp<'rt>>,
270    /// A loader the host installed, handed to the interpreter when it is built.
271    module_loader: Option<Box<dyn module::ModuleLoader>>,
272    /// The value of the last script, as `qjs` reports it.
273    last_value: Value,
274    /// The name a top-level script is compiled under, which is what `error.stack`
275    /// prints: `<cmdline>` for `-e`, a path for a file, `None` for `<input>`.
276    script_name: Option<String>,
277    /// The script arguments, as `qjs` exposes them through `scriptArgs`.
278    ///
279    /// Kept here and installed into the realm on first use, because the interpreter (and
280    /// so the global object) does not exist until something runs.
281    script_args: Option<Vec<String>>,
282    /// Whether a rejection nobody handled is reported as an error.
283    ///
284    /// The reference's `--no-unhandled-rejection` clears the host's rejection tracker, so
285    /// this is a *context* setting there — not a decision the CLI makes after the fact.
286    /// It has to be that way round: `eval` reports an unhandled rejection as an error the
287    /// moment the script returns, long before any event loop sees it.
288    track_unhandled_rejection: bool,
289}
290
291impl<'rt> Context<'rt> {
292    /// Create a context on `runtime`.
293    pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
294        Context {
295            runtime,
296            interp: None,
297            module_loader: None,
298            last_value: Value::Undefined,
299            script_name: None,
300            script_args: None,
301            track_unhandled_rejection: true,
302        }
303    }
304
305    /// `qjs --no-unhandled-rejection`: forget unhandled rejections instead of failing.
306    ///
307    /// Off means a rejection nobody listened to is neither printed nor reported — the
308    /// script's outcome is what it would have been had the promise been handled. This is
309    /// the reference's semantics, and it is what a conformance runner wants: test262 judges
310    /// a test by what it asserts, and the policy on stray rejections is the host's.
311    pub fn set_track_unhandled_rejection(&mut self, track: bool) {
312        self.track_unhandled_rejection = track;
313    }
314
315    /// Whether unhandled rejections are reported. See
316    /// [`Context::set_track_unhandled_rejection`].
317    pub fn tracks_unhandled_rejection(&self) -> bool {
318        self.track_unhandled_rejection
319    }
320
321    /// Install how module specifiers are resolved and read.
322    ///
323    /// Without one, importing is a clear error rather than a silent failure: the engine
324    /// cannot guess whether `./x.js` means a file, and the host is what knows.
325    pub fn set_module_loader(&mut self, loader: Box<dyn module::ModuleLoader>) {
326        // A context that has already run something owns a live interpreter, so the loader
327        // goes to whichever exists.
328        if let Some(interp) = self.interp.as_mut() {
329            interp.module_loader = Some(loader);
330        } else {
331            self.module_loader = Some(loader);
332        }
333    }
334
335    /// Name the scripts this context evaluates, for stack traces.
336    ///
337    /// Mirrors what `qjs` passes to `JS_Eval`: `-e` code is `<cmdline>`, a script file
338    /// is its own path. Without a name, frames print `<input>`, which is what the
339    /// reference uses for code with no file behind it.
340    pub fn set_script_name(&mut self, name: impl Into<String>) {
341        self.script_name = Some(name.into());
342    }
343
344    /// Set the arguments `scriptArgs` should hold.
345    ///
346    /// Element 0 is the script itself, matching `qjs`: `qjs f.js a b` gives
347    /// `["f.js", "a", "b"]`. With `-e` there is no script, so the array is just the
348    /// trailing arguments and `-e`'s own text never appears in it.
349    ///
350    /// This was parsed by the CLI and then dropped on the floor: `opts.script_args` was
351    /// assigned in two places and read in none, so `scriptArgs` was simply undeclared.
352    /// An ordinary script's `if (typeof scriptArgs != "undefined")` branch therefore never
353    /// ran, and `examples/pi_bigint.js` printed a thousand digits of pi where the
354    /// reference printed `usage: pi n_digits`.
355    ///
356    /// Works whether or not the interpreter exists yet. The realm is built on first use,
357    /// so a host that installs something *else* first (an output sink, a host function)
358    /// would otherwise create it early and have these arguments silently dropped — which
359    /// is exactly what `print(JSON.stringify(scriptArgs))` caught.
360    pub fn set_script_args(&mut self, args: Vec<String>) {
361        if let Some(interp) = self.interp.as_mut() {
362            install_script_args(interp, &args);
363        } else {
364            self.script_args = Some(args);
365        }
366    }
367
368    /// The runtime this context belongs to.
369    pub fn runtime(&self) -> &'rt Runtime {
370        self.runtime
371    }
372
373    /// Everything `print` has written.
374    pub fn output(&self) -> &str {
375        self.interp.as_ref().map_or("", |interp| &interp.output)
376    }
377
378    /// The interpreter, for a host layer that has to run JavaScript from inside a native
379    /// callback.
380    ///
381    /// This is the same interpreter [`Context::interp`] builds on first use; it is public
382    /// because a callback C code re-enters (the C ABI layer's `JS_GetPropertyStr` and
383    /// friends) needs a `&mut Interp` that outlives the one closure invocation it was
384    /// handed. The interpreter's address is stable — the `Context` owns it behind an
385    /// `Option` in a boxed struct, so it never moves once created — and that is exactly the
386    /// property the C side depends on.
387    pub fn interp_mut(&mut self) -> &mut Interp<'rt> {
388        self.interp()
389    }
390
391    /// The interpreter, creating it and its realm on first use.
392    fn interp(&mut self) -> &mut Interp<'rt> {
393        let heap: &'rt Heap = &self.runtime.heap;
394        let loader = self.module_loader.take();
395        let script_args = self.script_args.take();
396        let memory_limit = self.runtime.memory_limit;
397        let stack_size = self.runtime.stack_size;
398        self.interp.get_or_insert_with(|| {
399            let mut interp = Interp::new(heap);
400            interp.module_loader = loader;
401            // The limits are the runtime's, and the interpreter is created lazily on first
402            // use — so they have to be handed over here rather than in `Runtime`. `None`
403            // means the defaults, which are the reference's: no memory cap, and
404            // `JS_DEFAULT_STACK_SIZE`.
405            heap.set_memory_limit(memory_limit);
406            if let Some(size) = stack_size {
407                interp.stack_limit = size;
408            }
409            if let Some(args) = script_args {
410                install_script_args(&mut interp, &args);
411            }
412            interp
413        })
414    }
415    /// Evaluate `specifier` as the entry module, the way `qjs -m` does.
416    ///
417    /// The microtask queue is drained afterwards, so a module whose top level launched an
418    /// async task has finished it by the time this returns.
419    pub fn eval_module(&mut self, specifier: &str) -> Result<Value> {
420        let loader = self.module_loader.take();
421        let track = self.track_unhandled_rejection;
422        let interp = self.interp();
423        if interp.module_loader.is_none() {
424            interp.module_loader = loader;
425        }
426        match interp.run_main_module(specifier) {
427            Ok(value) => {
428                let drained = interp.drain_jobs();
429                let unhandled = reported_unhandled(interp, track);
430                if let Err(Signal::Throw(reason)) = drained {
431                    let text = interp.describe_exception(&reason);
432                    return Err(Error::Exception(text));
433                }
434                if !unhandled.is_empty() {
435                    return Err(Error::Exception(unhandled.join("\n")));
436                }
437                self.last_value = value.clone();
438                Ok(value)
439            }
440            Err(Signal::Throw(value)) => {
441                let text = interp.describe_exception(&value);
442                Err(Error::Exception(text))
443            }
444            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
445        }
446    }
447
448    /// Evaluate an already-compiled bytecode blob, as an AOT binary does.
449    ///
450    /// Nothing is parsed and nothing is compiled: the input is
451    /// [`js_compile::serialize::serialize`]'s output, which carries the file name, the
452    /// optional source text and the module tables alongside the code. A blob with module
453    /// tables is run the way `qjs -m` runs a file — its requests are resolved through the
454    /// installed module loader, so a precompiled entry module can still import ordinary
455    /// source files.
456    ///
457    /// A blob is only accepted when its format *version* matches this build. Bytecode and
458    /// the opcode table are one unit, so a stale blob is rejected instead of being read
459    /// as different instructions.
460    pub fn eval_bytecode(&mut self, bytes: &[u8]) -> Result<Value> {
461        let code = js_compile::serialize::deserialize(bytes)
462            .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
463        let is_module = code.module.is_some();
464        let loader = self.module_loader.take();
465        let track = self.track_unhandled_rejection;
466        let interp = self.interp();
467        if interp.module_loader.is_none() {
468            interp.module_loader = loader;
469        }
470        let outcome = if is_module {
471            interp.run_precompiled_module(code)
472        } else {
473            interp.run_script(code)
474        };
475        match outcome {
476            Ok(value) => {
477                // An unhandled rejection is fatal *after* the body finishes, which is when
478                // the reference decides nothing else will claim it. The body's own output
479                // has already been buffered, so it still prints first.
480                let drained = interp.drain_jobs();
481                let unhandled = reported_unhandled(interp, track);
482                if let Err(Signal::Throw(reason)) = drained {
483                    let text = interp.describe_exception(&reason);
484                    return Err(Error::Exception(text));
485                }
486                if !unhandled.is_empty() {
487                    return Err(Error::Exception(unhandled.join("\n")));
488                }
489                self.last_value = value.clone();
490                Ok(value)
491            }
492            Err(Signal::Throw(value)) => {
493                let text = interp.describe_exception(&value);
494                Err(Error::Exception(text))
495            }
496            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
497        }
498    }
499
500    /// Register a module from bytecode, so an import of it never reaches the loader.
501    ///
502    /// This is the second half of AOT for modules: `qjsc` compiles every module the program
503    /// can reach into a blob, and the product registers them all before running the entry
504    /// one. The name comes from the blob (`qjsc` stamped it), and it is the name the loader
505    /// would have produced, so `import "./dep.js"` finds it.
506    pub fn register_module(&mut self, bytes: &[u8]) -> Result<String> {
507        let code = js_compile::serialize::deserialize(bytes)
508            .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
509        if code.module.is_none() {
510            return Err(Error::Syntax(
511                "invalid bytecode: this blob is a script, not a module".to_string(),
512            ));
513        }
514        let interp = self.interp();
515        match interp.register_module(code) {
516            Ok(name) => Ok(name),
517            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
518            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
519        }
520    }
521
522    /// Register a JSON, text or bytes module from its bytes, by name.
523    ///
524    /// `attributes` is the module's `with { type: … }` list, or empty for the name's
525    /// extension to decide — the same rule the loader applies.
526    pub fn register_data_module(
527        &mut self,
528        name: &str,
529        source: Vec<u8>,
530        attributes: &[(String, String)],
531    ) -> Result<()> {
532        let interp = self.interp();
533        match interp.register_data_module(name, source, attributes) {
534            Ok(()) => Ok(()),
535            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
536            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
537        }
538    }
539
540    /// Evaluate `source` as a global script and return its completion value.
541    ///
542    /// The value is reported the way `qjs -e` reports it: a string for anything the
543    /// script leaves on the stack, and nothing at all for `undefined`.
544    pub fn eval(&mut self, source: &str) -> Result<Value> {
545        self.eval_in(source, false)
546    }
547
548    /// [`Context::eval`] with the whole script strict from its first token.
549    ///
550    /// This is `qjs --strict`, and the reason it is a parse *mode* rather than a prepended
551    /// `"use strict"`: a directive shifts every column on the first line, and those
552    /// columns are what a stack trace reports. The reference does the same thing one level
553    /// down, with `JS_EVAL_FLAG_STRICT`.
554    pub fn eval_strict(&mut self, source: &str) -> Result<Value> {
555        self.eval_in(source, true)
556    }
557
558    /// Evaluate a global script, keeping the thrown *value* rather than a rendering of it.
559    ///
560    /// [`Context::eval`] answers an [`Error`] whose exception case is already text — that is
561    /// what a CLI prints. An embedding needs the value itself: the C API's `JS_Eval` stores
562    /// it as the context's pending exception and `JS_GetException` hands the very object a
563    /// script threw to C, which then reads `.name`, `.message` or any custom property off
564    /// it.
565    ///
566    /// `name` becomes the script name, which is what stack frames and syntax errors report;
567    /// it is scoped to this call so two `JS_Eval`s with different names do not leak into
568    /// each other's traces.
569    pub fn eval_detailed(
570        &mut self,
571        source: &str,
572        name: &str,
573    ) -> std::result::Result<Value, EvalError> {
574        let program = js_parse::parse_script(source)
575            .map_err(|error| EvalError::Syntax(Error::syntax(&error, name).to_string()))?;
576        let mut code = js_compile::compile_script_with_source(&program, source)
577            .map_err(|error| EvalError::Syntax(Error::syntax(&error, name).to_string()))?;
578        code.set_filename(name);
579        let interp = self.interp();
580        match interp.run_script(code) {
581            Ok(value) => {
582                self.last_value = value.clone();
583                Ok(value)
584            }
585            Err(Signal::Throw(value)) => Err(EvalError::Throw(value)),
586            Err(Signal::OutOfMemory) => Err(EvalError::OutOfMemory),
587        }
588    }
589
590    fn eval_in(&mut self, source: &str, strict: bool) -> Result<Value> {
591        let program = if strict {
592            js_parse::parse_script_strict(source)
593        } else {
594            js_parse::parse_script(source)
595        }
596        .map_err(|error| Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>")))?;
597        let mut code =
598            js_compile::compile_script_with_source(&program, source).map_err(|error| {
599                Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>"))
600            })?;
601        // Position information travels with the code, but the file name is the host's
602        // to supply — the parser never sees it.
603        code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
604        let track = self.track_unhandled_rejection;
605        let interp = self.interp();
606        match interp.run_script(code) {
607            Ok(value) => {
608                // An unhandled rejection is fatal *after* the script finishes, which is
609                // when the reference decides nothing else will claim it. The script's own
610                // output has already been buffered, so it still prints first.
611                let unhandled = reported_unhandled(interp, track);
612                if !unhandled.is_empty() {
613                    return Err(Error::Exception(unhandled.join("\n")));
614                }
615                self.last_value = value.clone();
616                Ok(value)
617            }
618            Err(Signal::Throw(value)) => {
619                let text = interp.describe_exception(&value);
620                Err(Error::Exception(text))
621            }
622            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
623        }
624    }
625
626    /// The value of the script that ran last.
627    pub fn last_value(&self) -> &Value {
628        &self.last_value
629    }
630
631    // -----------------------------------------------------------------------
632    // Host surface: what an embedding needs to expose its own functions.
633    //
634    // These are narrow on purpose. Handing the host `&mut Interp` would let it hold a
635    // borrow that outlives the `Context`, and every method here would have to be
636    // re-derived at each call site. Each one below is a single well-defined operation.
637    // -----------------------------------------------------------------------
638
639    /// A host function as a value, for putting on an object rather than the global.
640    ///
641    /// [`Context::set_global_function`] is this plus the install; a host *module* needs the
642    /// function first and the install second, on its own object.
643    pub fn new_host_function_value(
644        &mut self,
645        name: &str,
646        length: u32,
647        f: crate::object::HostFn,
648    ) -> Result<Value> {
649        let interp = self.interp();
650        Ok(Value::Object(interp.new_host_function(name, length, f)))
651    }
652
653    /// Install `value` on the global object as `name`.
654    ///
655    /// A host module is one object with functions on it, so mounting `std` is a single
656    /// `set_global` rather than a function per name — which is what
657    /// [`Context::set_global_function`] does.
658    pub fn set_global(&mut self, name: &str, value: Value) -> Result<()> {
659        let global = self.interp().realm.global.clone();
660        global.define(name, Property::with_attributes(value, true, false));
661        Ok(())
662    }
663
664    /// Install `f` on the global object as `name`.
665    ///
666    /// This is how a host module is built: `std.loadFile` is a global function the host
667    /// registers before the script runs. The closure may capture Rust state but **must
668    /// not capture a [`Gc`]** — see [`crate::object::HostFn`].
669    pub fn set_global_function(
670        &mut self,
671        name: &str,
672        length: u32,
673        f: crate::object::HostFn,
674    ) -> Result<()> {
675        let interp = self.interp();
676        let function = interp.new_host_function(name, length, f);
677        let global = interp.realm.global.clone();
678        global.define(
679            name,
680            Property::with_attributes(Value::Object(function), true, false),
681        );
682        Ok(())
683    }
684
685    /// Install `f` on the global object as the constructor `name`.
686    ///
687    /// Unlike [`Context::set_global_function`] this one gets a `prototype` object, which
688    /// it owns and which `new` uses — the shape a host class like `std.File` needs.
689    /// Returns the constructor so the host can put methods on its `prototype`.
690    pub fn set_global_constructor(
691        &mut self,
692        name: &str,
693        length: u32,
694        f: crate::object::HostFn,
695    ) -> Result<Value> {
696        let interp = self.interp();
697        let function = interp.new_host_ctor(name, length, f);
698        let global = interp.realm.global.clone();
699        global.define(
700            name,
701            Property::with_attributes(Value::Object(function.clone()), true, false),
702        );
703        Ok(Value::Object(function))
704    }
705
706    /// Call a JavaScript function from Rust.
707    ///
708    /// A thrown value comes back as [`Error::Exception`], so a host callback can report
709    /// the script's own error rather than swallowing it.
710    pub fn call(&mut self, function: Value, this: Value, args: Vec<Value>) -> Result<Value> {
711        let interp = self.interp();
712        match interp.call_value(function, this, args) {
713            Ok(value) => Ok(value),
714            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
715            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
716        }
717    }
718
719    /// A fresh empty object, for the host to hand back to a script.
720    pub fn new_object(&mut self) -> Value {
721        let interp = self.interp();
722        let proto = interp.realm.object_proto.clone();
723        Value::Object(interp.new_object(Some(proto)))
724    }
725
726    /// Set `name` on `object` to `value`, as a plain writable property.
727    pub fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
728        let Some(object) = object.as_object() else {
729            return Err(Error::Exception("set_property on a non-object".to_string()));
730        };
731        object.define(name, Property::with_attributes(value, true, true));
732        Ok(())
733    }
734
735    /// Define `name` on `object` as a **non-enumerable** data property.
736    ///
737    /// [`Context::set_property`] writes an enumerable property, which is right for the
738    /// members of a host module — `Object.keys(std)` should list them. A method on a host
739    /// class prototype is the opposite: `quickjs-libc.c` defines the seventeen `FILE`
740    /// methods with `JS_CFUNC_DEF`, whose flags leave `enumerable` off, so
741    /// `Object.keys(std.out)` is `[]` in the reference. A host class needs the same.
742    pub fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
743        let Some(object) = object.as_object() else {
744            return Err(Error::Exception(
745                "define_hidden on a non-object".to_string(),
746            ));
747        };
748        object.define(name, Property::with_attributes(value, true, false));
749        Ok(())
750    }
751
752    /// A new ordinary object whose prototype is `proto`.
753    ///
754    /// [`Context::new_object`] gives an object whose prototype is `Object.prototype`; a
755    /// host class needs instances that inherit from its own prototype instead.
756    pub fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value> {
757        let Some(proto) = proto.as_object() else {
758            return Err(Error::Exception("prototype is not an object".to_string()));
759        };
760        let proto = proto.clone();
761        let interp = self.interp();
762        Ok(Value::Object(interp.new_object(Some(proto))))
763    }
764
765    /// The global object, for a host module that has to keep something reachable from
766    /// every host function it installs.
767    ///
768    /// A [`HostFn`](crate::object::HostFn) closure may not hold a `Gc` — the collector
769    /// cannot see into it — so a shared JavaScript value (a class prototype, say) has to
770    /// live where the collector already scans. The global object is the one object every
771    /// interpreter has.
772    pub fn global(&mut self) -> Value {
773        let interp = self.interp();
774        Value::Object(interp.realm.global.clone())
775    }
776
777    // -----------------------------------------------------------------------
778    // Host classes: the `JS_NewClass` / `JS_NewObjectProtoClass` / `JS_GetOpaque`
779    // surface an embedding needs to expose its own native object types.
780    // -----------------------------------------------------------------------
781
782    /// Register a class and get the id its instances will answer to (`JS_NewClassID` +
783    /// `JS_NewClass`).
784    ///
785    /// The definition carries the finalizer, the `gc_mark` callback and the exotic
786    /// methods; instances carry their own opaque payload from then on.
787    pub fn register_class(&mut self, def: crate::object::ClassDef) -> crate::object::ClassId {
788        self.interp().register_host_class(def)
789    }
790
791    /// Install the prototype that [`Context::new_class_instance`] uses when the host does
792    /// not name one (`JS_SetClassProto`).
793    pub fn set_class_proto(&mut self, id: crate::object::ClassId, proto: &Value) -> Result<()> {
794        let Some(proto) = proto.as_object() else {
795            return Err(Error::Exception(
796                "class prototype is not an object".to_string(),
797            ));
798        };
799        let proto = proto.clone();
800        self.interp().set_host_class_proto(id, proto);
801        Ok(())
802    }
803
804    /// A new instance of class `id` (`JS_NewObjectProtoClass`).
805    ///
806    /// `proto` is the `new.target.prototype` a constructor pass-through would use; `None`
807    /// takes the registered prototype. An id that was never registered is an error: the C
808    /// API answers an exception there, and quietly making an ordinary object instead would
809    /// move the failure to the first `JS_GetOpaque` that no longer matches.
810    pub fn new_class_instance(
811        &mut self,
812        id: crate::object::ClassId,
813        proto: Option<&Value>,
814    ) -> Result<Value> {
815        let proto = match proto {
816            None => None,
817            Some(value) => match value.as_object() {
818                Some(object) => Some(object.clone()),
819                None => return Err(Error::Exception("prototype is not an object".to_string())),
820            },
821        };
822        self.interp()
823            .new_host_object(proto, id)
824            .map(Value::Object)
825            .ok_or_else(|| Error::Exception(format!("class {id} is not registered")))
826    }
827
828    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `id`.
829    pub fn class_opaque(
830        &mut self,
831        value: &Value,
832        id: crate::object::ClassId,
833    ) -> Option<crate::object::Opaque> {
834        self.interp().host_opaque(value, id)
835    }
836
837    /// `JS_SetOpaque`: store a payload on `value`, answering whether it is an instance of
838    /// *some* host class.
839    pub fn set_class_opaque(&mut self, value: &Value, opaque: crate::object::Opaque) -> bool {
840        self.interp().set_host_opaque(value, opaque)
841    }
842
843    /// A string value.
844    pub fn new_string(&mut self, text: &str) -> Value {
845        let interp = self.interp();
846        interp.string(text)
847    }
848
849    /// A number value.
850    pub fn new_number(&mut self, number: f64) -> Value {
851        Value::Float(number)
852    }
853
854    /// A boolean value.
855    pub fn new_boolean(&mut self, value: bool) -> Value {
856        Value::Bool(value)
857    }
858
859    /// Route `print`'s output to `sink` as it happens, in addition to the buffer
860    /// [`Context::output`] reads.
861    ///
862    /// Without a sink a script's output appears only when it finishes. A timer callback
863    /// printing *after* earlier output has to be observably later, which needs the write
864    /// to go out at the moment `print` runs.
865    pub fn set_output_sink(&mut self, sink: Box<dyn std::io::Write>) {
866        self.interp().output_sink = Some(sink);
867    }
868
869    /// Parse `text` in the extended JSON dialect: comments, unquoted keys, single quotes,
870    /// trailing commas, `+1`/`.1`/`0o10`/`0xa0`, and `Infinity`/`NaN`.
871    ///
872    /// This is what backs `std.parseExtJSON`. It is a separate entry point rather than a
873    /// flag on `JSON.parse` because the two must never share behaviour: a relaxed
874    /// `JSON.parse` would silently accept documents the standard rejects.
875    pub fn parse_ext_json(&mut self, text: &str) -> Result<Value> {
876        let interp = self.interp();
877        match interp.parse_ext_json(text) {
878            Ok(value) => Ok(value),
879            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
880            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
881        }
882    }
883
884    /// Schedule `callback` to run after `delay_ms` milliseconds; returns the timer id.
885    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
886        self.interp().schedule_timer(callback, delay_ms)
887    }
888
889    /// A promise that resolves after `delay_ms` — `os.sleepAsync`.
890    pub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value> {
891        let interp = self.interp();
892        match interp.sleep_async(delay_ms) {
893            Ok(value) => Ok(value),
894            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
895            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
896        }
897    }
898
899    /// Register or clear an `os.signal` handler.
900    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
901        self.interp().set_signal_handler(signal, handler);
902    }
903
904    /// Run the handler for `signal`. `false` when none is registered.
905    pub fn fire_signal(&mut self, signal: i32) -> Result<bool> {
906        let interp = self.interp();
907        match interp.fire_signal(signal) {
908            Ok(ran) => Ok(ran),
909            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
910            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
911        }
912    }
913
914    /// Register or clear an `os.setReadHandler`/`os.setWriteHandler` callback.
915    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
916        self.interp().set_fd_handler(fd, readable, callback);
917    }
918
919    /// The descriptors the host must poll, and in which direction.
920    pub fn pending_fds(&self) -> Vec<FdInterest> {
921        // An interpreter that has not been created cannot have handlers: nothing has run.
922        self.interp
923            .as_ref()
924            .map(Interp::pending_fds)
925            .unwrap_or_default()
926    }
927
928    /// Report descriptor readiness, calling the handler. `false` when none was registered.
929    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> Result<bool> {
930        let interp = self.interp();
931        match interp.fire_fd(fd, readable, writable) {
932            Ok(ran) => Ok(ran),
933            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
934            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
935        }
936    }
937
938    /// Cancel a pending timer. `false` when the id is unknown or already fired.
939    pub fn cancel_timer(&mut self, id: i32) -> bool {
940        self.interp().cancel_timer(id)
941    }
942
943    /// Run one turn of the event loop, reporting what the caller should do next.
944    ///
945    /// [`crate::Turn::Wait`] carries the delay to block for; this method never blocks, so
946    /// an embedder decides what "wait" means (a thread sleep, a tokio timer, a test clock).
947    pub fn run_one_turn(&mut self) -> Result<crate::Turn> {
948        let interp = self.interp();
949        match interp.run_one_turn() {
950            Ok(turn) => Ok(turn),
951            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
952            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
953        }
954    }
955
956    /// Whether any microtask or timer is still pending.
957    pub fn has_pending_work(&self) -> bool {
958        self.interp.as_ref().is_some_and(Interp::has_pending_work)
959    }
960
961    /// Whether a timer or a microtask is pending, ignoring registered descriptors.
962    ///
963    /// A REPL whose stdin is at end of file still has a read handler registered, and that
964    /// handler will keep firing without ever producing another line — so "there is work"
965    /// has to mean something narrower than [`Context::has_pending_work`] there.
966    pub fn has_pending_timers_or_jobs(&self) -> bool {
967        self.interp
968            .as_ref()
969            .is_some_and(Interp::has_pending_timers_or_jobs)
970    }
971
972    /// Rejections nobody handled, drained.
973    ///
974    /// [`Context::eval`] turns these into an error, but an event loop needs them *after*
975    /// every turn rather than at the end of one script: a promise may only become
976    /// unhandled later.
977    ///
978    /// Empty when [`Context::set_track_unhandled_rejection`] is off — the entries are still
979    /// drained, so a later turn cannot report one either.
980    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
981        let track = self.track_unhandled_rejection;
982        match self.interp.as_mut() {
983            Some(interp) => reported_unhandled(interp, track),
984            None => Vec::new(),
985        }
986    }
987
988    /// Errors that timer callbacks threw, drained.
989    pub fn take_timer_errors(&mut self) -> Vec<String> {
990        match self.interp.as_mut() {
991            Some(interp) => interp.take_timer_errors(),
992            None => Vec::new(),
993        }
994    }
995
996    /// Measure what this context occupies, as `qjs -d` and `JS_ComputeMemoryUsage` report it.
997    ///
998    /// O(live heap blocks): it walks the registry rather than reading counters, so it cannot
999    /// drift the way a counter incremented at two hundred call sites can. Call it behind a
1000    /// debug flag, not in a loop.
1001    pub fn memory_usage(&mut self) -> (MemoryUsage, ClassCensus) {
1002        // The interpreter has to exist for the realm's own objects to be in the measurement
1003        // — building it here is the difference between "an empty heap" and "a realm".
1004        self.interp();
1005        memory::compute(&self.runtime.heap)
1006    }
1007
1008    /// The same measurement, rendered as the report `qjs -d` prints.
1009    pub fn dump_memory_usage(&mut self) -> String {
1010        let (usage, census) = self.memory_usage();
1011        memory::dump(&usage, &census)
1012    }
1013
1014    /// Take the buffered output, leaving the buffer empty.
1015    ///
1016    /// For a host that keeps running turns: [`Context::output`] grows without bound, so
1017    /// draining after each turn bounds the memory without changing what any one
1018    /// assertion sees.
1019    pub fn take_output(&mut self) -> String {
1020        match self.interp.as_mut() {
1021            Some(interp) => std::mem::take(&mut interp.output),
1022            None => String::new(),
1023        }
1024    }
1025}
1026
1027/// What a host module needs from the engine, whichever way the engine was reached.
1028///
1029/// A host module (`std`, `os`) is installed from two different places, and until this trait
1030/// existed the two could not share one implementation:
1031///
1032/// * `qjs --std` installs at startup, holding a [`Context`] — that is what every host
1033///   function value is created through;
1034/// * `import * as std from "std"` installs *inside a running interpreter*, because
1035///   [`module::ModuleLoader::load_native`] is handed `&mut Interp` and nothing else. A
1036///   `Context` cannot be conjured from an `Interp`: the `Context` owns the interpreter.
1037///
1038/// So the handful of operations a host module actually performs are named here, and both
1039/// types provide them. Keeping the five methods rather than "just call the interpreter"
1040/// preserves the reason [`Context`]'s host surface exists at all: a `HostFn` closure may
1041/// not capture a [`Gc`](crate::Gc), so host code reaches shared values through the global
1042/// object, and that is one of the five.
1043pub trait HostSurface {
1044    /// A host function as a value, for putting on an object rather than the global.
1045    fn new_host_function_value(
1046        &mut self,
1047        name: &str,
1048        length: u32,
1049        f: crate::object::HostFn,
1050    ) -> Result<Value>;
1051
1052    /// A string value.
1053    fn new_string(&mut self, text: &str) -> Value;
1054
1055    /// A fresh empty object whose prototype is `Object.prototype`.
1056    ///
1057    /// Named `new_plain_object` rather than `new_object` because [`Interp`] already has a
1058    /// `new_object(Option<Gc<JsObject>>)`; two methods of the same name on one type would
1059    /// make every call site ambiguous.
1060    fn new_plain_object(&mut self) -> Value;
1061
1062    /// A fresh empty object whose prototype is `proto`.
1063    fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value>;
1064
1065    /// The global object — where a host module parks what its closures cannot capture.
1066    fn global(&mut self) -> Value;
1067
1068    /// Define `name` on `object` as a **non-enumerable** data property.
1069    fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()>;
1070
1071    /// Define `name` on `object` as an **enumerable** data property.
1072    fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()>;
1073
1074    /// The own data property `name` of `object`, if it has one.
1075    fn hidden(&mut self, object: &Value, name: &str) -> Option<Value>;
1076}
1077
1078impl HostSurface for Context<'_> {
1079    fn new_host_function_value(
1080        &mut self,
1081        name: &str,
1082        length: u32,
1083        f: crate::object::HostFn,
1084    ) -> Result<Value> {
1085        Context::new_host_function_value(self, name, length, f)
1086    }
1087
1088    fn new_string(&mut self, text: &str) -> Value {
1089        Context::new_string(self, text)
1090    }
1091
1092    fn new_plain_object(&mut self) -> Value {
1093        Context::new_object(self)
1094    }
1095
1096    fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value> {
1097        Context::new_object_with_prototype(self, proto)
1098    }
1099
1100    fn global(&mut self) -> Value {
1101        Context::global(self)
1102    }
1103
1104    fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
1105        Context::define_hidden(self, object, name, value)
1106    }
1107
1108    fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
1109        Context::set_property(self, object, name, value)
1110    }
1111
1112    fn hidden(&mut self, object: &Value, name: &str) -> Option<Value> {
1113        let object = object.as_object()?;
1114        object.own_property(name)?.value
1115    }
1116}
1117
1118impl HostSurface for Interp<'_> {
1119    fn new_host_function_value(
1120        &mut self,
1121        name: &str,
1122        length: u32,
1123        f: crate::object::HostFn,
1124    ) -> Result<Value> {
1125        Ok(Value::Object(self.new_host_function(name, length, f)))
1126    }
1127
1128    fn new_string(&mut self, text: &str) -> Value {
1129        self.string(text)
1130    }
1131
1132    fn new_plain_object(&mut self) -> Value {
1133        let proto = self.realm.object_proto.clone();
1134        Value::Object(self.new_object(Some(proto)))
1135    }
1136
1137    fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value> {
1138        let Some(proto) = proto.as_object() else {
1139            return Err(Error::Exception("prototype is not an object".to_string()));
1140        };
1141        let proto = proto.clone();
1142        Ok(Value::Object(self.new_object(Some(proto))))
1143    }
1144
1145    fn global(&mut self) -> Value {
1146        Value::Object(self.realm.global.clone())
1147    }
1148
1149    fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
1150        let Some(object) = object.as_object() else {
1151            return Err(Error::Exception(
1152                "define_hidden on a non-object".to_string(),
1153            ));
1154        };
1155        object.define(name, Property::with_attributes(value, true, false));
1156        Ok(())
1157    }
1158
1159    fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
1160        let Some(object) = object.as_object() else {
1161            return Err(Error::Exception("set_property on a non-object".to_string()));
1162        };
1163        object.define(name, Property::with_attributes(value, true, true));
1164        Ok(())
1165    }
1166
1167    fn hidden(&mut self, object: &Value, name: &str) -> Option<Value> {
1168        let object = object.as_object()?;
1169        object.own_property(name)?.value
1170    }
1171}
1172
1173/// Put `scriptArgs` on the global object.
1174///
1175/// `scriptArgs` is a host addition, like `print`, so it is installed from the host side
1176/// rather than by the realm's builtins. `qjs` defines it only when there is something to
1177/// put in it, which is why `-e` with no trailing arguments still leaves an empty array
1178/// rather than an absent binding.
1179fn install_script_args(interp: &mut Interp<'_>, args: &[String]) {
1180    let elements = args
1181        .iter()
1182        .map(|arg| interp.string(arg.clone()))
1183        .collect::<Vec<_>>();
1184    let array = interp.new_array(elements);
1185    interp
1186        .realm
1187        .global
1188        .clone()
1189        .define_data("scriptArgs", Value::Object(array));
1190}
1191
1192/// The rejections to report, honouring the tracking switch.
1193///
1194/// A free function rather than a method because the call sites hold a mutable borrow of the
1195/// interpreter — `self.interp()` — and `&self` cannot be taken while that is alive.
1196fn reported_unhandled(interp: &mut Interp<'_>, track: bool) -> Vec<String> {
1197    let unhandled = interp.take_unhandled_rejections();
1198    if track { unhandled } else { Vec::new() }
1199}