Skip to main content

nodejs/
lib.rs

1//! node-js — JavaScript as a fusevm frontend.
2//!
3//! Pipeline: `lexer` → `parser` builds a JS AST → `compiler` lowers it to a
4//! `fusevm::Chunk` (plus a table of function/arrow sub-chunks and try-block
5//! chunks) → fusevm executes it, calling back into the `host` (through
6//! registered builtins and the strict numeric hook) for every JS-specific
7//! operation. There is no bespoke VM or JIT here — execution and codegen live in
8//! fusevm.
9
10pub mod ast;
11pub mod builtins;
12pub mod cli;
13pub mod compiler;
14pub mod host;
15pub mod lexer;
16pub mod lsp;
17pub mod parser;
18
19pub use fusevm::Value;
20
21/// Compile a source string to a runnable program.
22pub fn compile(src: &str) -> Result<compiler::Program, String> {
23    let stmts = parser::parse(src)?;
24    compiler::compile(&stmts)
25}
26
27/// Rebase a freshly compiled program's func/try ids above those already loaded
28/// on the host, install its functions/tries, and return the (rebased) main
29/// chunk to run.
30pub fn load_merged(mut prog: compiler::Program) -> fusevm::Chunk {
31    let (func_off, try_off) = host::with_host(|h| h.program_offsets());
32    compiler::rebase_program(&mut prog, func_off, try_off);
33    let compiler::Program {
34        main,
35        functions,
36        tries,
37    } = prog;
38    let funcs: Vec<host::FuncDef> = functions.into_iter().map(|(_, f)| f).collect();
39    host::with_host(|h| h.load_program(funcs, tries));
40    main
41}
42
43/// Run an already-compiled program on the current host.
44pub fn run_compiled(prog: compiler::Program) -> Result<Value, String> {
45    host::run_main(load_merged(prog))
46}
47
48/// Parse/compile and run a JS source string on a fresh host.
49pub fn eval_str(src: &str) -> Result<Value, String> {
50    host::reset_host();
51    run_compiled(compile(src)?)
52}
53
54/// Read and run a `.js` file.
55pub fn eval_file(path: &str) -> Result<Value, String> {
56    let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
57    host::reset_host();
58    run_compiled(compile(&src)?)
59}