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