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