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