quickjs-pure 0.10.0

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! `quickjs` — an embeddable JavaScript engine written in pure Rust.
//!
//! The crate is being built as a drop-in replacement for
//! [bellard/quickjs](https://github.com/bellard/quickjs); the language level
//! tracked is the upstream release whose version string is
//! [`COMPAT_VERSION`].
//!
//! # Current state (v0.4.0 — milestones M0–M6)
//!
//! Source is parsed, compiled to bytecode and executed: [`Context::eval`] runs a
//! script and returns its completion value, and [`Context::output`] holds whatever
//! `print` wrote.
//!
//! ```
//! let rt = quickjs::Runtime::new();
//! let mut ctx = quickjs::Context::new(&rt);
//! ctx.eval("print(1 + 1)").expect("runs");
//! assert_eq!(ctx.output(), "2\n");
//! ```
//!
//! The standard library covers `Object`, `Function`, `Array`, `String`, `Number`,
//! `Math`, `JSON`, `Reflect`, `Date`, `RegExp`, `Symbol`, `Map`/`Set`, `BigInt`,
//! TypedArray, `DataView` and the error classes; the ES6+ runtime is in place
//! (class, destructuring, generators, `Proxy`, `Promise`/async, `for await`); and
//! ES modules run through [`Context::eval_module`].
//!
//! # Not there yet
//!
//! Every gap below is a loud failure rather than a wrong answer:
//!
//! * private class fields (`#x`) are rejected by the compiler with a
//!   `SyntaxError`;
//! * the `std`/`os` host modules and the event loop are absent, so `setTimeout`
//!   is undefined and a script cannot touch the filesystem;
//! * `Iterator` helpers and `RegExp.escape` are missing, and `RegExp` lookbehind
//!   does not parse;
//! * the host API is still small: a script can be evaluated, but Rust cannot yet
//!   register a native function on the global object or call a JavaScript
//!   function back.
//!
//! See `docs/requirements.md` in the repository for the milestone plan and
//! `docs/test262-status.md` for the measured language coverage.

#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]

pub use js_compile;
pub use js_gc::{CollectStats, Gc, Heap, Trace, Tracer, WeakGc};
pub use js_parse;

mod bignum;

pub mod bigint;
pub mod builtins;
pub mod interp;
pub mod module;
pub mod object;
/// The reference's `JS_PrintValue`, which lives in the *engine* (`quickjs.c`) and not in
/// the host library. `std.__printObject` is a one-line wrapper over it, and so is the
/// reporting of an uncaught exception — which is why this belongs here rather than in
/// `quickjs-host`.
pub mod print;
// The engine lives in its own crate so that `quickjs-compile` can validate a `/…/u`
// literal at parse time without depending on this one.
pub use quickjs_regexp as regexp;
mod tzif;
pub mod value;

pub use interp::{FdInterest, Interp, JsResult, Signal, Task, Turn};
pub use object::{Callable, JsObject, ObjectKind, Property};
pub use value::{Cell, JsString, Value};

/// Version string of the upstream QuickJS release this port tracks.
pub const COMPAT_VERSION: &str = "2026-06-04";

/// Error raised by the engine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// The source did not parse, or did not compile.
    Syntax(String),
    /// The script threw, or the engine raised while running it.
    Exception(String),
    /// The feature/entry point exists in the API but is not implemented yet.
    NotImplemented(&'static str),
    /// The runtime exceeded its memory limit (`--memory-limit`).
    OutOfMemory,
    /// The runtime exceeded its stack limit (`--stack-size`).
    StackOverflow,
}

