#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]
pub use js_compile;
pub use js_gc::{CollectStats, Gc, Heap, Trace, Tracer, WeakGc};
pub use js_parse;
mod bignum;
pub mod bigint;
pub mod builtins;
pub mod interp;
pub mod module;
pub mod object;
pub mod regexp;
mod tzif;
pub mod value;
pub use interp::{Interp, Signal};
pub use object::{Callable, JsObject, ObjectKind, Property};
pub use value::{Cell, JsString, Value};
pub const COMPAT_VERSION: &str = "2026-06-04";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
Syntax(String),
Exception(String),
NotImplemented(&'static str),
OutOfMemory,
StackOverflow,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::NotImplemented(what) => write!(f, "not implemented yet: {what}"),
Error::Syntax(what) => write!(f, "{what}"),
Error::Exception(what) => write!(f, "{what}"),
Error::OutOfMemory => write!(f, "out of memory"),
Error::StackOverflow => write!(f, "stack overflow"),
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
pub fn is_module_source(source: &str) -> bool {
let bytes = source.as_bytes();
let mut index = 0;
if bytes.starts_with(b"#!") {
while index < bytes.len() && bytes[index] != b'\n' {
index += 1;
}
}
loop {
while index < bytes.len() && bytes[index].is_ascii_whitespace() {
index += 1;
}
if bytes[index..].starts_with(b"//") {
while index < bytes.len() && bytes[index] != b'\n' {
index += 1;
}
continue;
}
if bytes[index..].starts_with(b"/*") {
index += 2;
while index < bytes.len() && !bytes[index..].starts_with(b"*/") {
index += 1;
}
index = (index + 2).min(bytes.len());
continue;
}
break;
}
let rest = &source[index.min(source.len())..];
let word = |w: &str| -> Option<&str> { rest.strip_prefix(w) };
if let Some(tail) = word("export") {
return !tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$');
}
if let Some(tail) = word("import") {
if tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$') {
return false;
}
let tail = tail.trim_start();
if tail.starts_with('.') || tail.starts_with('(') {
return false;
}
return true;
}
false
}
pub struct Runtime {
heap: Heap,
memory_limit: Option<usize>,
stack_size: Option<usize>,
}
impl Default for Runtime {
fn default() -> Self {
Self::new()
}
}
impl Runtime {
pub fn new() -> Runtime {
Runtime {
heap: Heap::new(),
memory_limit: None,
stack_size: None,
}
}
pub fn heap(&self) -> &Heap {
&self.heap
}
pub fn set_memory_limit(&mut self, limit: Option<usize>) {
self.memory_limit = limit;
}
pub fn memory_limit(&self) -> Option<usize> {
self.memory_limit
}
pub fn set_stack_size(&mut self, limit: Option<usize>) {
self.stack_size = limit;
}
pub fn stack_size(&self) -> Option<usize> {
self.stack_size
}
pub fn run_gc(&self) -> CollectStats {
self.heap.collect()
}
}
pub struct Context<'rt> {
runtime: &'rt Runtime,
interp: Option<Interp<'rt>>,
module_loader: Option<Box<dyn module::ModuleLoader>>,
last_value: Value,
script_name: Option<String>,
}
impl<'rt> Context<'rt> {
pub fn new(runtime: &'rt Runtime) -> Context<'rt> {
Context {
runtime,
interp: None,
module_loader: None,
last_value: Value::Undefined,
script_name: None,
}
}
pub fn set_module_loader(&mut self, loader: Box<dyn module::ModuleLoader>) {
if let Some(interp) = self.interp.as_mut() {
interp.module_loader = Some(loader);
} else {
self.module_loader = Some(loader);
}
}
pub fn set_script_name(&mut self, name: impl Into<String>) {
self.script_name = Some(name.into());
}
pub fn runtime(&self) -> &'rt Runtime {
self.runtime
}
pub fn output(&self) -> &str {
self.interp.as_ref().map_or("", |interp| &interp.output)
}
fn interp(&mut self) -> &mut Interp<'rt> {
let heap: &'rt Heap = &self.runtime.heap;
let loader = self.module_loader.take();
self.interp.get_or_insert_with(|| {
let mut interp = Interp::new(heap);
interp.module_loader = loader;
interp
})
}
pub fn eval_module(&mut self, specifier: &str) -> Result<Value> {
let loader = self.module_loader.take();
let interp = self.interp();
if interp.module_loader.is_none() {
interp.module_loader = loader;
}
match interp.run_main_module(specifier) {
Ok(value) => {
let drained = interp.drain_jobs();
let unhandled = interp.take_unhandled_rejections();
if let Err(Signal::Throw(reason)) = drained {
let text = interp.describe_exception(&reason);
return Err(Error::Exception(text));
}
if !unhandled.is_empty() {
return Err(Error::Exception(unhandled.join("\n")));
}
self.last_value = value.clone();
Ok(value)
}
Err(Signal::Throw(value)) => {
let text = interp.describe_exception(&value);
Err(Error::Exception(text))
}
Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
}
}
pub fn eval(&mut self, source: &str) -> Result<Value> {
let program =
js_parse::parse_script(source).map_err(|error| Error::Syntax(error.to_string()))?;
let mut code = js_compile::compile_script(&program)
.map_err(|error| Error::Syntax(error.message.clone()))?;
code.set_filename(self.script_name.as_deref().unwrap_or("<input>"));
let interp = self.interp();
match interp.run_script(code) {
Ok(value) => {
let unhandled = interp.take_unhandled_rejections();
if !unhandled.is_empty() {
return Err(Error::Exception(unhandled.join("\n")));
}
self.last_value = value.clone();
Ok(value)
}
Err(Signal::Throw(value)) => {
let text = interp.describe_exception(&value);
Err(Error::Exception(text))
}
Err(Signal::OutOfMemory) => Err(Error::OutOfMemory),
}
}
pub fn last_value(&self) -> &Value {
&self.last_value
}
}