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/// Whether `source` should be evaluated as a module, decided the way `qjs` decides.
135///
136/// The rule is deliberately shallow: the **first token** must be `import` or `export`
137/// (an `import` followed by `.` or `(` is `import.meta` or `import()`, both of which are
138/// expressions, so a script may use them). Nothing else makes a file a module.
139///
140/// It has to be this shallow to match the reference, and the difference is observable:
141/// a file that merely *mentions* `import.meta` further down is a script, so it fails with
142/// "import.meta only valid in module code" rather than silently becoming a module.
143pub fn is_module_source(source: &str) -> bool {
144 let bytes = source.as_bytes();
145 let mut index = 0;
146 // A shebang line is not code.
147 if bytes.starts_with(b"#!") {
148 while index < bytes.len() && bytes[index] != b'\n' {
149 index += 1;
150 }
151 }
152 loop {
153 // Whitespace.
154 while index < bytes.len() && bytes[index].is_ascii_whitespace() {
155 index += 1;
156 }
157 if bytes[index..].starts_with(b"//") {
158 while index < bytes.len() && bytes[index] != b'\n' {
159 index += 1;
160 }
161 continue;
162 }
163 if bytes[index..].starts_with(b"/*") {
164 index += 2;
165 while index < bytes.len() && !bytes[index..].starts_with(b"*/") {
166 index += 1;
167 }
168 index = (index + 2).min(bytes.len());
169 continue;
170 }
171 break;
172 }
173 let rest = &source[index.min(source.len())..];
174 let word = |w: &str| -> Option<&str> { rest.strip_prefix(w) };
175 if let Some(tail) = word("export") {
176 // `exportedThing` is an identifier, not the keyword.
177 return !tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$');
178 }
179 if let Some(tail) = word("import") {
180 if tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$') {
181 return false;
182 }
183 let tail = tail.trim_start();
184 // `import.meta` and `import(...)` are expressions.
185 if tail.starts_with('.') || tail.starts_with('(') {
186 return false;
187 }
188 return true;
189 }
190 false
191}
192
193/// A JavaScript runtime: one heap, one memory limit, one set of host hooks.
194///
195/// Mirrors the role of `JSRuntime` in the QuickJS C API.
196pub struct Runtime {
197 heap: Heap,
198 memory_limit: Option<usize>,
199 stack_size: Option<usize>,
200}
201
202impl Default for Runtime {
203 fn default() -> Self {
204 Self::new()
205 }
206}
207
208impl Runtime {
209 /// Create a runtime with default limits.
210 pub fn new() -> Runtime {
211 Runtime {
212 heap: Heap::new(),
213 memory_limit: None,
214 stack_size: None,
215 }
216 }
217
218 /// The runtime's object heap.
219 pub fn heap(&self) -> &Heap {
220 &self.heap
221 }
222
223 /// Equivalent of `JS_SetMemoryLimit`.
224 pub fn set_memory_limit(&mut self, limit: Option<usize>) {
225 self.memory_limit = limit;
226 }
227
228 /// Configured memory limit, if any.
229 pub fn memory_limit(&self) -> Option<usize> {
230 self.memory_limit
231 }
232
233 /// Equivalent of `JS_SetMaxStackSize`.
234 pub fn set_stack_size(&mut self, limit: Option<usize>) {
235 self.stack_size = limit;
236 }
237
238 /// Configured stack size limit, if any.
239 pub fn stack_size(&self) -> Option<usize> {
240 self.stack_size
241 }
242
243 /// Equivalent of `JS_RunGC`.
244 pub fn run_gc(&self) -> CollectStats {
245 self.heap.collect()
246 }
247}
248
249/// An execution context: a global object plus the builtins installed on it.
250///
251/// Mirrors the role of `JSContext` in the QuickJS C API.
252pub struct Context<'rt> {
253 runtime: &'rt Runtime,
254 /// The interpreter, created on first use.
255 interp: Option<Interp<'rt>>,
256 /// A loader the host installed, handed to the interpreter when it is built.
257 module_loader: Option<Box<dyn module::ModuleLoader>>,
258 /// The value of the last script, as `qjs` reports it.
259 last_value: Value,
260 /// The name a top-level script is compiled under, which is what `error.stack`
261 /// prints: `<cmdline>` for `-e`, a path for a file, `None` for `<input>`.
262 script_name: Option<String>,
263 /// The script arguments, as `qjs` exposes them through `scriptArgs`.
264 ///
265 /// Kept here and installed into the realm on first use, because the interpreter (and
266 /// so the global object) does not exist until something runs.
267 script_args: Option<Vec<String>>,
268}
269
270impl<'rt> Context<'rt> {
271 /// Create a context on `runtime`.
272 pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
273 Context {
274 runtime,
275 interp: None,
276 module_loader: None,
277 last_value: Value::Undefined,
278 script_name: None,
279 script_args: None,
280 }
281 }
282
283 /// Install how module specifiers are resolved and read.
284 ///
285 /// Without one, importing is a clear error rather than a silent failure: the engine
286 /// cannot guess whether `./x.js` means a file, and the host is what knows.
287 pub fn set_module_loader(&mut self, loader: Box<dyn module::ModuleLoader>) {
288 // A context that has already run something owns a live interpreter, so the loader
289 // goes to whichever exists.
290 if let Some(interp) = self.interp.as_mut() {
291 interp.module_loader = Some(loader);
292 } else {
293 self.module_loader = Some(loader);
294 }
295 }
296
297 /// Name the scripts this context evaluates, for stack traces.
298 ///
299 /// Mirrors what `qjs` passes to `JS_Eval`: `-e` code is `<cmdline>`, a script file
300 /// is its own path. Without a name, frames print `<input>`, which is what the
301 /// reference uses for code with no file behind it.
302 pub fn set_script_name(&mut self, name: impl Into<String>) {
303 self.script_name = Some(name.into());
304 }
305
306 /// Set the arguments `scriptArgs` should hold.
307 ///
308 /// Element 0 is the script itself, matching `qjs`: `qjs f.js a b` gives
309 /// `["f.js", "a", "b"]`. With `-e` there is no script, so the array is just the
310 /// trailing arguments and `-e`'s own text never appears in it.
311 ///
312 /// This was parsed by the CLI and then dropped on the floor: `opts.script_args` was
313 /// assigned in two places and read in none, so `scriptArgs` was simply undeclared.
314 /// An ordinary script's `if (typeof scriptArgs != "undefined")` branch therefore never
315 /// ran, and `examples/pi_bigint.js` printed a thousand digits of pi where the
316 /// reference printed `usage: pi n_digits`.
317 ///
318 /// Works whether or not the interpreter exists yet. The realm is built on first use,
319 /// so a host that installs something *else* first (an output sink, a host function)
320 /// would otherwise create it early and have these arguments silently dropped — which
321 /// is exactly what `print(JSON.stringify(scriptArgs))` caught.
322 pub fn set_script_args(&mut self, args: Vec<String>) {
323 if let Some(interp) = self.interp.as_mut() {
324 install_script_args(interp, &args);
325 } else {
326 self.script_args = Some(args);
327 }
328 }
329
330 /// The runtime this context belongs to.
331 pub fn runtime(&self) -> &'rt Runtime {
332 self.runtime
333 }
334
335 /// Everything `print` has written.
336 pub fn output(&self) -> &str {
337 self.interp.as_ref().map_or("", |interp| &interp.output)
338 }
339
340 /// The interpreter, creating it and its realm on first use.
341 fn interp(&mut self) -> &mut Interp<'rt> {
342 let heap: &'rt Heap = &self.runtime.heap;
343 let loader = self.module_loader.take();
344 let script_args = self.script_args.take();
345 self.interp.get_or_insert_with(|| {
346 let mut interp = Interp::new(heap);
347 interp.module_loader = loader;
348 if let Some(args) = script_args {
349 install_script_args(&mut interp, &args);
350 }
351 interp
352 })
353 }
354 /// Evaluate `specifier` as the entry module, the way `qjs -m` does.
355 ///
356 /// The microtask queue is drained afterwards, so a module whose top level launched an
357 /// async task has finished it by the time this returns.
358 pub fn eval_module(&mut self, specifier: &str) -> Result<Value> {
359 let loader = self.module_loader.take();
360 let interp = self.interp();
361 if interp.module_loader.is_none() {
362 interp.module_loader = loader;
363 }
364 match interp.run_main_module(specifier) {
365 Ok(value) => {
366 let drained = interp.drain_jobs();
367 let unhandled = interp.take_unhandled_rejections();
368 if let Err(Signal::Throw(reason)) = drained {
369 let text = interp.describe_exception(&reason);
370 return Err(Error::Exception(text));
371 }
372 if !unhandled.is_empty() {
373 return Err(Error::Exception(unhandled.join("\n")));
374 }
375 self.last_value = value.clone();
376 Ok(value)
377 }
378 Err(Signal::Throw(value)) => {
379 let text = interp.describe_exception(&value);
380 Err(Error::Exception(text))
381 }
382 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
383 }
384 }
385
386 /// Evaluate `source` as a global script and return its completion value.
387 ///
388 /// The value is reported the way `qjs -e` reports it: a string for anything the
389 /// script leaves on the stack, and nothing at all for `undefined`.
390 pub fn eval(&mut self, source: &str) -> Result<Value> {
391 self.eval_in(source, false)
392 }
393
394 /// [`Context::eval`] with the whole script strict from its first token.
395 ///
396 /// This is `qjs --strict`, and the reason it is a parse *mode* rather than a prepended
397 /// `"use strict"`: a directive shifts every column on the first line, and those
398 /// columns are what a stack trace reports. The reference does the same thing one level
399 /// down, with `JS_EVAL_FLAG_STRICT`.
400 pub fn eval_strict(&mut self, source: &str) -> Result<Value> {
401 self.eval_in(source, true)
402 }
403
404 fn eval_in(&mut self, source: &str, strict: bool) -> Result<Value> {
405 let program = if strict {
406 js_parse::parse_script_strict(source)
407 } else {
408 js_parse::parse_script(source)
409 }
410 .map_err(|error| Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>")))?;
411 let mut code = js_compile::compile_script(&program).map_err(|error| {
412 Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>"))
413 })?;
414 // Position information travels with the code, but the file name is the host's
415 // to supply — the parser never sees it.
416 code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
417 let interp = self.interp();
418 match interp.run_script(code) {
419 Ok(value) => {
420 // An unhandled rejection is fatal *after* the script finishes, which is
421 // when the reference decides nothing else will claim it. The script's own
422 // output has already been buffered, so it still prints first.
423 let unhandled = interp.take_unhandled_rejections();
424 if !unhandled.is_empty() {
425 return Err(Error::Exception(unhandled.join("\n")));
426 }
427 self.last_value = value.clone();
428 Ok(value)
429 }
430 Err(Signal::Throw(value)) => {
431 let text = interp.describe_exception(&value);
432 Err(Error::Exception(text))
433 }
434 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
435 }
436 }
437
438 /// The value of the script that ran last.
439 pub fn last_value(&self) -> &Value {
440 &self.last_value
441 }
442
443 // -----------------------------------------------------------------------
444 // Host surface: what an embedding needs to expose its own functions.
445 //
446 // These are narrow on purpose. Handing the host `&mut Interp` would let it hold a
447 // borrow that outlives the `Context`, and every method here would have to be
448 // re-derived at each call site. Each one below is a single well-defined operation.
449 // -----------------------------------------------------------------------
450
451 /// A host function as a value, for putting on an object rather than the global.
452 ///
453 /// [`Context::set_global_function`] is this plus the install; a host *module* needs the
454 /// function first and the install second, on its own object.
455 pub fn new_host_function_value(
456 &mut self,
457 name: &str,
458 length: u32,
459 f: crate::object::HostFn,
460 ) -> Result<Value> {
461 let interp = self.interp();
462 Ok(Value::Object(interp.new_host_function(name, length, f)))
463 }
464
465 /// Install `value` on the global object as `name`.
466 ///
467 /// A host module is one object with functions on it, so mounting `std` is a single
468 /// `set_global` rather than a function per name — which is what
469 /// [`Context::set_global_function`] does.
470 pub fn set_global(&mut self, name: &str, value: Value) -> Result<()> {
471 let global = self.interp().realm.global.clone();
472 global.define(name, Property::with_attributes(value, true, false));
473 Ok(())
474 }
475
476 /// Install `f` on the global object as `name`.
477 ///
478 /// This is how a host module is built: `std.loadFile` is a global function the host
479 /// registers before the script runs. The closure may capture Rust state but **must
480 /// not capture a [`Gc`]** — see [`crate::object::HostFn`].
481 pub fn set_global_function(
482 &mut self,
483 name: &str,
484 length: u32,
485 f: crate::object::HostFn,
486 ) -> Result<()> {
487 let interp = self.interp();
488 let function = interp.new_host_function(name, length, f);
489 let global = interp.realm.global.clone();
490 global.define(
491 name,
492 Property::with_attributes(Value::Object(function), true, false),
493 );
494 Ok(())
495 }
496
497 /// Install `f` on the global object as the constructor `name`.
498 ///
499 /// Unlike [`Context::set_global_function`] this one gets a `prototype` object, which
500 /// it owns and which `new` uses — the shape a host class like `std.File` needs.
501 /// Returns the constructor so the host can put methods on its `prototype`.
502 pub fn set_global_constructor(
503 &mut self,
504 name: &str,
505 length: u32,
506 f: crate::object::HostFn,
507 ) -> Result<Value> {
508 let interp = self.interp();
509 let function = interp.new_host_ctor(name, length, f);
510 let global = interp.realm.global.clone();
511 global.define(
512 name,
513 Property::with_attributes(Value::Object(function.clone()), true, false),
514 );
515 Ok(Value::Object(function))
516 }
517
518 /// Call a JavaScript function from Rust.
519 ///
520 /// A thrown value comes back as [`Error::Exception`], so a host callback can report
521 /// the script's own error rather than swallowing it.
522 pub fn call(&mut self, function: Value, this: Value, args: Vec<Value>) -> Result<Value> {
523 let interp = self.interp();
524 match interp.call_value(function, this, args) {
525 Ok(value) => Ok(value),
526 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
527 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
528 }
529 }
530
531 /// A fresh empty object, for the host to hand back to a script.
532 pub fn new_object(&mut self) -> Value {
533 let interp = self.interp();
534 let proto = interp.realm.object_proto.clone();
535 Value::Object(interp.new_object(Some(proto)))
536 }
537
538 /// Set `name` on `object` to `value`, as a plain writable property.
539 pub fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
540 let Some(object) = object.as_object() else {
541 return Err(Error::Exception("set_property on a non-object".to_string()));
542 };
543 object.define(name, Property::with_attributes(value, true, true));
544 Ok(())
545 }
546
547 /// Define `name` on `object` as a **non-enumerable** data property.
548 ///
549 /// [`Context::set_property`] writes an enumerable property, which is right for the
550 /// members of a host module — `Object.keys(std)` should list them. A method on a host
551 /// class prototype is the opposite: `quickjs-libc.c` defines the seventeen `FILE`
552 /// methods with `JS_CFUNC_DEF`, whose flags leave `enumerable` off, so
553 /// `Object.keys(std.out)` is `[]` in the reference. A host class needs the same.
554 pub fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
555 let Some(object) = object.as_object() else {
556 return Err(Error::Exception(
557 "define_hidden on a non-object".to_string(),
558 ));
559 };
560 object.define(name, Property::with_attributes(value, true, false));
561 Ok(())
562 }
563
564 /// A new ordinary object whose prototype is `proto`.
565 ///
566 /// [`Context::new_object`] gives an object whose prototype is `Object.prototype`; a
567 /// host class needs instances that inherit from its own prototype instead.
568 pub fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value> {
569 let Some(proto) = proto.as_object() else {
570 return Err(Error::Exception("prototype is not an object".to_string()));
571 };
572 let proto = proto.clone();
573 let interp = self.interp();
574 Ok(Value::Object(interp.new_object(Some(proto))))
575 }
576
577 /// The global object, for a host module that has to keep something reachable from
578 /// every host function it installs.
579 ///
580 /// A [`HostFn`](crate::object::HostFn) closure may not hold a `Gc` — the collector
581 /// cannot see into it — so a shared JavaScript value (a class prototype, say) has to
582 /// live where the collector already scans. The global object is the one object every
583 /// interpreter has.
584 pub fn global(&mut self) -> Value {
585 let interp = self.interp();
586 Value::Object(interp.realm.global.clone())
587 }
588
589 /// A string value.
590 pub fn new_string(&mut self, text: &str) -> Value {
591 let interp = self.interp();
592 interp.string(text)
593 }
594
595 /// A number value.
596 pub fn new_number(&mut self, number: f64) -> Value {
597 Value::Float(number)
598 }
599
600 /// A boolean value.
601 pub fn new_boolean(&mut self, value: bool) -> Value {
602 Value::Bool(value)
603 }
604
605 /// Route `print`'s output to `sink` as it happens, in addition to the buffer
606 /// [`Context::output`] reads.
607 ///
608 /// Without a sink a script's output appears only when it finishes. A timer callback
609 /// printing *after* earlier output has to be observably later, which needs the write
610 /// to go out at the moment `print` runs.
611 pub fn set_output_sink(&mut self, sink: Box<dyn std::io::Write>) {
612 self.interp().output_sink = Some(sink);
613 }
614
615 /// Parse `text` in the extended JSON dialect: comments, unquoted keys, single quotes,
616 /// trailing commas, `+1`/`.1`/`0o10`/`0xa0`, and `Infinity`/`NaN`.
617 ///
618 /// This is what backs `std.parseExtJSON`. It is a separate entry point rather than a
619 /// flag on `JSON.parse` because the two must never share behaviour: a relaxed
620 /// `JSON.parse` would silently accept documents the standard rejects.
621 pub fn parse_ext_json(&mut self, text: &str) -> Result<Value> {
622 let interp = self.interp();
623 match interp.parse_ext_json(text) {
624 Ok(value) => Ok(value),
625 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
626 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
627 }
628 }
629
630 /// Schedule `callback` to run after `delay_ms` milliseconds; returns the timer id.
631 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
632 self.interp().schedule_timer(callback, delay_ms)
633 }
634
635 /// A promise that resolves after `delay_ms` — `os.sleepAsync`.
636 pub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value> {
637 let interp = self.interp();
638 match interp.sleep_async(delay_ms) {
639 Ok(value) => Ok(value),
640 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
641 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
642 }
643 }
644
645 /// Register or clear an `os.signal` handler.
646 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
647 self.interp().set_signal_handler(signal, handler);
648 }
649
650 /// Run the handler for `signal`. `false` when none is registered.
651 pub fn fire_signal(&mut self, signal: i32) -> Result<bool> {
652 let interp = self.interp();
653 match interp.fire_signal(signal) {
654 Ok(ran) => Ok(ran),
655 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
656 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
657 }
658 }
659
660 /// Register or clear an `os.setReadHandler`/`os.setWriteHandler` callback.
661 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
662 self.interp().set_fd_handler(fd, readable, callback);
663 }
664
665 /// The descriptors the host must poll, and in which direction.
666 pub fn pending_fds(&self) -> Vec<FdInterest> {
667 // An interpreter that has not been created cannot have handlers: nothing has run.
668 self.interp
669 .as_ref()
670 .map(Interp::pending_fds)
671 .unwrap_or_default()
672 }
673
674 /// Report descriptor readiness, calling the handler. `false` when none was registered.
675 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> Result<bool> {
676 let interp = self.interp();
677 match interp.fire_fd(fd, readable, writable) {
678 Ok(ran) => Ok(ran),
679 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
680 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
681 }
682 }
683
684 /// Cancel a pending timer. `false` when the id is unknown or already fired.
685 pub fn cancel_timer(&mut self, id: i32) -> bool {
686 self.interp().cancel_timer(id)
687 }
688
689 /// Run one turn of the event loop, reporting what the caller should do next.
690 ///
691 /// [`crate::Turn::Wait`] carries the delay to block for; this method never blocks, so
692 /// an embedder decides what "wait" means (a thread sleep, a tokio timer, a test clock).
693 pub fn run_one_turn(&mut self) -> Result<crate::Turn> {
694 let interp = self.interp();
695 match interp.run_one_turn() {
696 Ok(turn) => Ok(turn),
697 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
698 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
699 }
700 }
701
702 /// Whether any microtask or timer is still pending.
703 pub fn has_pending_work(&self) -> bool {
704 self.interp.as_ref().is_some_and(Interp::has_pending_work)
705 }
706
707 /// Whether a timer or a microtask is pending, ignoring registered descriptors.
708 ///
709 /// A REPL whose stdin is at end of file still has a read handler registered, and that
710 /// handler will keep firing without ever producing another line — so "there is work"
711 /// has to mean something narrower than [`Context::has_pending_work`] there.
712 pub fn has_pending_timers_or_jobs(&self) -> bool {
713 self.interp
714 .as_ref()
715 .is_some_and(Interp::has_pending_timers_or_jobs)
716 }
717
718 /// Rejections nobody handled, drained.
719 ///
720 /// [`Context::eval`] turns these into an error, but an event loop needs them *after*
721 /// every turn rather than at the end of one script: a promise may only become
722 /// unhandled later.
723 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
724 match self.interp.as_mut() {
725 Some(interp) => interp.take_unhandled_rejections(),
726 None => Vec::new(),
727 }
728 }
729
730 /// Errors that timer callbacks threw, drained.
731 pub fn take_timer_errors(&mut self) -> Vec<String> {
732 match self.interp.as_mut() {
733 Some(interp) => interp.take_timer_errors(),
734 None => Vec::new(),
735 }
736 }
737
738 /// Take the buffered output, leaving the buffer empty.
739 ///
740 /// For a host that keeps running turns: [`Context::output`] grows without bound, so
741 /// draining after each turn bounds the memory without changing what any one
742 /// assertion sees.
743 pub fn take_output(&mut self) -> String {
744 match self.interp.as_mut() {
745 Some(interp) => std::mem::take(&mut interp.output),
746 None => String::new(),
747 }
748 }
749}
750
751/// Put `scriptArgs` on the global object.
752///
753/// `scriptArgs` is a host addition, like `print`, so it is installed from the host side
754/// rather than by the realm's builtins. `qjs` defines it only when there is something to
755/// put in it, which is why `-e` with no trailing arguments still leaves an empty array
756/// rather than an absent binding.
757fn install_script_args(interp: &mut Interp<'_>, args: &[String]) {
758 let elements = args
759 .iter()
760 .map(|arg| interp.string(arg.clone()))
761 .collect::<Vec<_>>();
762 let array = interp.new_array(elements);
763 interp
764 .realm
765 .global
766 .clone()
767 .define_data("scriptArgs", Value::Object(array));
768}