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