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 module;
37pub mod object;
38pub mod regexp;
39mod tzif;
40pub mod value;
41
42pub use interp::{Interp, Signal};
43pub use object::{Callable, JsObject, ObjectKind, Property};
44pub use value::{Cell, JsString, Value};
45
46/// Version string of the upstream QuickJS release this port tracks.
47pub const COMPAT_VERSION: &str = "2026-06-04";
48
49/// Error raised by the engine.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum Error {
52 /// The source did not parse, or did not compile.
53 Syntax(String),
54 /// The script threw, or the engine raised while running it.
55 Exception(String),
56 /// The feature/entry point exists in the API but is not implemented yet.
57 NotImplemented(&'static str),
58 /// The runtime exceeded its memory limit (`--memory-limit`).
59 OutOfMemory,
60 /// The runtime exceeded its stack limit (`--stack-size`).
61 StackOverflow,
62}
63
64impl std::fmt::Display for Error {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 match self {
67 Error::NotImplemented(what) => write!(f, "not implemented yet: {what}"),
68 Error::Syntax(what) => write!(f, "{what}"),
69 Error::Exception(what) => write!(f, "{what}"),
70 Error::OutOfMemory => write!(f, "out of memory"),
71 Error::StackOverflow => write!(f, "stack overflow"),
72 }
73 }
74}
75
76impl std::error::Error for Error {}
77
78/// Convenience alias used throughout the crate.
79pub type Result<T> = std::result::Result<T, Error>;
80
81/// Whether `source` should be evaluated as a module, decided the way `qjs` decides.
82///
83/// The rule is deliberately shallow: the **first token** must be `import` or `export`
84/// (an `import` followed by `.` or `(` is `import.meta` or `import()`, both of which are
85/// expressions, so a script may use them). Nothing else makes a file a module.
86///
87/// It has to be this shallow to match the reference, and the difference is observable:
88/// a file that merely *mentions* `import.meta` further down is a script, so it fails with
89/// "import.meta only valid in module code" rather than silently becoming a module.
90pub fn is_module_source(source: &str) -> bool {
91 let bytes = source.as_bytes();
92 let mut index = 0;
93 // A shebang line is not code.
94 if bytes.starts_with(b"#!") {
95 while index < bytes.len() && bytes[index] != b'\n' {
96 index += 1;
97 }
98 }
99 loop {
100 // Whitespace.
101 while index < bytes.len() && bytes[index].is_ascii_whitespace() {
102 index += 1;
103 }
104 if bytes[index..].starts_with(b"//") {
105 while index < bytes.len() && bytes[index] != b'\n' {
106 index += 1;
107 }
108 continue;
109 }
110 if bytes[index..].starts_with(b"/*") {
111 index += 2;
112 while index < bytes.len() && !bytes[index..].starts_with(b"*/") {
113 index += 1;
114 }
115 index = (index + 2).min(bytes.len());
116 continue;
117 }
118 break;
119 }
120 let rest = &source[index.min(source.len())..];
121 let word = |w: &str| -> Option<&str> { rest.strip_prefix(w) };
122 if let Some(tail) = word("export") {
123 // `exportedThing` is an identifier, not the keyword.
124 return !tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$');
125 }
126 if let Some(tail) = word("import") {
127 if tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$') {
128 return false;
129 }
130 let tail = tail.trim_start();
131 // `import.meta` and `import(...)` are expressions.
132 if tail.starts_with('.') || tail.starts_with('(') {
133 return false;
134 }
135 return true;
136 }
137 false
138}
139
140/// A JavaScript runtime: one heap, one memory limit, one set of host hooks.
141///
142/// Mirrors the role of `JSRuntime` in the QuickJS C API.
143pub struct Runtime {
144 heap: Heap,
145 memory_limit: Option<usize>,
146 stack_size: Option<usize>,
147}
148
149impl Default for Runtime {
150 fn default() -> Self {
151 Self::new()
152 }
153}
154
155impl Runtime {
156 /// Create a runtime with default limits.
157 pub fn new() -> Runtime {
158 Runtime {
159 heap: Heap::new(),
160 memory_limit: None,
161 stack_size: None,
162 }
163 }
164
165 /// The runtime's object heap.
166 pub fn heap(&self) -> &Heap {
167 &self.heap
168 }
169
170 /// Equivalent of `JS_SetMemoryLimit`.
171 pub fn set_memory_limit(&mut self, limit: Option<usize>) {
172 self.memory_limit = limit;
173 }
174
175 /// Configured memory limit, if any.
176 pub fn memory_limit(&self) -> Option<usize> {
177 self.memory_limit
178 }
179
180 /// Equivalent of `JS_SetMaxStackSize`.
181 pub fn set_stack_size(&mut self, limit: Option<usize>) {
182 self.stack_size = limit;
183 }
184
185 /// Configured stack size limit, if any.
186 pub fn stack_size(&self) -> Option<usize> {
187 self.stack_size
188 }
189
190 /// Equivalent of `JS_RunGC`.
191 pub fn run_gc(&self) -> CollectStats {
192 self.heap.collect()
193 }
194}
195
196/// An execution context: a global object plus the builtins installed on it.
197///
198/// Mirrors the role of `JSContext` in the QuickJS C API.
199pub struct Context<'rt> {
200 runtime: &'rt Runtime,
201 /// The interpreter, created on first use.
202 interp: Option<Interp<'rt>>,
203 /// A loader the host installed, handed to the interpreter when it is built.
204 module_loader: Option<Box<dyn module::ModuleLoader>>,
205 /// The value of the last script, as `qjs` reports it.
206 last_value: Value,
207 /// The name a top-level script is compiled under, which is what `error.stack`
208 /// prints: `<cmdline>` for `-e`, a path for a file, `None` for `<input>`.
209 script_name: Option<String>,
210}
211
212impl<'rt> Context<'rt> {
213 /// Create a context on `runtime`.
214 pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
215 Context {
216 runtime,
217 interp: None,
218 module_loader: None,
219 last_value: Value::Undefined,
220 script_name: None,
221 }
222 }
223
224 /// Install how module specifiers are resolved and read.
225 ///
226 /// Without one, importing is a clear error rather than a silent failure: the engine
227 /// cannot guess whether `./x.js` means a file, and the host is what knows.
228 pub fn set_module_loader(&mut self, loader: Box<dyn module::ModuleLoader>) {
229 // A context that has already run something owns a live interpreter, so the loader
230 // goes to whichever exists.
231 if let Some(interp) = self.interp.as_mut() {
232 interp.module_loader = Some(loader);
233 } else {
234 self.module_loader = Some(loader);
235 }
236 }
237
238 /// Name the scripts this context evaluates, for stack traces.
239 ///
240 /// Mirrors what `qjs` passes to `JS_Eval`: `-e` code is `<cmdline>`, a script file
241 /// is its own path. Without a name, frames print `<input>`, which is what the
242 /// reference uses for code with no file behind it.
243 pub fn set_script_name(&mut self, name: impl Into<String>) {
244 self.script_name = Some(name.into());
245 }
246
247 /// The runtime this context belongs to.
248 pub fn runtime(&self) -> &'rt Runtime {
249 self.runtime
250 }
251
252 /// Everything `print` has written.
253 pub fn output(&self) -> &str {
254 self.interp.as_ref().map_or("", |interp| &interp.output)
255 }
256
257 /// The interpreter, creating it and its realm on first use.
258 fn interp(&mut self) -> &mut Interp<'rt> {
259 let heap: &'rt Heap = &self.runtime.heap;
260 let loader = self.module_loader.take();
261 self.interp.get_or_insert_with(|| {
262 let mut interp = Interp::new(heap);
263 interp.module_loader = loader;
264 interp
265 })
266 }
267
268 /// Evaluate `specifier` as the entry module, the way `qjs -m` does.
269 ///
270 /// The microtask queue is drained afterwards, so a module whose top level launched an
271 /// async task has finished it by the time this returns.
272 pub fn eval_module(&mut self, specifier: &str) -> Result<Value> {
273 let loader = self.module_loader.take();
274 let interp = self.interp();
275 if interp.module_loader.is_none() {
276 interp.module_loader = loader;
277 }
278 match interp.run_main_module(specifier) {
279 Ok(value) => {
280 let drained = interp.drain_jobs();
281 let unhandled = interp.take_unhandled_rejections();
282 if let Err(Signal::Throw(reason)) = drained {
283 let text = interp.describe_exception(&reason);
284 return Err(Error::Exception(text));
285 }
286 if !unhandled.is_empty() {
287 return Err(Error::Exception(unhandled.join("\n")));
288 }
289 self.last_value = value.clone();
290 Ok(value)
291 }
292 Err(Signal::Throw(value)) => {
293 let text = interp.describe_exception(&value);
294 Err(Error::Exception(text))
295 }
296 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
297 }
298 }
299
300 /// Evaluate `source` as a global script and return its completion value.
301 ///
302 /// The value is reported the way `qjs -e` reports it: a string for anything the
303 /// script leaves on the stack, and nothing at all for `undefined`.
304 pub fn eval(&mut self, source: &str) -> Result<Value> {
305 let program =
306 js_parse::parse_script(source).map_err(|error| Error::Syntax(error.to_string()))?;
307 let mut code = js_compile::compile_script(&program)
308 .map_err(|error| Error::Syntax(error.message.clone()))?;
309 // Position information travels with the code, but the file name is the host's
310 // to supply — the parser never sees it.
311 code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
312 let interp = self.interp();
313 match interp.run_script(code) {
314 Ok(value) => {
315 // An unhandled rejection is fatal *after* the script finishes, which is
316 // when the reference decides nothing else will claim it. The script's own
317 // output has already been buffered, so it still prints first.
318 let unhandled = interp.take_unhandled_rejections();
319 if !unhandled.is_empty() {
320 return Err(Error::Exception(unhandled.join("\n")));
321 }
322 self.last_value = value.clone();
323 Ok(value)
324 }
325 Err(Signal::Throw(value)) => {
326 let text = interp.describe_exception(&value);
327 Err(Error::Exception(text))
328 }
329 Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
330 }
331 }
332
333 /// The value of the script that ran last.
334 pub fn last_value(&self) -> &Value {
335 &self.last_value
336 }
337}