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 let program = js_parse::parse_script(source).map_err(|error| {
392 Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>"))
393 })?;
394 let mut code = js_compile::compile_script(&program).map_err(|error| {
395 Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>"))
396 })?;
397 // Position information travels with the code, but the file name is the host's
398 // to supply — the parser never sees it.
399 code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
400 let interp = self.interp();
401 match interp.run_script(code) {
402 Ok(value) => {
403 // An unhandled rejection is fatal *after* the script finishes, which is
404 // when the reference decides nothing else will claim it. The script's own
405 // output has already been buffered, so it still prints first.
406 let unhandled = interp.take_unhandled_rejections();
407 if !unhandled.is_empty() {
408 return Err(Error::Exception(unhandled.join("\n")));
409 }
410 self.last_value = value.clone();
411 Ok(value)
412 }
413 Err(Signal::Throw(value)) => {
414 let text = interp.describe_exception(&value);
415 Err(Error::Exception(text))
416 }
417 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
418 }
419 }
420
421 /// The value of the script that ran last.
422 pub fn last_value(&self) -> &Value {
423 &self.last_value
424 }
425
426 // -----------------------------------------------------------------------
427 // Host surface: what an embedding needs to expose its own functions.
428 //
429 // These are narrow on purpose. Handing the host `&mut Interp` would let it hold a
430 // borrow that outlives the `Context`, and every method here would have to be
431 // re-derived at each call site. Each one below is a single well-defined operation.
432 // -----------------------------------------------------------------------
433
434 /// A host function as a value, for putting on an object rather than the global.
435 ///
436 /// [`Context::set_global_function`] is this plus the install; a host *module* needs the
437 /// function first and the install second, on its own object.
438 pub fn new_host_function_value(
439 &mut self,
440 name: &str,
441 length: u32,
442 f: crate::object::HostFn,
443 ) -> Result<Value> {
444 let interp = self.interp();
445 Ok(Value::Object(interp.new_host_function(name, length, f)))
446 }
447
448 /// Install `value` on the global object as `name`.
449 ///
450 /// A host module is one object with functions on it, so mounting `std` is a single
451 /// `set_global` rather than a function per name — which is what
452 /// [`Context::set_global_function`] does.
453 pub fn set_global(&mut self, name: &str, value: Value) -> Result<()> {
454 let global = self.interp().realm.global.clone();
455 global.define(name, Property::with_attributes(value, true, false));
456 Ok(())
457 }
458
459 /// Install `f` on the global object as `name`.
460 ///
461 /// This is how a host module is built: `std.loadFile` is a global function the host
462 /// registers before the script runs. The closure may capture Rust state but **must
463 /// not capture a [`Gc`]** — see [`crate::object::HostFn`].
464 pub fn set_global_function(
465 &mut self,
466 name: &str,
467 length: u32,
468 f: crate::object::HostFn,
469 ) -> Result<()> {
470 let interp = self.interp();
471 let function = interp.new_host_function(name, length, f);
472 let global = interp.realm.global.clone();
473 global.define(
474 name,
475 Property::with_attributes(Value::Object(function), true, false),
476 );
477 Ok(())
478 }
479
480 /// Install `f` on the global object as the constructor `name`.
481 ///
482 /// Unlike [`Context::set_global_function`] this one gets a `prototype` object, which
483 /// it owns and which `new` uses — the shape a host class like `std.File` needs.
484 /// Returns the constructor so the host can put methods on its `prototype`.
485 pub fn set_global_constructor(
486 &mut self,
487 name: &str,
488 length: u32,
489 f: crate::object::HostFn,
490 ) -> Result<Value> {
491 let interp = self.interp();
492 let function = interp.new_host_ctor(name, length, f);
493 let global = interp.realm.global.clone();
494 global.define(
495 name,
496 Property::with_attributes(Value::Object(function.clone()), true, false),
497 );
498 Ok(Value::Object(function))
499 }
500
501 /// Call a JavaScript function from Rust.
502 ///
503 /// A thrown value comes back as [`Error::Exception`], so a host callback can report
504 /// the script's own error rather than swallowing it.
505 pub fn call(&mut self, function: Value, this: Value, args: Vec<Value>) -> Result<Value> {
506 let interp = self.interp();
507 match interp.call_value(function, this, args) {
508 Ok(value) => Ok(value),
509 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
510 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
511 }
512 }
513
514 /// A fresh empty object, for the host to hand back to a script.
515 pub fn new_object(&mut self) -> Value {
516 let interp = self.interp();
517 let proto = interp.realm.object_proto.clone();
518 Value::Object(interp.new_object(Some(proto)))
519 }
520
521 /// Set `name` on `object` to `value`, as a plain writable property.
522 pub fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
523 let Some(object) = object.as_object() else {
524 return Err(Error::Exception("set_property on a non-object".to_string()));
525 };
526 object.define(name, Property::with_attributes(value, true, true));
527 Ok(())
528 }
529
530 /// Define `name` on `object` as a **non-enumerable** data property.
531 ///
532 /// [`Context::set_property`] writes an enumerable property, which is right for the
533 /// members of a host module — `Object.keys(std)` should list them. A method on a host
534 /// class prototype is the opposite: `quickjs-libc.c` defines the seventeen `FILE`
535 /// methods with `JS_CFUNC_DEF`, whose flags leave `enumerable` off, so
536 /// `Object.keys(std.out)` is `[]` in the reference. A host class needs the same.
537 pub fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
538 let Some(object) = object.as_object() else {
539 return Err(Error::Exception(
540 "define_hidden on a non-object".to_string(),
541 ));
542 };
543 object.define(name, Property::with_attributes(value, true, false));
544 Ok(())
545 }
546
547 /// A new ordinary object whose prototype is `proto`.
548 ///
549 /// [`Context::new_object`] gives an object whose prototype is `Object.prototype`; a
550 /// host class needs instances that inherit from its own prototype instead.
551 pub fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value> {
552 let Some(proto) = proto.as_object() else {
553 return Err(Error::Exception("prototype is not an object".to_string()));
554 };
555 let proto = proto.clone();
556 let interp = self.interp();
557 Ok(Value::Object(interp.new_object(Some(proto))))
558 }
559
560 /// The global object, for a host module that has to keep something reachable from
561 /// every host function it installs.
562 ///
563 /// A [`HostFn`](crate::object::HostFn) closure may not hold a `Gc` — the collector
564 /// cannot see into it — so a shared JavaScript value (a class prototype, say) has to
565 /// live where the collector already scans. The global object is the one object every
566 /// interpreter has.
567 pub fn global(&mut self) -> Value {
568 let interp = self.interp();
569 Value::Object(interp.realm.global.clone())
570 }
571
572 /// A string value.
573 pub fn new_string(&mut self, text: &str) -> Value {
574 let interp = self.interp();
575 interp.string(text)
576 }
577
578 /// A number value.
579 pub fn new_number(&mut self, number: f64) -> Value {
580 Value::Float(number)
581 }
582
583 /// A boolean value.
584 pub fn new_boolean(&mut self, value: bool) -> Value {
585 Value::Bool(value)
586 }
587
588 /// Route `print`'s output to `sink` as it happens, in addition to the buffer
589 /// [`Context::output`] reads.
590 ///
591 /// Without a sink a script's output appears only when it finishes. A timer callback
592 /// printing *after* earlier output has to be observably later, which needs the write
593 /// to go out at the moment `print` runs.
594 pub fn set_output_sink(&mut self, sink: Box<dyn std::io::Write>) {
595 self.interp().output_sink = Some(sink);
596 }
597
598 /// Parse `text` in the extended JSON dialect: comments, unquoted keys, single quotes,
599 /// trailing commas, `+1`/`.1`/`0o10`/`0xa0`, and `Infinity`/`NaN`.
600 ///
601 /// This is what backs `std.parseExtJSON`. It is a separate entry point rather than a
602 /// flag on `JSON.parse` because the two must never share behaviour: a relaxed
603 /// `JSON.parse` would silently accept documents the standard rejects.
604 pub fn parse_ext_json(&mut self, text: &str) -> Result<Value> {
605 let interp = self.interp();
606 match interp.parse_ext_json(text) {
607 Ok(value) => Ok(value),
608 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
609 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
610 }
611 }
612
613 /// Schedule `callback` to run after `delay_ms` milliseconds; returns the timer id.
614 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
615 self.interp().schedule_timer(callback, delay_ms)
616 }
617
618 /// A promise that resolves after `delay_ms` — `os.sleepAsync`.
619 pub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value> {
620 let interp = self.interp();
621 match interp.sleep_async(delay_ms) {
622 Ok(value) => Ok(value),
623 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
624 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
625 }
626 }
627
628 /// Register or clear an `os.signal` handler.
629 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
630 self.interp().set_signal_handler(signal, handler);
631 }
632
633 /// Run the handler for `signal`. `false` when none is registered.
634 pub fn fire_signal(&mut self, signal: i32) -> Result<bool> {
635 let interp = self.interp();
636 match interp.fire_signal(signal) {
637 Ok(ran) => Ok(ran),
638 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
639 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
640 }
641 }
642
643 /// Register or clear an `os.setReadHandler`/`os.setWriteHandler` callback.
644 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
645 self.interp().set_fd_handler(fd, readable, callback);
646 }
647
648 /// The descriptors the host must poll, and in which direction.
649 pub fn pending_fds(&self) -> Vec<FdInterest> {
650 // An interpreter that has not been created cannot have handlers: nothing has run.
651 self.interp
652 .as_ref()
653 .map(Interp::pending_fds)
654 .unwrap_or_default()
655 }
656
657 /// Report descriptor readiness, calling the handler. `false` when none was registered.
658 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> Result<bool> {
659 let interp = self.interp();
660 match interp.fire_fd(fd, readable, writable) {
661 Ok(ran) => Ok(ran),
662 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
663 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
664 }
665 }
666
667 /// Cancel a pending timer. `false` when the id is unknown or already fired.
668 pub fn cancel_timer(&mut self, id: i32) -> bool {
669 self.interp().cancel_timer(id)
670 }
671
672 /// Run one turn of the event loop, reporting what the caller should do next.
673 ///
674 /// [`crate::Turn::Wait`] carries the delay to block for; this method never blocks, so
675 /// an embedder decides what "wait" means (a thread sleep, a tokio timer, a test clock).
676 pub fn run_one_turn(&mut self) -> Result<crate::Turn> {
677 let interp = self.interp();
678 match interp.run_one_turn() {
679 Ok(turn) => Ok(turn),
680 Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
681 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
682 }
683 }
684
685 /// Whether any microtask or timer is still pending.
686 pub fn has_pending_work(&self) -> bool {
687 self.interp.as_ref().is_some_and(Interp::has_pending_work)
688 }
689
690 /// Whether a timer or a microtask is pending, ignoring registered descriptors.
691 ///
692 /// A REPL whose stdin is at end of file still has a read handler registered, and that
693 /// handler will keep firing without ever producing another line — so "there is work"
694 /// has to mean something narrower than [`Context::has_pending_work`] there.
695 pub fn has_pending_timers_or_jobs(&self) -> bool {
696 self.interp
697 .as_ref()
698 .is_some_and(Interp::has_pending_timers_or_jobs)
699 }
700
701 /// Rejections nobody handled, drained.
702 ///
703 /// [`Context::eval`] turns these into an error, but an event loop needs them *after*
704 /// every turn rather than at the end of one script: a promise may only become
705 /// unhandled later.
706 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
707 match self.interp.as_mut() {
708 Some(interp) => interp.take_unhandled_rejections(),
709 None => Vec::new(),
710 }
711 }
712
713 /// Errors that timer callbacks threw, drained.
714 pub fn take_timer_errors(&mut self) -> Vec<String> {
715 match self.interp.as_mut() {
716 Some(interp) => interp.take_timer_errors(),
717 None => Vec::new(),
718 }
719 }
720
721 /// Take the buffered output, leaving the buffer empty.
722 ///
723 /// For a host that keeps running turns: [`Context::output`] grows without bound, so
724 /// draining after each turn bounds the memory without changing what any one
725 /// assertion sees.
726 pub fn take_output(&mut self) -> String {
727 match self.interp.as_mut() {
728 Some(interp) => std::mem::take(&mut interp.output),
729 None => String::new(),
730 }
731 }
732}
733
734/// Put `scriptArgs` on the global object.
735///
736/// `scriptArgs` is a host addition, like `print`, so it is installed from the host side
737/// rather than by the realm's builtins. `qjs` defines it only when there is something to
738/// put in it, which is why `-e` with no trailing arguments still leaves an empty array
739/// rather than an absent binding.
740fn install_script_args(interp: &mut Interp<'_>, args: &[String]) {
741 let elements = args
742 .iter()
743 .map(|arg| interp.string(arg.clone()))
744 .collect::<Vec<_>>();
745 let array = interp.new_array(elements);
746 interp
747 .realm
748 .global
749 .clone()
750 .define_data("scriptArgs", Value::Object(array));
751}