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