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