impl Error {
    /// A compile error, rendered the way the reference prints one.
    ///
    /// `SyntaxError: <message>` and, when the error has a position,
    /// `    at <file>:<line>:<column>` on the next line. The reference gets this shape
    /// from `js_std_dump_error` printing an exception object whose `stack` is those two
    /// lines; we have no object yet (nothing has run), so the text is built directly.
    ///
    /// A parse error is not "`file: SyntaxError: L:C: message`", which is what the CLI
    /// used to print: that put the file name where the reference puts nothing, and the
    /// position where the reference puts the file name.
    fn syntax(error: &js_parse::SyntaxError, file: &str) -> Error {
        if error.positionless {
            Error::Syntax(error.message.clone())
        } else {
            Error::Syntax(format!(
                "{}\n    at {}:{}:{}",
                error.message, file, error.span.start.line, error.span.start.column
            ))
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::NotImplemented(what) => write!(f, "not implemented yet: {what}"),
            // A compile error is a `SyntaxError` in the language, and saying so is not
            // cosmetic: the conformance runner classifies a `negative:` test by the
            // constructor name in the message, and the reference prints the same prefix.
            Error::Syntax(what) => write!(f, "SyntaxError: {what}"),
            Error::Exception(what) => write!(f, "{what}"),
            Error::OutOfMemory => write!(f, "out of memory"),
            Error::StackOverflow => write!(f, "stack overflow"),
        }
    }
}

impl std::error::Error for Error {}

/// Convenience alias used throughout the crate.
pub type Result<T> = std::result::Result<T, Error>;

/// [`js_parse::is_module_source`], which is the rule `qjs` uses to decide module mode.
///
/// It lives in the parser because it is a question about source text, not about the
/// engine: `qjsc` needs the same answer and has no business linking an interpreter to
/// get it.
pub use js_parse::is_module_source;

/// A JavaScript runtime: one heap, one memory limit, one set of host hooks.
///
/// Mirrors the role of `JSRuntime` in the QuickJS C API.
pub struct Runtime {
    heap: Heap,
    memory_limit: Option<usize>,
    stack_size: Option<usize>,
}

impl Default for Runtime {
    fn default() -> Self {
        Self::new()
    }
}

impl Runtime {
    /// Create a runtime with default limits.
    pub fn new() -> Runtime {
        Runtime {
            heap: Heap::new(),
            memory_limit: None,
            stack_size: None,
        }
    }

    /// The runtime's object heap.
    pub fn heap(&self) -> &Heap {
        &self.heap
    }

    /// Equivalent of `JS_SetMemoryLimit`.
    pub fn set_memory_limit(&mut self, limit: Option<usize>) {
        self.memory_limit = limit;
    }

    /// Configured memory limit, if any.
    pub fn memory_limit(&self) -> Option<usize> {
        self.memory_limit
    }

    /// Equivalent of `JS_SetMaxStackSize`.
    pub fn set_stack_size(&mut self, limit: Option<usize>) {
        self.stack_size = limit;
    }

    /// Configured stack size limit, if any.
    pub fn stack_size(&self) -> Option<usize> {
        self.stack_size
    }

    /// Equivalent of `JS_RunGC`.
    pub fn run_gc(&self) -> CollectStats {
        self.heap.collect()
    }
}

/// An execution context: a global object plus the builtins installed on it.
///
/// Mirrors the role of `JSContext` in the QuickJS C API.
pub struct Context<'rt> {
    runtime: &'rt Runtime,
    /// The interpreter, created on first use.
    interp: Option<Interp<'rt>>,
    /// A loader the host installed, handed to the interpreter when it is built.
    module_loader: Option<Box<dyn module::ModuleLoader>>,
    /// The value of the last script, as `qjs` reports it.
    last_value: Value,
    /// The name a top-level script is compiled under, which is what `error.stack`
    /// prints: `<cmdline>` for `-e`, a path for a file, `None` for `<input>`.
    script_name: Option<String>,
    /// The script arguments, as `qjs` exposes them through `scriptArgs`.
    ///
    /// Kept here and installed into the realm on first use, because the interpreter (and
    /// so the global object) does not exist until something runs.
    script_args: Option<Vec<String>>,
}

