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}
258
259impl<'rt> Context<'rt> {
260    /// Create a context on `runtime`.
261    pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
262        Context {
263            runtime,
264            interp: None,
265            module_loader: None,
266            last_value: Value::Undefined,
267            script_name: None,
268            script_args: None,
269        }
270    }
271
272    /// Install how module specifiers are resolved and read.
273    ///
274    /// Without one, importing is a clear error rather than a silent failure: the engine
275    /// cannot guess whether `./x.js` means a file, and the host is what knows.
276    pub fn set_module_loader(&mut self, loader: Box<dyn module::ModuleLoader>) {
277        // A context that has already run something owns a live interpreter, so the loader
278        // goes to whichever exists.
279        if let Some(interp) = self.interp.as_mut() {
280            interp.module_loader = Some(loader);
281        } else {
282            self.module_loader = Some(loader);
283        }
284    }
285
286    /// Name the scripts this context evaluates, for stack traces.
287    ///
288    /// Mirrors what `qjs` passes to `JS_Eval`: `-e` code is `<cmdline>`, a script file
289    /// is its own path. Without a name, frames print `<input>`, which is what the
290    /// reference uses for code with no file behind it.
291    pub fn set_script_name(&mut self, name: impl Into<String>) {
292        self.script_name = Some(name.into());
293    }
294
295    /// Set the arguments `scriptArgs` should hold.
296    ///
297    /// Element 0 is the script itself, matching `qjs`: `qjs f.js a b` gives
298    /// `["f.js", "a", "b"]`. With `-e` there is no script, so the array is just the
299    /// trailing arguments and `-e`'s own text never appears in it.
300    ///
301    /// This was parsed by the CLI and then dropped on the floor: `opts.script_args` was
302    /// assigned in two places and read in none, so `scriptArgs` was simply undeclared.
303    /// An ordinary script's `if (typeof scriptArgs != "undefined")` branch therefore never
304    /// ran, and `examples/pi_bigint.js` printed a thousand digits of pi where the
305    /// reference printed `usage: pi n_digits`.
306    ///
307    /// Works whether or not the interpreter exists yet. The realm is built on first use,
308    /// so a host that installs something *else* first (an output sink, a host function)
309    /// would otherwise create it early and have these arguments silently dropped — which
310    /// is exactly what `print(JSON.stringify(scriptArgs))` caught.
311    pub fn set_script_args(&mut self, args: Vec<String>) {
312        if let Some(interp) = self.interp.as_mut() {
313            install_script_args(interp, &args);
314        } else {
315            self.script_args = Some(args);
316        }
317    }
318
319    /// The runtime this context belongs to.
320    pub fn runtime(&self) -> &'rt Runtime {
321        self.runtime
322    }
323
324    /// Everything `print` has written.
325    pub fn output(&self) -> &str {
326        self.interp.as_ref().map_or("", |interp| &interp.output)
327    }
328
329    /// The interpreter, for a host layer that has to run JavaScript from inside a native
330    /// callback.
331    ///
332    /// This is the same interpreter [`Context::interp`] builds on first use; it is public
333    /// because a callback C code re-enters (the C ABI layer's `JS_GetPropertyStr` and
334    /// friends) needs a `&mut Interp` that outlives the one closure invocation it was
335    /// handed. The interpreter's address is stable — the `Context` owns it behind an
336    /// `Option` in a boxed struct, so it never moves once created — and that is exactly the
337    /// property the C side depends on.
338    pub fn interp_mut(&mut self) -> &mut Interp<'rt> {
339        self.interp()
340    }
341
342    /// The interpreter, creating it and its realm on first use.
343    fn interp(&mut self) -> &mut Interp<'rt> {
344        let heap: &'rt Heap = &self.runtime.heap;
345        let loader = self.module_loader.take();
346        let script_args = self.script_args.take();
347        let memory_limit = self.runtime.memory_limit;
348        let stack_size = self.runtime.stack_size;
349        self.interp.get_or_insert_with(|| {
350            let mut interp = Interp::new(heap);
351            interp.module_loader = loader;
352            // The limits are the runtime's, and the interpreter is created lazily on first
353            // use — so they have to be handed over here rather than in `Runtime`. `None`
354            // means the defaults, which are the reference's: no memory cap, and
355            // `JS_DEFAULT_STACK_SIZE`.
356            heap.set_memory_limit(memory_limit);
357            if let Some(size) = stack_size {
358                interp.stack_limit = size;
359            }
360            if let Some(args) = script_args {
361                install_script_args(&mut interp, &args);
362            }
363            interp
364        })
365    }
366    /// Evaluate `specifier` as the entry module, the way `qjs -m` does.
367    ///
368    /// The microtask queue is drained afterwards, so a module whose top level launched an
369    /// async task has finished it by the time this returns.
370    pub fn eval_module(&mut self, specifier: &str) -> Result<Value> {
371        let loader = self.module_loader.take();
372        let interp = self.interp();
373        if interp.module_loader.is_none() {
374            interp.module_loader = loader;
375        }
376        match interp.run_main_module(specifier) {
377            Ok(value) => {
378                let drained = interp.drain_jobs();
379                let unhandled = interp.take_unhandled_rejections();
380                if let Err(Signal::Throw(reason)) = drained {
381                    let text = interp.describe_exception(&reason);
382                    return Err(Error::Exception(text));
383                }
384                if !unhandled.is_empty() {
385                    return Err(Error::Exception(unhandled.join("\n")));
386                }
387                self.last_value = value.clone();
388                Ok(value)
389            }
390            Err(Signal::Throw(value)) => {
391                let text = interp.describe_exception(&value);
392                Err(Error::Exception(text))
393            }
394            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
395        }
396    }
397
398    /// Evaluate an already-compiled bytecode blob, as an AOT binary does.
399    ///
400    /// Nothing is parsed and nothing is compiled: the input is
401    /// [`js_compile::serialize::serialize`]'s output, which carries the file name, the
402    /// optional source text and the module tables alongside the code. A blob with module
403    /// tables is run the way `qjs -m` runs a file — its requests are resolved through the
404    /// installed module loader, so a precompiled entry module can still import ordinary
405    /// source files.
406    ///
407    /// A blob is only accepted when its format *version* matches this build. Bytecode and
408    /// the opcode table are one unit, so a stale blob is rejected instead of being read
409    /// as different instructions.
410    pub fn eval_bytecode(&mut self, bytes: &[u8]) -> Result<Value> {
411        let code = js_compile::serialize::deserialize(bytes)
412            .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
413        let is_module = code.module.is_some();
414        let loader = self.module_loader.take();
415        let interp = self.interp();
416        if interp.module_loader.is_none() {
417            interp.module_loader = loader;
418        }
419        let outcome = if is_module {
420            interp.run_precompiled_module(code)
421        } else {
422            interp.run_script(code)
423        };
424        match outcome {
425            Ok(value) => {
426                // An unhandled rejection is fatal *after* the body finishes, which is when
427                // the reference decides nothing else will claim it. The body's own output
428                // has already been buffered, so it still prints first.
429                let drained = interp.drain_jobs();
430                let unhandled = interp.take_unhandled_rejections();
431                if let Err(Signal::Throw(reason)) = drained {
432                    let text = interp.describe_exception(&reason);
433                    return Err(Error::Exception(text));
434                }
435                if !unhandled.is_empty() {
436                    return Err(Error::Exception(unhandled.join("\n")));
437                }
438                self.last_value = value.clone();
439                Ok(value)
440            }
441            Err(Signal::Throw(value)) => {
442                let text = interp.describe_exception(&value);
443                Err(Error::Exception(text))
444            }
445            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
446        }
447    }
448
449    /// Register a module from bytecode, so an import of it never reaches the loader.
450    ///
451    /// This is the second half of AOT for modules: `qjsc` compiles every module the program
452    /// can reach into a blob, and the product registers them all before running the entry
453    /// one. The name comes from the blob (`qjsc` stamped it), and it is the name the loader
454    /// would have produced, so `import "./dep.js"` finds it.
455    pub fn register_module(&mut self, bytes: &[u8]) -> Result<String> {
456        let code = js_compile::serialize::deserialize(bytes)
457            .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
458        if code.module.is_none() {
459            return Err(Error::Syntax(
460                "invalid bytecode: this blob is a script, not a module".to_string(),
461            ));
462        }
463        let interp = self.interp();
464        match interp.register_module(code) {
465            Ok(name) => Ok(name),
466            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
467            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
468        }
469    }
470
471    /// Register a JSON, text or bytes module from its bytes, by name.
472    ///
473    /// `attributes` is the module's `with { type: … }` list, or empty for the name's
474    /// extension to decide — the same rule the loader applies.
475    pub fn register_data_module(
476        &mut self,
477        name: &str,
478        source: Vec<u8>,
479        attributes: &[(String, String)],
480    ) -> Result<()> {
481        let interp = self.interp();
482        match interp.register_data_module(name, source, attributes) {
483            Ok(()) => Ok(()),
484            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
485            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
486        }
487    }
488
489    /// Evaluate `source` as a global script and return its completion value.
490    ///
491    /// The value is reported the way `qjs -e` reports it: a string for anything the
492    /// script leaves on the stack, and nothing at all for `undefined`.
493    pub fn eval(&mut self, source: &str) -> Result<Value> {
494        self.eval_in(source, false)
495    }
496
497    /// [`Context::eval`] with the whole script strict from its first token.
498    ///
499    /// This is `qjs --strict`, and the reason it is a parse *mode* rather than a prepended
500    /// `"use strict"`: a directive shifts every column on the first line, and those
501    /// columns are what a stack trace reports. The reference does the same thing one level
502    /// down, with `JS_EVAL_FLAG_STRICT`.
503    pub fn eval_strict(&mut self, source: &str) -> Result<Value> {
504        self.eval_in(source, true)
505    }
506
507    /// Evaluate a global script, keeping the thrown *value* rather than a rendering of it.
508    ///
509    /// [`Context::eval`] answers an [`Error`] whose exception case is already text — that is
510    /// what a CLI prints. An embedding needs the value itself: the C API's `JS_Eval` stores
511    /// it as the context's pending exception and `JS_GetException` hands the very object a
512    /// script threw to C, which then reads `.name`, `.message` or any custom property off
513    /// it.
514    ///
515    /// `name` becomes the script name, which is what stack frames and syntax errors report;
516    /// it is scoped to this call so two `JS_Eval`s with different names do not leak into
517    /// each other's traces.
518    pub fn eval_detailed(
519        &mut self,
520        source: &str,
521        name: &str,
522    ) -> std::result::Result<Value, EvalError> {
523        let program = js_parse::parse_script(source)
524            .map_err(|error| EvalError::Syntax(Error::syntax(&error, name).to_string()))?;
525        let mut code = js_compile::compile_script(&program)
526            .map_err(|error| EvalError::Syntax(Error::syntax(&error, name).to_string()))?;
527        code.set_filename(name);
528        let interp = self.interp();
529        match interp.run_script(code) {
530            Ok(value) => {
531                self.last_value = value.clone();
532                Ok(value)
533            }
534            Err(Signal::Throw(value)) => Err(EvalError::Throw(value)),
535            Err(Signal::OutOfMemory) => Err(EvalError::OutOfMemory),
536        }
537    }
538
539    fn eval_in(&mut self, source: &str, strict: bool) -> Result<Value> {
540        let program = if strict {
541            js_parse::parse_script_strict(source)
542        } else {
543            js_parse::parse_script(source)
544        }
545        .map_err(|error| Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>")))?;
546        let mut code = js_compile::compile_script(&program).map_err(|error| {
547            Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>"))
548        })?;
549        // Position information travels with the code, but the file name is the host's
550        // to supply — the parser never sees it.
551        code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
552        let interp = self.interp();
553        match interp.run_script(code) {
554            Ok(value) => {
555                // An unhandled rejection is fatal *after* the script finishes, which is
556                // when the reference decides nothing else will claim it. The script's own
557                // output has already been buffered, so it still prints first.
558                let unhandled = interp.take_unhandled_rejections();
559                if !unhandled.is_empty() {
560                    return Err(Error::Exception(unhandled.join("\n")));
561                }
562                self.last_value = value.clone();
563                Ok(value)
564            }
565            Err(Signal::Throw(value)) => {
566                let text = interp.describe_exception(&value);
567                Err(Error::Exception(text))
568            }
569            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
570        }
571    }
572
573    /// The value of the script that ran last.
574    pub fn last_value(&self) -> &Value {
575        &self.last_value
576    }
577
578    // -----------------------------------------------------------------------
579    // Host surface: what an embedding needs to expose its own functions.
580    //
581    // These are narrow on purpose. Handing the host `&mut Interp` would let it hold a
582    // borrow that outlives the `Context`, and every method here would have to be
583    // re-derived at each call site. Each one below is a single well-defined operation.
584    // -----------------------------------------------------------------------
585
586    /// A host function as a value, for putting on an object rather than the global.
587    ///
588    /// [`Context::set_global_function`] is this plus the install; a host *module* needs the
589    /// function first and the install second, on its own object.
590    pub fn new_host_function_value(
591        &mut self,
592        name: &str,
593        length: u32,
594        f: crate::object::HostFn,
595    ) -> Result<Value> {
596        let interp = self.interp();
597        Ok(Value::Object(interp.new_host_function(name, length, f)))
598    }
599
600    /// Install `value` on the global object as `name`.
601    ///
602    /// A host module is one object with functions on it, so mounting `std` is a single
603    /// `set_global` rather than a function per name — which is what
604    /// [`Context::set_global_function`] does.
605    pub fn set_global(&mut self, name: &str, value: Value) -> Result<()> {
606        let global = self.interp().realm.global.clone();
607        global.define(name, Property::with_attributes(value, true, false));
608        Ok(())
609    }
610
611    /// Install `f` on the global object as `name`.
612    ///
613    /// This is how a host module is built: `std.loadFile` is a global function the host
614    /// registers before the script runs. The closure may capture Rust state but **must
615    /// not capture a [`Gc`]** — see [`crate::object::HostFn`].
616    pub fn set_global_function(
617        &mut self,
618        name: &str,
619        length: u32,
620        f: crate::object::HostFn,
621    ) -> Result<()> {
622        let interp = self.interp();
623        let function = interp.new_host_function(name, length, f);
624        let global = interp.realm.global.clone();
625        global.define(
626            name,
627            Property::with_attributes(Value::Object(function), true, false),
628        );
629        Ok(())
630    }
631
632    /// Install `f` on the global object as the constructor `name`.
633    ///
634    /// Unlike [`Context::set_global_function`] this one gets a `prototype` object, which
635    /// it owns and which `new` uses — the shape a host class like `std.File` needs.
636    /// Returns the constructor so the host can put methods on its `prototype`.
637    pub fn set_global_constructor(
638        &mut self,
639        name: &str,
640        length: u32,
641        f: crate::object::HostFn,
642    ) -> Result<Value> {
643        let interp = self.interp();
644        let function = interp.new_host_ctor(name, length, f);
645        let global = interp.realm.global.clone();
646        global.define(
647            name,
648            Property::with_attributes(Value::Object(function.clone()), true, false),
649        );
650        Ok(Value::Object(function))
651    }
652
653    /// Call a JavaScript function from Rust.
654    ///
655    /// A thrown value comes back as [`Error::Exception`], so a host callback can report
656    /// the script's own error rather than swallowing it.
657    pub fn call(&mut self, function: Value, this: Value, args: Vec<Value>) -> Result<Value> {
658        let interp = self.interp();
659        match interp.call_value(function, this, args) {
660            Ok(value) => Ok(value),
661            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
662            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
663        }
664    }
665
666    /// A fresh empty object, for the host to hand back to a script.
667    pub fn new_object(&mut self) -> Value {
668        let interp = self.interp();
669        let proto = interp.realm.object_proto.clone();
670        Value::Object(interp.new_object(Some(proto)))
671    }
672
673    /// Set `name` on `object` to `value`, as a plain writable property.
674    pub fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
675        let Some(object) = object.as_object() else {
676            return Err(Error::Exception("set_property on a non-object".to_string()));
677        };
678        object.define(name, Property::with_attributes(value, true, true));
679        Ok(())
680    }
681
682    /// Define `name` on `object` as a **non-enumerable** data property.
683    ///
684    /// [`Context::set_property`] writes an enumerable property, which is right for the
685    /// members of a host module — `Object.keys(std)` should list them. A method on a host
686    /// class prototype is the opposite: `quickjs-libc.c` defines the seventeen `FILE`
687    /// methods with `JS_CFUNC_DEF`, whose flags leave `enumerable` off, so
688    /// `Object.keys(std.out)` is `[]` in the reference. A host class needs the same.
689    pub fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
690        let Some(object) = object.as_object() else {
691            return Err(Error::Exception(
692                "define_hidden on a non-object".to_string(),
693            ));
694        };
695        object.define(name, Property::with_attributes(value, true, false));
696        Ok(())
697    }
698
699    /// A new ordinary object whose prototype is `proto`.
700    ///
701    /// [`Context::new_object`] gives an object whose prototype is `Object.prototype`; a
702    /// host class needs instances that inherit from its own prototype instead.
703    pub fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value> {
704        let Some(proto) = proto.as_object() else {
705            return Err(Error::Exception("prototype is not an object".to_string()));
706        };
707        let proto = proto.clone();
708        let interp = self.interp();
709        Ok(Value::Object(interp.new_object(Some(proto))))
710    }
711
712    /// The global object, for a host module that has to keep something reachable from
713    /// every host function it installs.
714    ///
715    /// A [`HostFn`](crate::object::HostFn) closure may not hold a `Gc` — the collector
716    /// cannot see into it — so a shared JavaScript value (a class prototype, say) has to
717    /// live where the collector already scans. The global object is the one object every
718    /// interpreter has.
719    pub fn global(&mut self) -> Value {
720        let interp = self.interp();
721        Value::Object(interp.realm.global.clone())
722    }
723
724    // -----------------------------------------------------------------------
725    // Host classes: the `JS_NewClass` / `JS_NewObjectProtoClass` / `JS_GetOpaque`
726    // surface an embedding needs to expose its own native object types.
727    // -----------------------------------------------------------------------
728
729    /// Register a class and get the id its instances will answer to (`JS_NewClassID` +
730    /// `JS_NewClass`).
731    ///
732    /// The definition carries the finalizer, the `gc_mark` callback and the exotic
733    /// methods; instances carry their own opaque payload from then on.
734    pub fn register_class(&mut self, def: crate::object::ClassDef) -> crate::object::ClassId {
735        self.interp().register_host_class(def)
736    }
737
738    /// Install the prototype that [`Context::new_class_instance`] uses when the host does
739    /// not name one (`JS_SetClassProto`).
740    pub fn set_class_proto(&mut self, id: crate::object::ClassId, proto: &Value) -> Result<()> {
741        let Some(proto) = proto.as_object() else {
742            return Err(Error::Exception(
743                "class prototype is not an object".to_string(),
744            ));
745        };
746        let proto = proto.clone();
747        self.interp().set_host_class_proto(id, proto);
748        Ok(())
749    }
750
751    /// A new instance of class `id` (`JS_NewObjectProtoClass`).
752    ///
753    /// `proto` is the `new.target.prototype` a constructor pass-through would use; `None`
754    /// takes the registered prototype. An id that was never registered is an error: the C
755    /// API answers an exception there, and quietly making an ordinary object instead would
756    /// move the failure to the first `JS_GetOpaque` that no longer matches.
757    pub fn new_class_instance(
758        &mut self,
759        id: crate::object::ClassId,
760        proto: Option<&Value>,
761    ) -> Result<Value> {
762        let proto = match proto {
763            None => None,
764            Some(value) => match value.as_object() {
765                Some(object) => Some(object.clone()),
766                None => return Err(Error::Exception("prototype is not an object".to_string())),
767            },
768        };
769        self.interp()
770            .new_host_object(proto, id)
771            .map(Value::Object)
772            .ok_or_else(|| Error::Exception(format!("class {id} is not registered")))
773    }
774
775    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `id`.
776    pub fn class_opaque(
777        &mut self,
778        value: &Value,
779        id: crate::object::ClassId,
780    ) -> Option<crate::object::Opaque> {
781        self.interp().host_opaque(value, id)
782    }
783
784    /// `JS_SetOpaque`: store a payload on `value`, answering whether it is an instance of
785    /// *some* host class.
786    pub fn set_class_opaque(&mut self, value: &Value, opaque: crate::object::Opaque) -> bool {
787        self.interp().set_host_opaque(value, opaque)
788    }
789
790    /// A string value.
791    pub fn new_string(&mut self, text: &str) -> Value {
792        let interp = self.interp();
793        interp.string(text)
794    }
795
796    /// A number value.
797    pub fn new_number(&mut self, number: f64) -> Value {
798        Value::Float(number)
799    }
800
801    /// A boolean value.
802    pub fn new_boolean(&mut self, value: bool) -> Value {
803        Value::Bool(value)
804    }
805
806    /// Route `print`'s output to `sink` as it happens, in addition to the buffer
807    /// [`Context::output`] reads.
808    ///
809    /// Without a sink a script's output appears only when it finishes. A timer callback
810    /// printing *after* earlier output has to be observably later, which needs the write
811    /// to go out at the moment `print` runs.
812    pub fn set_output_sink(&mut self, sink: Box<dyn std::io::Write>) {
813        self.interp().output_sink = Some(sink);
814    }
815
816    /// Parse `text` in the extended JSON dialect: comments, unquoted keys, single quotes,
817    /// trailing commas, `+1`/`.1`/`0o10`/`0xa0`, and `Infinity`/`NaN`.
818    ///
819    /// This is what backs `std.parseExtJSON`. It is a separate entry point rather than a
820    /// flag on `JSON.parse` because the two must never share behaviour: a relaxed
821    /// `JSON.parse` would silently accept documents the standard rejects.
822    pub fn parse_ext_json(&mut self, text: &str) -> Result<Value> {
823        let interp = self.interp();
824        match interp.parse_ext_json(text) {
825            Ok(value) => Ok(value),
826            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
827            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
828        }
829    }
830
831    /// Schedule `callback` to run after `delay_ms` milliseconds; returns the timer id.
832    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
833        self.interp().schedule_timer(callback, delay_ms)
834    }
835
836    /// A promise that resolves after `delay_ms` — `os.sleepAsync`.
837    pub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value> {
838        let interp = self.interp();
839        match interp.sleep_async(delay_ms) {
840            Ok(value) => Ok(value),
841            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
842            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
843        }
844    }
845
846    /// Register or clear an `os.signal` handler.
847    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
848        self.interp().set_signal_handler(signal, handler);
849    }
850
851    /// Run the handler for `signal`. `false` when none is registered.
852    pub fn fire_signal(&mut self, signal: i32) -> Result<bool> {
853        let interp = self.interp();
854        match interp.fire_signal(signal) {
855            Ok(ran) => Ok(ran),
856            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
857            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
858        }
859    }
860
861    /// Register or clear an `os.setReadHandler`/`os.setWriteHandler` callback.
862    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
863        self.interp().set_fd_handler(fd, readable, callback);
864    }
865
866    /// The descriptors the host must poll, and in which direction.
867    pub fn pending_fds(&self) -> Vec<FdInterest> {
868        // An interpreter that has not been created cannot have handlers: nothing has run.
869        self.interp
870            .as_ref()
871            .map(Interp::pending_fds)
872            .unwrap_or_default()
873    }
874
875    /// Report descriptor readiness, calling the handler. `false` when none was registered.
876    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> Result<bool> {
877        let interp = self.interp();
878        match interp.fire_fd(fd, readable, writable) {
879            Ok(ran) => Ok(ran),
880            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
881            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
882        }
883    }
884
885    /// Cancel a pending timer. `false` when the id is unknown or already fired.
886    pub fn cancel_timer(&mut self, id: i32) -> bool {
887        self.interp().cancel_timer(id)
888    }
889
890    /// Run one turn of the event loop, reporting what the caller should do next.
891    ///
892    /// [`crate::Turn::Wait`] carries the delay to block for; this method never blocks, so
893    /// an embedder decides what "wait" means (a thread sleep, a tokio timer, a test clock).
894    pub fn run_one_turn(&mut self) -> Result<crate::Turn> {
895        let interp = self.interp();
896        match interp.run_one_turn() {
897            Ok(turn) => Ok(turn),
898            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
899            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
900        }
901    }
902
903    /// Whether any microtask or timer is still pending.
904    pub fn has_pending_work(&self) -> bool {
905        self.interp.as_ref().is_some_and(Interp::has_pending_work)
906    }
907
908    /// Whether a timer or a microtask is pending, ignoring registered descriptors.
909    ///
910    /// A REPL whose stdin is at end of file still has a read handler registered, and that
911    /// handler will keep firing without ever producing another line — so "there is work"
912    /// has to mean something narrower than [`Context::has_pending_work`] there.
913    pub fn has_pending_timers_or_jobs(&self) -> bool {
914        self.interp
915            .as_ref()
916            .is_some_and(Interp::has_pending_timers_or_jobs)
917    }
918
919    /// Rejections nobody handled, drained.
920    ///
921    /// [`Context::eval`] turns these into an error, but an event loop needs them *after*
922    /// every turn rather than at the end of one script: a promise may only become
923    /// unhandled later.
924    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
925        match self.interp.as_mut() {
926            Some(interp) => interp.take_unhandled_rejections(),
927            None => Vec::new(),
928        }
929    }
930
931    /// Errors that timer callbacks threw, drained.
932    pub fn take_timer_errors(&mut self) -> Vec<String> {
933        match self.interp.as_mut() {
934            Some(interp) => interp.take_timer_errors(),
935            None => Vec::new(),
936        }
937    }
938
939    /// Take the buffered output, leaving the buffer empty.
940    ///
941    /// For a host that keeps running turns: [`Context::output`] grows without bound, so
942    /// draining after each turn bounds the memory without changing what any one
943    /// assertion sees.
944    pub fn take_output(&mut self) -> String {
945        match self.interp.as_mut() {
946            Some(interp) => std::mem::take(&mut interp.output),
947            None => String::new(),
948        }
949    }
950}
951
952/// Put `scriptArgs` on the global object.
953///
954/// `scriptArgs` is a host addition, like `print`, so it is installed from the host side
955/// rather than by the realm's builtins. `qjs` defines it only when there is something to
956/// put in it, which is why `-e` with no trailing arguments still leaves an empty array
957/// rather than an absent binding.
958fn install_script_args(interp: &mut Interp<'_>, args: &[String]) {
959    let elements = args
960        .iter()
961        .map(|arg| interp.string(arg.clone()))
962        .collect::<Vec<_>>();
963    let array = interp.new_array(elements);
964    interp
965        .realm
966        .global
967        .clone()
968        .define_data("scriptArgs", Value::Object(array));
969}