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 rather than a wrong answer:
43//!
44//! * `std`/`os` and the event loop live in `quickjs-host`, not here, so `setTimeout`
45//! is undefined in a bare [`Context`]. The same goes for the other host-provided
46//! globals — `queueMicrotask`, `structuredClone`, `performance` — and for `Intl`,
47//! which is ECMA-402 rather than ECMA-262;
48//! * `Function.prototype.toString` answers with the original source for a function
49//! written in source, but a *method* (`m(){}`, `get x(){}`) still reports the
50//! `[native code]` form, and so does `TypedArray.prototype.toSpliced`, which the C
51//! reference does not have either;
52//! * performance is **0.04×–0.18×** the C reference on the twelve measured cases
53//! (`scripts/bench.sh` in the repository); there is no NaN boxing and no
54//! superinstruction dispatch yet.
55//!
56//! See `docs/requirements.md` in the repository for the milestone plan and
57//! `docs/test262-status.md` for the measured language coverage.
58
59#![deny(unsafe_op_in_unsafe_fn)]
60#![warn(missing_docs)]
61
62pub use js_compile;
63pub use js_gc::{CollectStats, Gc, Heap, Trace, Tracer, WeakGc};
64pub use js_parse;
65
66mod bignum;
67
68pub mod bigint;
69pub mod builtins;
70pub mod insn;
71pub mod interp;
72pub mod memory;
73pub mod module;
74pub mod normalize;
75mod normalize_tables;
76pub mod object;
77/// The reference's `JS_PrintValue`, which lives in the *engine* (`quickjs.c`) and not in
78/// the host library. `std.__printObject` is a one-line wrapper over it, and so is the
79/// reporting of an uncaught exception — which is why this belongs here rather than in
80/// `quickjs-host`.
81pub mod print;
82// The engine lives in its own crate so that `quickjs-compile` can validate a `/…/u`
83// literal at parse time without depending on this one.
84pub use quickjs_regexp as regexp;
85mod tzif;
86pub mod value;
87
88pub use interp::{FdInterest, Interp, JsResult, Signal, Task, Turn};
89pub use memory::{ClassCensus, MemoryUsage};
90pub use object::{Callable, ClassDef, ClassId, Exotic, JsObject, ObjectKind, Opaque, Property};
91pub use value::{Cell, JsString, Value};
92
93/// Version string of the upstream QuickJS release this port tracks.
94pub const COMPAT_VERSION: &str = "2026-06-04";
95
96/// Why [`Context::eval_detailed`] failed, keeping the thrown value intact.
97///
98/// The distinction from [`Error`] is the whole reason this type exists: an embedding has to
99/// hand the thrown object back to its caller (the C API's `JS_GetException`), and once it
100/// has been turned into text that is no longer possible.
101#[derive(Debug, Clone)]
102pub enum EvalError {
103 /// The source did not compile. The text is already a rendered `SyntaxError`, because a
104 /// compile error has no object behind it — nothing ran, so there is nothing to throw.
105 Syntax(String),
106 /// The script threw this value.
107 Throw(Value),
108 /// The runtime ran out of memory.
109 OutOfMemory,
110}
111
112/// Error raised by the engine.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum Error {
115 /// The source did not parse, or did not compile.
116 Syntax(String),
117 /// The script threw, or the engine raised while running it.
118 Exception(String),
119 /// The feature/entry point exists in the API but is not implemented yet.
120 NotImplemented(&'static str),
121 /// The runtime exceeded its memory limit (`--memory-limit`).
122 OutOfMemory,
123 /// The runtime exceeded its stack limit (`--stack-size`).
124 StackOverflow,
125}
126
127impl Error {
128 /// A compile error, rendered the way the reference prints one.
129 ///
130 /// `SyntaxError: <message>` and, when the error has a position,
131 /// ` at <file>:<line>:<column>` on the next line. The reference gets this shape
132 /// from `js_std_dump_error` printing an exception object whose `stack` is those two
133 /// lines; we have no object yet (nothing has run), so the text is built directly.
134 ///
135 /// A parse error is not "`file: SyntaxError: L:C: message`", which is what the CLI
136 /// used to print: that put the file name where the reference puts nothing, and the
137 /// position where the reference puts the file name.
138 fn syntax(error: &js_parse::SyntaxError, file: &str) -> Error {
139 if error.positionless {
140 Error::Syntax(error.message.clone())
141 } else {
142 Error::Syntax(format!(
143 "{}\n at {}:{}:{}",
144 error.message, file, error.span.start.line, error.span.start.column
145 ))
146 }
147 }
148}
149
150impl std::fmt::Display for Error {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 match self {
153 Error::NotImplemented(what) => write!(f, "not implemented yet: {what}"),
154 // A compile error is a `SyntaxError` in the language, and saying so is not
155 // cosmetic: the conformance runner classifies a `negative:` test by the
156 // constructor name in the message, and the reference prints the same prefix.
157 Error::Syntax(what) => write!(f, "SyntaxError: {what}"),
158 Error::Exception(what) => write!(f, "{what}"),
159 Error::OutOfMemory => write!(f, "out of memory"),
160 Error::StackOverflow => write!(f, "stack overflow"),
161 }
162 }
163}
164
165impl std::error::Error for Error {}
166
167/// Convenience alias used throughout the crate.
168pub type Result<T> = std::result::Result<T, Error>;
169
170/// [`js_parse::is_module_source`], which is the rule `qjs` uses to decide module mode.
171///
172/// It lives in the parser because it is a question about source text, not about the
173/// engine: `qjsc` needs the same answer and has no business linking an interpreter to
174/// get it.
175pub use js_parse::is_module_source;
176
177/// A JavaScript runtime: one heap, one memory limit, one set of host hooks.
178///
179/// Mirrors the role of `JSRuntime` in the QuickJS C API.
180pub struct Runtime {
181 heap: Heap,
182 memory_limit: Option<usize>,
183 stack_size: Option<usize>,
184}
185
186impl Default for Runtime {
187 fn default() -> Self {
188 Self::new()
189 }
190}
191
192impl Runtime {
193 /// Create a runtime with default limits.
194 pub fn new() -> Runtime {
195 Runtime {
196 heap: Heap::new(),
197 memory_limit: None,
198 stack_size: None,
199 }
200 }
201
202 /// The runtime's object heap.
203 pub fn heap(&self) -> &Heap {
204 &self.heap
205 }
206
207 /// Equivalent of `JS_SetMemoryLimit`.
208 ///
209 /// Applied to the heap as well as recorded, because the heap is what enforces it and it
210 /// outlives every interpreter a context creates. Recording alone was a real bug: a host
211 /// that called `JS_SetMemoryLimit` *after* its first evaluation had no limit at all, and
212 /// `tests/c/embed.c` caught it by printing a 64 MiB array the limit should have refused.
213 pub fn set_memory_limit(&mut self, limit: Option<usize>) {
214 self.memory_limit = limit;
215 self.heap.set_memory_limit(limit);
216 }
217
218 /// Configured memory limit, if any.
219 pub fn memory_limit(&self) -> Option<usize> {
220 self.memory_limit
221 }
222
223 /// Equivalent of `JS_SetMaxStackSize`.
224 pub fn set_stack_size(&mut self, limit: Option<usize>) {
225 self.stack_size = limit;
226 }
227
228 /// Configured stack size limit, if any.
229 pub fn stack_size(&self) -> Option<usize> {
230 self.stack_size
231 }
232
233 /// Equivalent of `JS_RunGC`.
234 pub fn run_gc(&self) -> CollectStats {
235 self.heap.collect()
236 }
237}
238
239/// An execution context: a global object plus the builtins installed on it.
240///
241/// Mirrors the role of `JSContext` in the QuickJS C API.
242pub struct Context<'rt> {
243 runtime: &'rt Runtime,
244 /// The interpreter, created on first use.
245 interp: Option<Interp<'rt>>,
246 /// A loader the host installed, handed to the interpreter when it is built.
247 module_loader: Option<Box<dyn module::ModuleLoader>>,
248 /// The value of the last script, as `qjs` reports it.
249 last_value: Value,
250 /// The name a top-level script is compiled under, which is what `error.stack`
251 /// prints: `<cmdline>` for `-e`, a path for a file, `None` for `<input>`.
252 script_name: Option<String>,
253 /// The script arguments, as `qjs` exposes them through `scriptArgs`.
254 ///
255 /// Kept here and installed into the realm on first use, because the interpreter (and
256 /// so the global object) does not exist until something runs.
257 script_args: Option<Vec<String>>,
258 /// Whether a rejection nobody handled is reported as an error.
259 ///
260 /// The reference's `--no-unhandled-rejection` clears the host's rejection tracker, so
261 /// this is a *context* setting there — not a decision the CLI makes after the fact.
262 /// It has to be that way round: `eval` reports an unhandled rejection as an error the
263 /// moment the script returns, long before any event loop sees it.
264 track_unhandled_rejection: bool,
265}
266
267impl<'rt> Context<'rt> {
268 /// Create a context on `runtime`.
269 pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
270 Context {
271 runtime,
272 interp: None,
273 module_loader: None,
274 last_value: Value::Undefined,
275 script_name: None,
276 script_args: None,
277 track_unhandled_rejection: true,
278 }
279 }
280
281 /// `qjs --no-unhandled-rejection`: forget unhandled rejections instead of failing.
282 ///
283 /// Off means a rejection nobody listened to is neither printed nor reported — the
284 /// script's outcome is what it would have been had the promise been handled. This is
285 /// the reference's semantics, and it is what a conformance runner wants: test262 judges
286 /// a test by what it asserts, and the policy on stray rejections is the host's.
287 pub fn set_track_unhandled_rejection(&mut self, track: bool) {
288 self.track_unhandled_rejection = track;
289 }
290
291 /// Whether unhandled rejections are reported. See
292 /// [`Context::set_track_unhandled_rejection`].
293 pub fn tracks_unhandled_rejection(&self) -> bool {
294 self.track_unhandled_rejection
295 }
296
297 /// Install how module specifiers are resolved and read.
298 ///
299 /// Without one, importing is a clear error rather than a silent failure: the engine
300 /// cannot guess whether `./x.js` means a file, and the host is what knows.
301 pub fn set_module_loader(&mut self, loader: Box<dyn module::ModuleLoader>) {
302 // A context that has already run something owns a live interpreter, so the loader
303 // goes to whichever exists.
304 if let Some(interp) = self.interp.as_mut() {
305 interp.module_loader = Some(loader);
306 } else {
307 self.module_loader = Some(loader);
308 }
309 }
310
311 /// Name the scripts this context evaluates, for stack traces.
312 ///
313 /// Mirrors what `qjs` passes to `JS_Eval`: `-e` code is `<cmdline>`, a script file
314 /// is its own path. Without a name, frames print `<input>`, which is what the
315 /// reference uses for code with no file behind it.
316 pub fn set_script_name(&mut self, name: impl Into<String>) {
317 self.script_name = Some(name.into());
318 }
319
320 /// Set the arguments `scriptArgs` should hold.
321 ///
322 /// Element 0 is the script itself, matching `qjs`: `qjs f.js a b` gives
323 /// `["f.js", "a", "b"]`. With `-e` there is no script, so the array is just the
324 /// trailing arguments and `-e`'s own text never appears in it.
325 ///
326 /// This was parsed by the CLI and then dropped on the floor: `opts.script_args` was
327 /// assigned in two places and read in none, so `scriptArgs` was simply undeclared.
328 /// An ordinary script's `if (typeof scriptArgs != "undefined")` branch therefore never
329 /// ran, and `examples/pi_bigint.js` printed a thousand digits of pi where the
330 /// reference printed `usage: pi n_digits`.
331 ///
332 /// Works whether or not the interpreter exists yet. The realm is built on first use,
333 /// so a host that installs something *else* first (an output sink, a host function)
334 /// would otherwise create it early and have these arguments silently dropped — which
335 /// is exactly what `print(JSON.stringify(scriptArgs))` caught.
336 pub fn set_script_args(&mut self, args: Vec<String>) {
337 if let Some(interp) = self.interp.as_mut() {
338 install_script_args(interp, &args);
339 } else {
340 self.script_args = Some(args);
341 }
342 }
343
344 /// The runtime this context belongs to.
345 pub fn runtime(&self) -> &'rt Runtime {
346 self.runtime
347 }
348
349 /// Everything `print` has written.
350 pub fn output(&self) -> &str {
351 self.interp.as_ref().map_or("", |interp| &interp.output)
352 }
353
354 /// The interpreter, for a host layer that has to run JavaScript from inside a native
355 /// callback.
356 ///
357 /// This is the same interpreter [`Context::interp`] builds on first use; it is public
358 /// because a callback C code re-enters (the C ABI layer's `JS_GetPropertyStr` and
359 /// friends) needs a `&mut Interp` that outlives the one closure invocation it was
360 /// handed. The interpreter's address is stable — the `Context` owns it behind an
361 /// `Option` in a boxed struct, so it never moves once created — and that is exactly the
362 /// property the C side depends on.
363 pub fn interp_mut(&mut self) -> &mut Interp<'rt> {
364 self.interp()
365 }
366
367 /// The interpreter, creating it and its realm on first use.
368 fn interp(&mut self) -> &mut Interp<'rt> {
369 let heap: &'rt Heap = &self.runtime.heap;
370 let loader = self.module_loader.take();
371 let script_args = self.script_args.take();
372 let memory_limit = self.runtime.memory_limit;
373 let stack_size = self.runtime.stack_size;
374 self.interp.get_or_insert_with(|| {
375 let mut interp = Interp::new(heap);
376 interp.module_loader = loader;
377 // The limits are the runtime's, and the interpreter is created lazily on first
378 // use — so they have to be handed over here rather than in `Runtime`. `None`
379 // means the defaults, which are the reference's: no memory cap, and
380 // `JS_DEFAULT_STACK_SIZE`.
381 heap.set_memory_limit(memory_limit);
382 if let Some(size) = stack_size {
383 interp.stack_limit = size;
384 }
385 if let Some(args) = script_args {
386 install_script_args(&mut interp, &args);
387 }
388 interp
389 })
390 }
391 /// Evaluate `specifier` as the entry module, the way `qjs -m` does.
392 ///
393 /// The microtask queue is drained afterwards, so a module whose top level launched an
394 /// async task has finished it by the time this returns.
395 pub fn eval_module(&mut self, specifier: &str) -> Result<Value> {
396 let loader = self.module_loader.take();
397 let track = self.track_unhandled_rejection;
398 let interp = self.interp();
399 if interp.module_loader.is_none() {
400 interp.module_loader = loader;
401 }
402 match interp.run_main_module(specifier) {
403 Ok(value) => {
404 let drained = interp.drain_jobs();
405 let unhandled = reported_unhandled(interp, track);
406 if let Err(Signal::Throw(reason)) = drained {
407 let text = interp.describe_exception(&reason);
408 return Err(Error::Exception(text));
409 }
410 if !unhandled.is_empty() {
411 return Err(Error::Exception(unhandled.join("\n")));
412 }
413 self.last_value = value.clone();
414 Ok(value)
415 }
416 Err(Signal::Throw(value)) => {
417 let text = interp.describe_exception(&value);
418 Err(Error::Exception(text))
419 }
420 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
421 }
422 }
423
424 /// Evaluate an already-compiled bytecode blob, as an AOT binary does.
425 ///
426 /// Nothing is parsed and nothing is compiled: the input is
427 /// [`js_compile::serialize::serialize`]'s output, which carries the file name, the
428 /// optional source text and the module tables alongside the code. A blob with module
429 /// tables is run the way `qjs -m` runs a file — its requests are resolved through the
430 /// installed module loader, so a precompiled entry module can still import ordinary
431 /// source files.
432 ///
433 /// A blob is only accepted when its format *version* matches this build. Bytecode and
434 /// the opcode table are one unit, so a stale blob is rejected instead of being read
435 /// as different instructions.
436 pub fn eval_bytecode(&mut self, bytes: &[u8]) -> Result<Value> {
437 let code = js_compile::serialize::deserialize(bytes)
438 .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
439 let is_module = code.module.is_some();
440 let loader = self.module_loader.take();
441 let track = self.track_unhandled_rejection;
442 let interp = self.interp();
443 if interp.module_loader.is_none() {
444 interp.module_loader = loader;
445 }
446 let outcome = if is_module {
447 interp.run_precompiled_module(code)
448 } else {
449 interp.run_script(code)
450 };
451 match outcome {
452 Ok(value) => {
453 // An unhandled rejection is fatal *after* the body finishes, which is when
454 // the reference decides nothing else will claim it. The body's own output
455 // has already been buffered, so it still prints first.
456 let drained = interp.drain_jobs();
457 let unhandled = reported_unhandled(interp, track);
458 if let Err(Signal::Throw(reason)) = drained {
459 let text = interp.describe_exception(&reason);
460 return Err(Error::Exception(text));
461 }
462 if !unhandled.is_empty() {
463 return Err(Error::Exception(unhandled.join("\n")));
464 }
465 self.last_value = value.clone();
466 Ok(value)
467 }
468 Err(Signal::Throw(value)) => {
469 let text = interp.describe_exception(&value);
470 Err(Error::Exception(text))
471 }
472 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
473 }
474 }
475
476 /// Register a module from bytecode, so an import of it never reaches the loader.
477 ///
478 /// This is the second half of AOT for modules: `qjsc` compiles every module the program
479 /// can reach into a blob, and the product registers them all before running the entry
480 /// one. The name comes from the blob (`qjsc` stamped it), and it is the name the loader
481 /// would have produced, so `import "./dep.js"` finds it.
482 pub fn register_module(&mut self, bytes: &[u8]) -> Result<String> {
483 let code = js_compile::serialize::deserialize(bytes)
484 .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
485 if code.module.is_none() {
486 return Err(Error::Syntax(
487 "invalid bytecode: this blob is a script, not a module".to_string(),
488 ));
489 }
490 let interp = self.interp();
491 match interp.register_module(code) {
492 Ok(name) => Ok(name),
493 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
494 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
495 }
496 }
497
498 /// Register a JSON, text or bytes module from its bytes, by name.
499 ///
500 /// `attributes` is the module's `with { type: … }` list, or empty for the name's
501 /// extension to decide — the same rule the loader applies.
502 pub fn register_data_module(
503 &mut self,
504 name: &str,
505 source: Vec<u8>,
506 attributes: &[(String, String)],
507 ) -> Result<()> {
508 let interp = self.interp();
509 match interp.register_data_module(name, source, attributes) {
510 Ok(()) => Ok(()),
511 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
512 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
513 }
514 }
515
516 /// Evaluate `source` as a global script and return its completion value.
517 ///
518 /// The value is reported the way `qjs -e` reports it: a string for anything the
519 /// script leaves on the stack, and nothing at all for `undefined`.
520 pub fn eval(&mut self, source: &str) -> Result<Value> {
521 self.eval_in(source, false)
522 }
523
524 /// [`Context::eval`] with the whole script strict from its first token.
525 ///
526 /// This is `qjs --strict`, and the reason it is a parse *mode* rather than a prepended
527 /// `"use strict"`: a directive shifts every column on the first line, and those
528 /// columns are what a stack trace reports. The reference does the same thing one level
529 /// down, with `JS_EVAL_FLAG_STRICT`.
530 pub fn eval_strict(&mut self, source: &str) -> Result<Value> {
531 self.eval_in(source, true)
532 }
533
534 /// Evaluate a global script, keeping the thrown *value* rather than a rendering of it.
535 ///
536 /// [`Context::eval`] answers an [`Error`] whose exception case is already text — that is
537 /// what a CLI prints. An embedding needs the value itself: the C API's `JS_Eval` stores
538 /// it as the context's pending exception and `JS_GetException` hands the very object a
539 /// script threw to C, which then reads `.name`, `.message` or any custom property off
540 /// it.
541 ///
542 /// `name` becomes the script name, which is what stack frames and syntax errors report;
543 /// it is scoped to this call so two `JS_Eval`s with different names do not leak into
544 /// each other's traces.
545 pub fn eval_detailed(
546 &mut self,
547 source: &str,
548 name: &str,
549 ) -> std::result::Result<Value, EvalError> {
550 let program = js_parse::parse_script(source)
551 .map_err(|error| EvalError::Syntax(Error::syntax(&error, name).to_string()))?;
552 let mut code = js_compile::compile_script_with_source(&program, source)
553 .map_err(|error| EvalError::Syntax(Error::syntax(&error, name).to_string()))?;
554 code.set_filename(name);
555 let interp = self.interp();
556 match interp.run_script(code) {
557 Ok(value) => {
558 self.last_value = value.clone();
559 Ok(value)
560 }
561 Err(Signal::Throw(value)) => Err(EvalError::Throw(value)),
562 Err(Signal::OutOfMemory) => Err(EvalError::OutOfMemory),
563 }
564 }
565
566 fn eval_in(&mut self, source: &str, strict: bool) -> Result<Value> {
567 let program = if strict {
568 js_parse::parse_script_strict(source)
569 } else {
570 js_parse::parse_script(source)
571 }
572 .map_err(|error| Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>")))?;
573 let mut code =
574 js_compile::compile_script_with_source(&program, source).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}