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