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