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