impl<'rt> Context<'rt> {
    /// Create a context on `runtime`.
    pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
        Context {
            runtime,
            interp: None,
            module_loader: None,
            last_value: Value::Undefined,
            script_name: None,
            script_args: None,
        }
    }

    /// Install how module specifiers are resolved and read.
    ///
    /// Without one, importing is a clear error rather than a silent failure: the engine
    /// cannot guess whether `./x.js` means a file, and the host is what knows.
    pub fn set_module_loader(&mut self, loader: Box<dyn module::ModuleLoader>) {
        // A context that has already run something owns a live interpreter, so the loader
        // goes to whichever exists.
        if let Some(interp) = self.interp.as_mut() {
            interp.module_loader = Some(loader);
        } else {
            self.module_loader = Some(loader);
        }
    }

    /// Name the scripts this context evaluates, for stack traces.
    ///
    /// Mirrors what `qjs` passes to `JS_Eval`: `-e` code is `<cmdline>`, a script file
    /// is its own path. Without a name, frames print `<input>`, which is what the
    /// reference uses for code with no file behind it.
    pub fn set_script_name(&mut self, name: impl Into<String>) {
        self.script_name = Some(name.into());
    }

    /// Set the arguments `scriptArgs` should hold.
    ///
    /// Element 0 is the script itself, matching `qjs`: `qjs f.js a b` gives
    /// `["f.js", "a", "b"]`. With `-e` there is no script, so the array is just the
    /// trailing arguments and `-e`'s own text never appears in it.
    ///
    /// This was parsed by the CLI and then dropped on the floor: `opts.script_args` was
    /// assigned in two places and read in none, so `scriptArgs` was simply undeclared.
    /// An ordinary script's `if (typeof scriptArgs != "undefined")` branch therefore never
    /// ran, and `examples/pi_bigint.js` printed a thousand digits of pi where the
    /// reference printed `usage: pi n_digits`.
    ///
    /// Works whether or not the interpreter exists yet. The realm is built on first use,
    /// so a host that installs something *else* first (an output sink, a host function)
    /// would otherwise create it early and have these arguments silently dropped — which
    /// is exactly what `print(JSON.stringify(scriptArgs))` caught.
    pub fn set_script_args(&mut self, args: Vec<String>) {
        if let Some(interp) = self.interp.as_mut() {
            install_script_args(interp, &args);
        } else {
            self.script_args = Some(args);
        }
    }

    /// The runtime this context belongs to.
    pub fn runtime(&self) -> &'rt Runtime {
        self.runtime
    }

    /// Everything `print` has written.
    pub fn output(&self) -> &str {
        self.interp.as_ref().map_or("", |interp| &interp.output)
    }

    /// The interpreter, creating it and its realm on first use.
    fn interp(&mut self) -> &mut Interp<'rt> {
        let heap: &'rt Heap = &self.runtime.heap;
        let loader = self.module_loader.take();
        let script_args = self.script_args.take();
        let memory_limit = self.runtime.memory_limit;
        let stack_size = self.runtime.stack_size;
        self.interp.get_or_insert_with(|| {
            let mut interp = Interp::new(heap);
            interp.module_loader = loader;
            // The limits are the runtime's, and the interpreter is created lazily on first
            // use — so they have to be handed over here rather than in `Runtime`. `None`
            // means the defaults, which are the reference's: no memory cap, and
            // `JS_DEFAULT_STACK_SIZE`.
            heap.set_memory_limit(memory_limit);
            if let Some(size) = stack_size {
                interp.stack_limit = size;
            }
            if let Some(args) = script_args {
                install_script_args(&mut interp, &args);
            }
            interp
        })
    }
    /// Evaluate `specifier` as the entry module, the way `qjs -m` does.
    ///
    /// The microtask queue is drained afterwards, so a module whose top level launched an
    /// async task has finished it by the time this returns.
    pub fn eval_module(&mut self, specifier: &str) -> Result<Value> {
        let loader = self.module_loader.take();
        let interp = self.interp();
        if interp.module_loader.is_none() {
            interp.module_loader = loader;
        }
        match interp.run_main_module(specifier) {
            Ok(value) => {
                let drained = interp.drain_jobs();
                let unhandled = interp.take_unhandled_rejections();
                if let Err(Signal::Throw(reason)) = drained {
                    let text = interp.describe_exception(&reason);
                    return Err(Error::Exception(text));
                }
                if !unhandled.is_empty() {
                    return Err(Error::Exception(unhandled.join("\n")));
                }
                self.last_value = value.clone();
                Ok(value)
            }
            Err(Signal::Throw(value)) => {
                let text = interp.describe_exception(&value);
                Err(Error::Exception(text))
            }
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Evaluate an already-compiled bytecode blob, as an AOT binary does.
    ///
    /// Nothing is parsed and nothing is compiled: the input is
    /// [`js_compile::serialize::serialize`]'s output, which carries the file name, the
    /// optional source text and the module tables alongside the code. A blob with module
    /// tables is run the way `qjs -m` runs a file — its requests are resolved through the
    /// installed module loader, so a precompiled entry module can still import ordinary
    /// source files.
    ///
    /// A blob is only accepted when its format *version* matches this build. Bytecode and
    /// the opcode table are one unit, so a stale blob is rejected instead of being read
    /// as different instructions.
    pub fn eval_bytecode(&mut self, bytes: &[u8]) -> Result<Value> {
        let code = js_compile::serialize::deserialize(bytes)
            .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
        let is_module = code.module.is_some();
        let loader = self.module_loader.take();
        let interp = self.interp();
        if interp.module_loader.is_none() {
            interp.module_loader = loader;
        }
        let outcome = if is_module {
            interp.run_precompiled_module(code)
        } else {
            interp.run_script(code)
        };
        match outcome {
            Ok(value) => {
                // An unhandled rejection is fatal *after* the body finishes, which is when
                // the reference decides nothing else will claim it. The body's own output
                // has already been buffered, so it still prints first.
                let drained = interp.drain_jobs();
                let unhandled = interp.take_unhandled_rejections();
                if let Err(Signal::Throw(reason)) = drained {
                    let text = interp.describe_exception(&reason);
                    return Err(Error::Exception(text));
                }
                if !unhandled.is_empty() {
                    return Err(Error::Exception(unhandled.join("\n")));
                }
                self.last_value = value.clone();
                Ok(value)
            }
            Err(Signal::Throw(value)) => {
                let text = interp.describe_exception(&value);
                Err(Error::Exception(text))
            }
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Register a module from bytecode, so an import of it never reaches the loader.
    ///
    /// This is the second half of AOT for modules: `qjsc` compiles every module the program
    /// can reach into a blob, and the product registers them all before running the entry
    /// one. The name comes from the blob (`qjsc` stamped it), and it is the name the loader
    /// would have produced, so `import "./dep.js"` finds it.
    pub fn register_module(&mut self, bytes: &[u8]) -> Result<String> {
        let code = js_compile::serialize::deserialize(bytes)
            .map_err(|error| Error::Syntax(format!("invalid bytecode: {error}")))?;
        if code.module.is_none() {
            return Err(Error::Syntax(
                "invalid bytecode: this blob is a script, not a module".to_string(),
            ));
        }
        let interp = self.interp();
        match interp.register_module(code) {
            Ok(name) => Ok(name),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Register a JSON, text or bytes module from its bytes, by name.
    ///
    /// `attributes` is the module's `with { type: … }` list, or empty for the name's
    /// extension to decide — the same rule the loader applies.
    pub fn register_data_module(
        &mut self,
        name: &str,
        source: Vec<u8>,
        attributes: &[(String, String)],
    ) -> Result<()> {
        let interp = self.interp();
        match interp.register_data_module(name, source, attributes) {
            Ok(()) => Ok(()),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Evaluate `source` as a global script and return its completion value.
    ///
    /// The value is reported the way `qjs -e` reports it: a string for anything the
    /// script leaves on the stack, and nothing at all for `undefined`.
    pub fn eval(&mut self, source: &str) -> Result<Value> {
        self.eval_in(source, false)
    }

    /// [`Context::eval`] with the whole script strict from its first token.
    ///
    /// This is `qjs --strict`, and the reason it is a parse *mode* rather than a prepended
    /// `"use strict"`: a directive shifts every column on the first line, and those
    /// columns are what a stack trace reports. The reference does the same thing one level
    /// down, with `JS_EVAL_FLAG_STRICT`.
    pub fn eval_strict(&mut self, source: &str) -> Result<Value> {
        self.eval_in(source, true)
    }

    fn eval_in(&mut self, source: &str, strict: bool) -> Result<Value> {
        let program = if strict {
            js_parse::parse_script_strict(source)
        } else {
            js_parse::parse_script(source)
        }
        .map_err(|error| Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>")))?;
        let mut code = js_compile::compile_script(&program).map_err(|error| {
            Error::syntax(&error, self.script_name.as_deref().unwrap_or("<input>"))
        })?;
        // Position information travels with the code, but the file name is the host's
        // to supply — the parser never sees it.
        code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
        let interp = self.interp();
        match interp.run_script(code) {
            Ok(value) => {
                // An unhandled rejection is fatal *after* the script finishes, which is
                // when the reference decides nothing else will claim it. The script's own
                // output has already been buffered, so it still prints first.
                let unhandled = interp.take_unhandled_rejections();
                if !unhandled.is_empty() {
                    return Err(Error::Exception(unhandled.join("\n")));
                }
                self.last_value = value.clone();
                Ok(value)
            }
            Err(Signal::Throw(value)) => {
                let text = interp.describe_exception(&value);
                Err(Error::Exception(text))
            }
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// The value of the script that ran last.
    pub fn last_value(&self) -> &Value {
        &self.last_value
    }

    // -----------------------------------------------------------------------
    // Host surface: what an embedding needs to expose its own functions.
    //
    // These are narrow on purpose. Handing the host `&mut Interp` would let it hold a
    // borrow that outlives the `Context`, and every method here would have to be
    // re-derived at each call site. Each one below is a single well-defined operation.
    // -----------------------------------------------------------------------

    /// A host function as a value, for putting on an object rather than the global.
    ///
    /// [`Context::set_global_function`] is this plus the install; a host *module* needs the
    /// function first and the install second, on its own object.
    pub fn new_host_function_value(
        &mut self,
        name: &str,
        length: u32,
        f: crate::object::HostFn,
    ) -> Result<Value> {
        let interp = self.interp();
        Ok(Value::Object(interp.new_host_function(name, length, f)))
    }

    /// Install `value` on the global object as `name`.
    ///
    /// A host module is one object with functions on it, so mounting `std` is a single
    /// `set_global` rather than a function per name — which is what
    /// [`Context::set_global_function`] does.
    pub fn set_global(&mut self, name: &str, value: Value) -> Result<()> {
        let global = self.interp().realm.global.clone();
        global.define(name, Property::with_attributes(value, true, false));
        Ok(())
    }

    /// Install `f` on the global object as `name`.
    ///
    /// This is how a host module is built: `std.loadFile` is a global function the host
    /// registers before the script runs. The closure may capture Rust state but **must
    /// not capture a [`Gc`]** — see [`crate::object::HostFn`].
    pub fn set_global_function(
        &mut self,
        name: &str,
        length: u32,
        f: crate::object::HostFn,
    ) -> Result<()> {
        let interp = self.interp();
        let function = interp.new_host_function(name, length, f);
        let global = interp.realm.global.clone();
        global.define(
            name,
            Property::with_attributes(Value::Object(function), true, false),
        );
        Ok(())
    }

    /// Install `f` on the global object as the constructor `name`.
    ///
    /// Unlike [`Context::set_global_function`] this one gets a `prototype` object, which
    /// it owns and which `new` uses — the shape a host class like `std.File` needs.
    /// Returns the constructor so the host can put methods on its `prototype`.
    pub fn set_global_constructor(
        &mut self,
        name: &str,
        length: u32,
        f: crate::object::HostFn,
    ) -> Result<Value> {
        let interp = self.interp();
        let function = interp.new_host_ctor(name, length, f);
        let global = interp.realm.global.clone();
        global.define(
            name,
            Property::with_attributes(Value::Object(function.clone()), true, false),
        );
        Ok(Value::Object(function))
    }

    /// Call a JavaScript function from Rust.
    ///
    /// A thrown value comes back as [`Error::Exception`], so a host callback can report
    /// the script's own error rather than swallowing it.
    pub fn call(&mut self, function: Value, this: Value, args: Vec<Value>) -> Result<Value> {
        let interp = self.interp();
        match interp.call_value(function, this, args) {
            Ok(value) => Ok(value),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// A fresh empty object, for the host to hand back to a script.
    pub fn new_object(&mut self) -> Value {
        let interp = self.interp();
        let proto = interp.realm.object_proto.clone();
        Value::Object(interp.new_object(Some(proto)))
    }

    /// Set `name` on `object` to `value`, as a plain writable property.
    pub fn set_property(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
        let Some(object) = object.as_object() else {
            return Err(Error::Exception("set_property on a non-object".to_string()));
        };
        object.define(name, Property::with_attributes(value, true, true));
        Ok(())
    }

    /// Define `name` on `object` as a **non-enumerable** data property.
    ///
    /// [`Context::set_property`] writes an enumerable property, which is right for the
    /// members of a host module — `Object.keys(std)` should list them. A method on a host
    /// class prototype is the opposite: `quickjs-libc.c` defines the seventeen `FILE`
    /// methods with `JS_CFUNC_DEF`, whose flags leave `enumerable` off, so
    /// `Object.keys(std.out)` is `[]` in the reference. A host class needs the same.
    pub fn define_hidden(&mut self, object: &Value, name: &str, value: Value) -> Result<()> {
        let Some(object) = object.as_object() else {
            return Err(Error::Exception(
                "define_hidden on a non-object".to_string(),
            ));
        };
        object.define(name, Property::with_attributes(value, true, false));
        Ok(())
    }

    /// A new ordinary object whose prototype is `proto`.
    ///
    /// [`Context::new_object`] gives an object whose prototype is `Object.prototype`; a
    /// host class needs instances that inherit from its own prototype instead.
    pub fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value> {
        let Some(proto) = proto.as_object() else {
            return Err(Error::Exception("prototype is not an object".to_string()));
        };
        let proto = proto.clone();
        let interp = self.interp();
        Ok(Value::Object(interp.new_object(Some(proto))))
    }

    /// The global object, for a host module that has to keep something reachable from
    /// every host function it installs.
    ///
    /// A [`HostFn`](crate::object::HostFn) closure may not hold a `Gc` — the collector
    /// cannot see into it — so a shared JavaScript value (a class prototype, say) has to
    /// live where the collector already scans. The global object is the one object every
    /// interpreter has.
    pub fn global(&mut self) -> Value {
        let interp = self.interp();
        Value::Object(interp.realm.global.clone())
    }

    /// A string value.
    pub fn new_string(&mut self, text: &str) -> Value {
        let interp = self.interp();
        interp.string(text)
    }

    /// A number value.
    pub fn new_number(&mut self, number: f64) -> Value {
        Value::Float(number)
    }

    /// A boolean value.
    pub fn new_boolean(&mut self, value: bool) -> Value {
        Value::Bool(value)
    }

    /// Route `print`'s output to `sink` as it happens, in addition to the buffer
    /// [`Context::output`] reads.
    ///
    /// Without a sink a script's output appears only when it finishes. A timer callback
    /// printing *after* earlier output has to be observably later, which needs the write
    /// to go out at the moment `print` runs.
    pub fn set_output_sink(&mut self, sink: Box<dyn std::io::Write>) {
        self.interp().output_sink = Some(sink);
    }

    /// Parse `text` in the extended JSON dialect: comments, unquoted keys, single quotes,
    /// trailing commas, `+1`/`.1`/`0o10`/`0xa0`, and `Infinity`/`NaN`.
    ///
    /// This is what backs `std.parseExtJSON`. It is a separate entry point rather than a
    /// flag on `JSON.parse` because the two must never share behaviour: a relaxed
    /// `JSON.parse` would silently accept documents the standard rejects.
    pub fn parse_ext_json(&mut self, text: &str) -> Result<Value> {
        let interp = self.interp();
        match interp.parse_ext_json(text) {
            Ok(value) => Ok(value),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Schedule `callback` to run after `delay_ms` milliseconds; returns the timer id.
    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
        self.interp().schedule_timer(callback, delay_ms)
    }

    /// A promise that resolves after `delay_ms` — `os.sleepAsync`.
    pub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value> {
        let interp = self.interp();
        match interp.sleep_async(delay_ms) {
            Ok(value) => Ok(value),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Register or clear an `os.signal` handler.
    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
        self.interp().set_signal_handler(signal, handler);
    }

    /// Run the handler for `signal`. `false` when none is registered.
    pub fn fire_signal(&mut self, signal: i32) -> Result<bool> {
        let interp = self.interp();
        match interp.fire_signal(signal) {
            Ok(ran) => Ok(ran),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Register or clear an `os.setReadHandler`/`os.setWriteHandler` callback.
    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
        self.interp().set_fd_handler(fd, readable, callback);
    }

    /// The descriptors the host must poll, and in which direction.
    pub fn pending_fds(&self) -> Vec<FdInterest> {
        // An interpreter that has not been created cannot have handlers: nothing has run.
        self.interp
            .as_ref()
            .map(Interp::pending_fds)
            .unwrap_or_default()
    }

    /// Report descriptor readiness, calling the handler. `false` when none was registered.
    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> Result<bool> {
        let interp = self.interp();
        match interp.fire_fd(fd, readable, writable) {
            Ok(ran) => Ok(ran),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Cancel a pending timer. `false` when the id is unknown or already fired.
    pub fn cancel_timer(&mut self, id: i32) -> bool {
        self.interp().cancel_timer(id)
    }

    /// Run one turn of the event loop, reporting what the caller should do next.
    ///
    /// [`crate::Turn::Wait`] carries the delay to block for; this method never blocks, so
    /// an embedder decides what "wait" means (a thread sleep, a tokio timer, a test clock).
    pub fn run_one_turn(&mut self) -> Result<crate::Turn> {
        let interp = self.interp();
        match interp.run_one_turn() {
            Ok(turn) => Ok(turn),
            Err(Signal::Throw(value)) => Err(Error::Exception(interp.describe_exception(&value))),
            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
        }
    }

    /// Whether any microtask or timer is still pending.
    pub fn has_pending_work(&self) -> bool {
        self.interp.as_ref().is_some_and(Interp::has_pending_work)
    }

    /// Whether a timer or a microtask is pending, ignoring registered descriptors.
    ///
    /// A REPL whose stdin is at end of file still has a read handler registered, and that
    /// handler will keep firing without ever producing another line — so "there is work"
    /// has to mean something narrower than [`Context::has_pending_work`] there.
    pub fn has_pending_timers_or_jobs(&self) -> bool {
        self.interp
            .as_ref()
            .is_some_and(Interp::has_pending_timers_or_jobs)
    }

    /// Rejections nobody handled, drained.
    ///
    /// [`Context::eval`] turns these into an error, but an event loop needs them *after*
    /// every turn rather than at the end of one script: a promise may only become
    /// unhandled later.
    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
        match self.interp.as_mut() {
            Some(interp) => interp.take_unhandled_rejections(),
            None => Vec::new(),
        }
    }

    /// Errors that timer callbacks threw, drained.
    pub fn take_timer_errors(&mut self) -> Vec<String> {
        match self.interp.as_mut() {
            Some(interp) => interp.take_timer_errors(),
            None => Vec::new(),
        }
    }

    /// Take the buffered output, leaving the buffer empty.
    ///
    /// For a host that keeps running turns: [`Context::output`] grows without bound, so
    /// draining after each turn bounds the memory without changing what any one
    /// assertion sees.
    pub fn take_output(&mut self) -> String {
        match self.interp.as_mut() {
            Some(interp) => std::mem::take(&mut interp.output),
            None => String::new(),
        }
    }
}

/// Put `scriptArgs` on the global object.
///
/// `scriptArgs` is a host addition, like `print`, so it is installed from the host side
/// rather than by the realm's builtins. `qjs` defines it only when there is something to
/// put in it, which is why `-e` with no trailing arguments still leaves an empty array
/// rather than an absent binding.
fn install_script_args(interp: &mut Interp<'_>, args: &[String]) {
    let elements = args
        .iter()
        .map(|arg| interp.string(arg.clone()))
        .collect::<Vec<_>>();
    let array = interp.new_array(elements);
    interp
        .realm
        .global
        .clone()
        .define_data("scriptArgs", Value::Object(array));
}