pub mod aot;
pub mod aot_native;
pub mod arity;
pub mod ast;
pub mod banner;
pub mod builtins;
pub mod cache;
pub mod capture;
pub mod cli;
pub mod compiler;
pub mod core_arity;
pub mod dap;
pub mod datefmt;
pub mod embed;
pub mod esm;
pub mod host;
pub mod ieee754;
pub mod lexer;
pub mod lsp;
pub mod module;
pub mod numfmt;
pub mod parser;
pub mod proxy;
pub mod regexp;
pub mod regexp_syntax;
pub mod repl;
pub mod rust_ffi;
pub mod slots;
pub mod stdlib;
pub mod tiers;
pub mod tzif;
pub mod tznames;
pub mod utf16;
pub use embed::run_program;
pub use fusevm::Value;
pub const JS_STACK_SIZE: usize = 256 * 1024 * 1024;
pub fn run_on_js_stack(f: fn() -> std::process::ExitCode) -> std::process::ExitCode {
match std::thread::Builder::new()
.name("node-js".into())
.stack_size(JS_STACK_SIZE)
.spawn(f)
{
Ok(h) => h.join().unwrap_or_else(|p| std::panic::resume_unwind(p)),
Err(_) => f(),
}
}
pub fn compile(src: &str) -> Result<compiler::Program, String> {
let stmts = parser::parse(src)?;
with_source(compiler::compile(&stmts, false), src)
}
pub fn compile_completion(src: &str) -> Result<compiler::Program, String> {
compile_completion_strict(src, false)
}
pub fn compile_completion_strict(
src: &str,
caller_strict: bool,
) -> Result<compiler::Program, String> {
compile_completion_in(src, caller_strict, false, false)
}
pub fn compile_completion_in(
src: &str,
caller_strict: bool,
allow_super: bool,
in_with: bool,
) -> Result<compiler::Program, String> {
let stmts = parser::parse_eval(src, allow_super, caller_strict)?;
with_source(
compiler::compile_completion_strict(&stmts, false, caller_strict, in_with),
src,
)
}
pub fn compile_debug(src: &str) -> Result<compiler::Program, String> {
let stmts = parser::parse(src)?;
with_source(compiler::compile(&stmts, true), src)
}
pub fn with_source(
prog: Result<compiler::Program, String>,
src: &str,
) -> Result<compiler::Program, String> {
prog.map(|mut p| {
p.source = Some(src.into());
p
})
}
pub fn load_merged(prog: compiler::Program) -> fusevm::Chunk {
load_merged_from(prog, None)
}
pub fn load_merged_from(
mut prog: compiler::Program,
origin: Option<host::ScriptOrigin>,
) -> fusevm::Chunk {
let (func_off, try_off) = host::with_host(|h| h.program_offsets());
compiler::rebase_program(&mut prog, func_off, try_off);
let compiler::Program {
mut main,
functions,
mut tries,
strict,
source,
} = prog;
let mut funcs: Vec<host::FuncDef> = functions.into_iter().map(|(_, f)| f).collect();
host::with_host(|h| {
let base = match source {
Some(text) => {
let script = h.scripts.len() as u32;
h.scripts.push(text);
for f in funcs.iter_mut().filter(|f| f.span.1 != 0) {
f.script = Some(script);
}
let origin = origin.unwrap_or_else(|| host::ScriptOrigin::named("<anonymous>"));
Some(h.register_source(script, origin))
}
None => None,
};
let mut chunks: Vec<&mut fusevm::Chunk> = vec![&mut main];
chunks.extend(funcs.iter_mut().map(|f| &mut f.chunk));
for t in &mut tries {
chunks.push(&mut t.block);
chunks.extend(t.handler.as_mut().map(|(_, c)| c));
chunks.extend(t.finalizer.as_mut());
}
for c in chunks {
compiler::rebase_positions(c, base);
}
h.load_program(funcs, tries);
if strict {
h.set_current_strict();
}
});
main
}
pub fn run_compiled(prog: compiler::Program) -> Result<Value, String> {
run_compiled_from(prog, None)
}
pub fn run_compiled_from(
prog: compiler::Program,
origin: Option<host::ScriptOrigin>,
) -> Result<Value, String> {
host::run_main(load_merged_from(prog, origin))
}
pub fn exit_code() -> Option<i32> {
host::with_host(|h| h.exit_code)
}
pub fn exit_code_after_failure() -> i32 {
if host::with_host(|h| h.fatal_handler_failed) {
return 7;
}
host::with_host(|h| h.exit_code = Some(1));
let _ = stdlib::process::emit_exit_event(1);
host::with_host(|h| h.exit_code).unwrap_or(1)
}
pub fn eval_in_global_scope(src: &str) -> Result<Value, String> {
eval_in_global_scope_from(src, None)
}
pub fn eval_internal(src: &str) -> Result<Value, String> {
eval_in_global_scope_from(src, Some(host::ScriptOrigin::internal("node:internal")))
}
pub fn eval_in_global_scope_from(
src: &str,
origin: Option<host::ScriptOrigin>,
) -> Result<Value, String> {
let prog = compile_completion(src)?;
let chunk = load_merged_from(prog, origin);
host::run_chunk_in_global_scope(chunk)
}
pub fn compile_or_load(src: &str) -> Result<compiler::Program, String> {
if let Some(prog) = cache::load(src) {
if std::env::var_os("NODE_JS_TRACE").is_some() {
eprintln!(
"node-js: cache HIT ({} ops, {} functions) — skipped lex/parse/lower",
prog.main.ops.len(),
prog.functions.len()
);
}
return Ok(prog);
}
let prog = compile(src)?;
let _ = cache::store(src, &prog);
if std::env::var_os("NODE_JS_TRACE").is_some() {
eprintln!(
"node-js: cache MISS — compiled + stored ({} ops, {} functions)",
prog.main.ops.len(),
prog.functions.len()
);
}
Ok(prog)
}
pub fn eval_str(src: &str) -> Result<Value, String> {
eval_str_from(src, "[eval]")
}
pub fn eval_str_from(src: &str, origin: &str) -> Result<Value, String> {
host::reset_host();
if let Ok(cwd) = std::env::current_dir() {
module::set_entry_dir(cwd);
}
match compile_or_load(src) {
Ok(prog) => {
module::install_entry_globals(origin);
run_compiled_from(prog, Some(host::ScriptOrigin::named(origin)))
}
Err(e) => {
let at = parser::take_error_pos();
if !esm::detect_module(src, &e) {
return Err(syntax_error(src, origin, e, at));
}
let cwd = std::env::current_dir().unwrap_or_default();
let entry = cwd.join("[eval1]").to_string_lossy().into_owned();
let main = esm::main_program(&entry, Some(src.to_string()), false);
run_compiled(compiler::compile(&main, false)?)
}
}
}
pub fn eval_str_print(src: &str, origin: &str) -> Result<(), String> {
host::reset_host();
if let Ok(cwd) = std::env::current_dir() {
module::set_entry_dir(cwd);
}
module::install_entry_globals(origin);
let value = run_compiled_from(
compile_completion(src)?,
Some(host::ScriptOrigin::named(origin)),
)?;
let line = stdlib::util::format(std::slice::from_ref(&value))?;
host::with_host(|h| h.write_out(&format!("{line}\n"), false));
Ok(())
}
pub fn eval_str_captured(src: &str, globals: &[(&str, &str)]) -> (Result<Value, String>, String) {
run_on_fresh_host(src, |h| {
for (name, text) in globals {
let value = h.new_str(*text);
h.set_global(name, value);
}
h.begin_capture();
})
}
pub(crate) fn run_on_fresh_host(
src: &str,
setup: impl FnOnce(&mut host::JsHost),
) -> (Result<Value, String>, String) {
host::reset_host();
if let Ok(cwd) = std::env::current_dir() {
module::set_entry_dir(cwd);
}
host::with_host(setup);
let result = compile_or_load(src).and_then(run_compiled);
let output = host::with_host(|h| h.end_capture());
(result, output)
}
pub fn eval_file(path: &str) -> Result<Value, String> {
let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
host::reset_host();
let dir = std::path::Path::new(path)
.parent()
.filter(|p| !p.as_os_str().is_empty())
.map(std::path::Path::to_path_buf)
.or_else(|| std::env::current_dir().ok())
.unwrap_or_default();
let dir = std::fs::canonicalize(&dir).unwrap_or(dir);
module::set_entry_dir(dir);
let entry = std::fs::canonicalize(path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| stdlib::path::resolve_one(path));
let entry_path = std::path::Path::new(&entry);
let format = esm::file_format_declared(entry_path);
let is_module = match format {
Some(f) => f == esm::Format::Module,
None => match compile_or_load(&src) {
Ok(prog) => {
module::install_entry_globals(&entry);
return run_compiled_from(prog, Some(host::ScriptOrigin::named(&entry)));
}
Err(e) => {
let at = parser::take_error_pos();
if !esm::detect_module(&src, &e) {
return Err(syntax_error(&src, &entry, e, at));
}
true
}
},
};
if is_module {
let main = esm::main_program(&entry, None, true);
return run_compiled(compiler::compile(&main, false)?);
}
module::install_entry_globals(&entry);
let prog = compile_or_load(&src).map_err(|e| {
let at = parser::take_error_pos();
syntax_error(&src, &entry, e, at)
})?;
run_compiled_from(prog, Some(host::ScriptOrigin::named(&entry)))
}
fn syntax_error(src: &str, origin: &str, e: String, at: ast::Pos) -> String {
host::note_syntax_error(src, host::ScriptOrigin::named(origin), &e, at);
e
}
pub fn eval_file_debug(path: &str) -> Result<Value, String> {
let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
let prog = compile_debug(&src)?;
host::reset_host();
host::set_debug_mode(true);
let r = run_compiled(prog);
host::set_debug_mode(false);
r
}