Skip to main content

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 (M3)
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//! Not there yet: the standard library beyond `print`, classes and generators, and
22//! modules. Those are later milestones (see `docs/requirements.md`).
23
24#![deny(unsafe_op_in_unsafe_fn)]
25#![warn(missing_docs)]
26
27pub use js_compile;
28pub use js_gc::{CollectStats, Gc, Heap, Trace, Tracer, WeakGc};
29pub use js_parse;
30
31mod bignum;
32
33pub mod bigint;
34pub mod builtins;
35pub mod interp;
36pub mod object;
37pub mod regexp;
38mod tzif;
39pub mod value;
40
41pub use interp::{Interp, Signal};
42pub use object::{Callable, JsObject, ObjectKind, Property};
43pub use value::{Cell, JsString, Value};
44
45/// Version string of the upstream QuickJS release this port tracks.
46pub const COMPAT_VERSION: &str = "2026-06-04";
47
48/// Error raised by the engine.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum Error {
51    /// The source did not parse, or did not compile.
52    Syntax(String),
53    /// The script threw, or the engine raised while running it.
54    Exception(String),
55    /// The feature/entry point exists in the API but is not implemented yet.
56    NotImplemented(&'static str),
57    /// The runtime exceeded its memory limit (`--memory-limit`).
58    OutOfMemory,
59    /// The runtime exceeded its stack limit (`--stack-size`).
60    StackOverflow,
61}
62
63impl std::fmt::Display for Error {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self {
66            Error::NotImplemented(what) => write!(f, "not implemented yet: {what}"),
67            Error::Syntax(what) => write!(f, "{what}"),
68            Error::Exception(what) => write!(f, "{what}"),
69            Error::OutOfMemory => write!(f, "out of memory"),
70            Error::StackOverflow => write!(f, "stack overflow"),
71        }
72    }
73}
74
75impl std::error::Error for Error {}
76
77/// Convenience alias used throughout the crate.
78pub type Result<T> = std::result::Result<T, Error>;
79
80/// A JavaScript runtime: one heap, one memory limit, one set of host hooks.
81///
82/// Mirrors the role of `JSRuntime` in the QuickJS C API.
83pub struct Runtime {
84    heap: Heap,
85    memory_limit: Option<usize>,
86    stack_size: Option<usize>,
87}
88
89impl Default for Runtime {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95impl Runtime {
96    /// Create a runtime with default limits.
97    pub fn new() -> Runtime {
98        Runtime {
99            heap: Heap::new(),
100            memory_limit: None,
101            stack_size: None,
102        }
103    }
104
105    /// The runtime's object heap.
106    pub fn heap(&self) -> &Heap {
107        &self.heap
108    }
109
110    /// Equivalent of `JS_SetMemoryLimit`.
111    pub fn set_memory_limit(&mut self, limit: Option<usize>) {
112        self.memory_limit = limit;
113    }
114
115    /// Configured memory limit, if any.
116    pub fn memory_limit(&self) -> Option<usize> {
117        self.memory_limit
118    }
119
120    /// Equivalent of `JS_SetMaxStackSize`.
121    pub fn set_stack_size(&mut self, limit: Option<usize>) {
122        self.stack_size = limit;
123    }
124
125    /// Configured stack size limit, if any.
126    pub fn stack_size(&self) -> Option<usize> {
127        self.stack_size
128    }
129
130    /// Equivalent of `JS_RunGC`.
131    pub fn run_gc(&self) -> CollectStats {
132        self.heap.collect()
133    }
134}
135
136/// An execution context: a global object plus the builtins installed on it.
137///
138/// Mirrors the role of `JSContext` in the QuickJS C API.
139pub struct Context<'rt> {
140    runtime: &'rt Runtime,
141    /// The interpreter, created on first use.
142    interp: Option<Interp<'rt>>,
143    /// The value of the last script, as `qjs` reports it.
144    last_value: Value,
145    /// The name a top-level script is compiled under, which is what `error.stack`
146    /// prints: `<cmdline>` for `-e`, a path for a file, `None` for `<input>`.
147    script_name: Option<String>,
148}
149
150impl<'rt> Context<'rt> {
151    /// Create a context on `runtime`.
152    pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
153        Context {
154            runtime,
155            interp: None,
156            last_value: Value::Undefined,
157            script_name: None,
158        }
159    }
160
161    /// Name the scripts this context evaluates, for stack traces.
162    ///
163    /// Mirrors what `qjs` passes to `JS_Eval`: `-e` code is `<cmdline>`, a script file
164    /// is its own path. Without a name, frames print `<input>`, which is what the
165    /// reference uses for code with no file behind it.
166    pub fn set_script_name(&mut self, name: impl Into<String>) {
167        self.script_name = Some(name.into());
168    }
169
170    /// The runtime this context belongs to.
171    pub fn runtime(&self) -> &'rt Runtime {
172        self.runtime
173    }
174
175    /// Everything `print` has written.
176    pub fn output(&self) -> &str {
177        self.interp.as_ref().map_or("", |interp| &interp.output)
178    }
179
180    /// The interpreter, creating it and its realm on first use.
181    fn interp(&mut self) -> &mut Interp<'rt> {
182        let heap: &'rt Heap = &self.runtime.heap;
183        self.interp.get_or_insert_with(|| Interp::new(heap))
184    }
185
186    /// Evaluate `source` as a global script and return its completion value.
187    ///
188    /// The value is reported the way `qjs -e` reports it: a string for anything the
189    /// script leaves on the stack, and nothing at all for `undefined`.
190    pub fn eval(&mut self, source: &str) -> Result<Value> {
191        let program =
192            js_parse::parse_script(source).map_err(|error| Error::Syntax(error.to_string()))?;
193        let mut code = js_compile::compile_script(&program)
194            .map_err(|error| Error::Syntax(error.message.clone()))?;
195        // Position information travels with the code, but the file name is the host's
196        // to supply — the parser never sees it.
197        code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
198        let interp = self.interp();
199        match interp.run_script(code) {
200            Ok(value) => {
201                // An unhandled rejection is fatal *after* the script finishes, which is
202                // when the reference decides nothing else will claim it. The script's own
203                // output has already been buffered, so it still prints first.
204                let unhandled = interp.take_unhandled_rejections();
205                if !unhandled.is_empty() {
206                    return Err(Error::Exception(unhandled.join("\n")));
207                }
208                self.last_value = value.clone();
209                Ok(value)
210            }
211            Err(Signal::Throw(value)) => {
212                let text = interp.describe_exception(&value);
213                Err(Error::Exception(text))
214            }
215            Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
216        }
217    }
218
219    /// The value of the script that ran last.
220    pub fn last_value(&self) -> &Value {
221        &self.last_value
222    }
223}