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