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