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 aot;
11pub mod aot_native;
12pub mod arity;
13pub mod ast;
14pub mod banner;
15pub mod builtins;
16pub mod cache;
17pub mod capture;
18pub mod cli;
19pub mod compiler;
20pub mod dap;
21pub mod host;
22pub mod lexer;
23pub mod lsp;
24pub mod module;
25pub mod parser;
26pub mod proxy;
27pub mod regexp;
28pub mod repl;
29pub mod rust_ffi;
30pub mod slots;
31pub mod stdlib;
32pub mod tiers;
33pub mod utf16;
34
35pub use fusevm::Value;
36
37/// Stack reserved for the thread JS runs on ([`run_on_js_stack`]).
38///
39/// A JS call is a Rust recursion (`host::run_user_func_nt` → `run_chunk_on` →
40/// a fresh `fusevm::VM` on the stack), so recursion depth is bounded by the
41/// native stack rather than by a frame counter. On the OS default 8 MiB this
42/// bought only 83 frames in a debug build — measured, `node -e 'function
43/// f(n){if(n<=0)return 0;return 1+f(n-1)} f(84)'` aborted — where node v26.7.0
44/// reaches 9901. Reserving 256 MiB is virtual address space, faulted in only as
45/// deep recursion actually uses it, and `host::stack_exhausted` still turns the
46/// far end into a catchable `RangeError` rather than an abort. The reservation
47/// is capped rather than sized to match node's depth exactly so that a runaway
48/// recursion's peak RSS stays bounded; the resulting depth is documented in
49/// BUGS.md.
50pub const JS_STACK_SIZE: usize = 256 * 1024 * 1024;
51
52/// Run `f` on a thread with [`JS_STACK_SIZE`] of stack, falling back to the
53/// calling thread if the reservation is refused (a `ulimit`ed or memory-capped
54/// environment must still run programs, just at a lower recursion ceiling —
55/// `host::stack_exhausted` measures whatever stack it ends up on).
56///
57/// Takes a plain `fn` pointer, not a closure: `Builder::spawn` consumes what it
58/// is given and does not hand it back on failure, and a `fn` is `Copy`, so the
59/// fallback can still call the same entry point.
60pub fn run_on_js_stack(f: fn() -> std::process::ExitCode) -> std::process::ExitCode {
61    match std::thread::Builder::new()
62        .name("node-js".into())
63        .stack_size(JS_STACK_SIZE)
64        .spawn(f)
65    {
66        // A panic on the JS thread has already written its message to stderr;
67        // re-raising keeps the process dying exactly as it would have without
68        // the hop, rather than turning an abort into a quiet exit code.
69        Ok(h) => h.join().unwrap_or_else(|p| std::panic::resume_unwind(p)),
70        Err(_) => f(),
71    }
72}
73
74/// Compile a source string to a runnable program.
75pub fn compile(src: &str) -> Result<compiler::Program, String> {
76    let stmts = parser::parse(src)?;
77    with_source(compiler::compile(&stmts, false), src)
78}
79
80/// Compile leaving the final top-level expression as the program's completion
81/// value (for `vm.runInThisContext` / `eval`).
82pub fn compile_completion(src: &str) -> Result<compiler::Program, String> {
83    compile_completion_strict(src, false)
84}
85
86/// As [`compile_completion`], with the caller's strictness folded in — what a
87/// direct `eval` inherits.
88pub fn compile_completion_strict(
89    src: &str,
90    caller_strict: bool,
91) -> Result<compiler::Program, String> {
92    let stmts = parser::parse(src)?;
93    with_source(
94        compiler::compile_completion_strict(&stmts, false, caller_strict),
95        src,
96    )
97}
98
99/// Compile with per-statement DAP line markers enabled (`node --dap`).
100pub fn compile_debug(src: &str) -> Result<compiler::Program, String> {
101    let stmts = parser::parse(src)?;
102    with_source(compiler::compile(&stmts, true), src)
103}
104
105/// Attach the text a program was parsed from, which its functions' spans
106/// index (`Function.prototype.toString`).
107pub fn with_source(
108    prog: Result<compiler::Program, String>,
109    src: &str,
110) -> Result<compiler::Program, String> {
111    prog.map(|mut p| {
112        p.source = Some(src.into());
113        p
114    })
115}
116
117/// Rebase a freshly compiled program's func/try ids above those already loaded
118/// on the host, install its functions/tries, and return the (rebased) main
119/// chunk to run.
120pub fn load_merged(mut prog: compiler::Program) -> fusevm::Chunk {
121    let (func_off, try_off) = host::with_host(|h| h.program_offsets());
122    compiler::rebase_program(&mut prog, func_off, try_off);
123    let compiler::Program {
124        main,
125        functions,
126        tries,
127        strict,
128        source,
129    } = prog;
130    let funcs: Vec<host::FuncDef> = functions.into_iter().map(|(_, f)| f).collect();
131    host::with_host(|h| {
132        // Each span-carrying function learns which script its span indexes.
133        let mut funcs = funcs;
134        if let Some(text) = source {
135            let script = h.scripts.len() as u32;
136            h.scripts.push(text);
137            for f in funcs.iter_mut().filter(|f| f.span.1 != 0) {
138                f.script = Some(script);
139            }
140        }
141        h.load_program(funcs, tries);
142        // A strict top level marks the frame it is about to run on, so a
143        // refused write throws there the way it does inside a strict function.
144        // A function's strictness rides in its `FuncDef`; the top level had
145        // nowhere to put it, so the module frame stayed sloppy.
146        if strict {
147            h.set_current_strict();
148        }
149    });
150    main
151}
152
153/// Run an already-compiled program on the current host.
154pub fn run_compiled(prog: compiler::Program) -> Result<Value, String> {
155    host::run_main(load_merged(prog))
156}
157
158/// `process.exitCode` as the program left it, or `None` if it was never set.
159///
160/// The binary reads this after a run completes to pick its own status — Node
161/// exits with `process.exitCode` when the loop drains normally, so a script
162/// that signals failure that way (rather than by throwing or calling
163/// `process.exit`) is reported as a failure rather than as success.
164pub fn exit_code() -> Option<i32> {
165    host::with_host(|h| h.exit_code)
166}
167
168/// Run the `exit` event for a program that died on an uncaught exception, and
169/// report the status to leave with.
170///
171/// Node fires `exit` on this path too, and an uncaught exception FORCES the
172/// code to 1 — overriding any `process.exitCode` the script had already set —
173/// while a code the handler itself assigns still wins. Verified on node
174/// v26.7.0: `process.exitCode = 3; process.on('exit', c => console.log(c));
175/// throw new Error('z')` prints `1` and exits 1, and
176/// `process.on('exit', () => { process.exitCode = 9 }); throw new Error('z')`
177/// exits 9.
178pub fn exit_code_after_failure() -> i32 {
179    host::with_host(|h| h.exit_code = Some(1));
180    let _ = stdlib::process::emit_exit_event(1);
181    host::with_host(|h| h.exit_code).unwrap_or(1)
182}
183
184/// Compile `src` and run it on the LIVE host — no reset, no event-loop drain —
185/// in the GLOBAL scope, returning its completion value.
186///
187/// This is the ONE runtime-source evaluator on this frontend. Every construct
188/// that turns a source string into a running program funnels through here:
189/// the CommonJS module wrapper (`module::compile_wrapper`), `vm.runInThisContext`
190/// / `vm.Script` / `vm.compileFunction`, `new Function` / `Function(...)`
191/// (`builtins::dynamic_function`), and the internal JS factories
192/// (`util.promisify`, `stream/promises`, `stream/consumers`,
193/// `performance.timerify`, `module.builtinModules`). Each of those used to carry
194/// its own `compile_completion` → `load_merged` → `run_chunk_on` triple — seven
195/// copies of the same three lines — and every one of them inherited the same
196/// bug: `run_chunk_on` executes on whatever frame is CURRENT, so nested source
197/// saw the calling function's locals. Measured against node v26.7.0,
198/// `function outer(){ let secret = 1; return require('./m.js'); }` with `m.js` =
199/// `module.exports = typeof secret` is `"undefined"` there and was `"number"`
200/// here; `vm.runInThisContext('typeof loc')` likewise. `run_chunk_in_global_scope`
201/// fixes it once, for all of them.
202pub fn eval_in_global_scope(src: &str) -> Result<Value, String> {
203    let prog = compile_completion(src)?;
204    let chunk = load_merged(prog);
205    host::run_chunk_in_global_scope(chunk)
206}
207
208/// Transparent bytecode cache: return the cached compiled `Program` for `src`
209/// (skipping lex/parse/lower entirely), else compile it, store it in the
210/// `~/.node-js/scripts.rkyv` shard, and return it. This runs on EVERY ordinary
211/// `node foo.js` / `node -e` invocation, so scripts are rkyv-cached automatically
212/// — not only under `--build`. Set `NODE_JS_TRACE=1` to log hit/miss to stderr
213/// (silent otherwise; normal runs print nothing).
214pub fn compile_or_load(src: &str) -> Result<compiler::Program, String> {
215    if let Some(prog) = cache::load(src) {
216        if std::env::var_os("NODE_JS_TRACE").is_some() {
217            eprintln!(
218                "node-js: cache HIT ({} ops, {} functions) — skipped lex/parse/lower",
219                prog.main.ops.len(),
220                prog.functions.len()
221            );
222        }
223        return Ok(prog);
224    }
225    let prog = compile(src)?;
226    let _ = cache::store(src, &prog);
227    if std::env::var_os("NODE_JS_TRACE").is_some() {
228        eprintln!(
229            "node-js: cache MISS — compiled + stored ({} ops, {} functions)",
230            prog.main.ops.len(),
231            prog.functions.len()
232        );
233    }
234    Ok(prog)
235}
236
237/// Parse/load, compile, and run a JS source string on a fresh host (rkyv-cached).
238///
239/// This is the `node -e` entry point; [`eval_str_from`] names the other
240/// source-on-the-command-line one, which reports a different `__filename`.
241pub fn eval_str(src: &str) -> Result<Value, String> {
242    eval_str_from(src, "[eval]")
243}
244
245/// [`eval_str`] with the entry-point NAME node reports for it: `[eval]` for
246/// `-e`, `[stdin]` for source piped in. The two are observably different —
247/// `__filename`, `module.id` and a stack frame's file all carry it.
248pub fn eval_str_from(src: &str, origin: &str) -> Result<Value, String> {
249    host::reset_host();
250    // `node -e` resolves top-level `require` from the current working directory.
251    if let Ok(cwd) = std::env::current_dir() {
252        module::set_entry_dir(cwd);
253    }
254    module::install_entry_globals(origin);
255    run_compiled(compile_or_load(src)?)
256}
257
258/// `node -p <src>`: evaluate as `-e` does, then write the program's COMPLETION
259/// value through the `console.log` formatter, exactly as Node's
260/// `--print` does (`node -p '[1,2]'` prints `[ 1, 2 ]`, `node -p '"s"'` prints
261/// the bare `s`). Side effects still happen, so `node -p 'console.log("x")'`
262/// prints `x` and then `undefined`.
263///
264/// Deliberately compiled with [`compile_completion`] rather than through the
265/// source-keyed rkyv cache: the cache is keyed by source TEXT alone, so a
266/// `-p`-shaped chunk and an `-e`-shaped chunk for the same string would alias.
267pub fn eval_str_print(src: &str, origin: &str) -> Result<(), String> {
268    host::reset_host();
269    if let Ok(cwd) = std::env::current_dir() {
270        module::set_entry_dir(cwd);
271    }
272    module::install_entry_globals(origin);
273    let value = run_compiled(compile_completion(src)?)?;
274    // One argument means no directive processing at all (node returns a lone
275    // argument as-is), so this call has nothing that can throw.
276    let line = stdlib::util::format(std::slice::from_ref(&value))?;
277    host::with_host(|h| h.write_out(&format!("{line}\n"), false));
278    Ok(())
279}
280
281/// Run a JS source string on a fresh host with `globals` bound and the
282/// program's output captured in-process, returning the program's outcome
283/// alongside everything it wrote.
284///
285/// This is the entry point for an embedder rather than for the `node` binary,
286/// and it exists because [`eval_str`] cannot serve one: it resets the host
287/// first, which wipes any global installed beforehand, and it lets
288/// `console.log` reach the real stdout, which corrupts a host that owns the
289/// terminal. Both are fixed here — the globals are seeded *after* the reset,
290/// and every write the program makes lands in the returned string.
291///
292/// The outcome and the output are returned separately (rather than the output
293/// only on success) because a program that prints and *then* throws produced
294/// both, and an embedder generally wants to show both.
295///
296/// Globals are given as text and interned as real JS strings here. They are
297/// deliberately *not* `Value`: strings live on this host's heap as
298/// `JsObj::Str`, so a `Value::Str` a caller builds is at best coerced and at
299/// worst method-less. Handing the host text and letting it intern removes that
300/// trap, and matches the sibling runtimes' embedder entry points.
301///
302/// ```no_run
303/// let (result, out) = nodejs::eval_str_captured("console.log(stdin.toUpperCase())", &[("stdin", "hi")]);
304/// assert!(result.is_ok());
305/// assert_eq!(out, "HI\n");
306/// ```
307pub fn eval_str_captured(src: &str, globals: &[(&str, &str)]) -> (Result<Value, String>, String) {
308    host::reset_host();
309    if let Ok(cwd) = std::env::current_dir() {
310        module::set_entry_dir(cwd);
311    }
312    host::with_host(|h| {
313        for (name, text) in globals {
314            let value = h.new_str(*text);
315            h.set_global(name, value);
316        }
317        h.begin_capture();
318    });
319    let result = compile_or_load(src).and_then(run_compiled);
320    let output = host::with_host(|h| h.end_capture());
321    (result, output)
322}
323
324/// Read and run a `.js` file (transparently rkyv-cached — see `compile_or_load`).
325pub fn eval_file(path: &str) -> Result<Value, String> {
326    let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
327    host::reset_host();
328    // Top-level `require` in `node app.js` resolves from the entry file's dir.
329    let dir = std::path::Path::new(path)
330        .parent()
331        .filter(|p| !p.as_os_str().is_empty())
332        .map(std::path::Path::to_path_buf)
333        .or_else(|| std::env::current_dir().ok())
334        .unwrap_or_default();
335    let dir = std::fs::canonicalize(&dir).unwrap_or(dir);
336    module::set_entry_dir(dir);
337    // `__filename` is the entry script's REALPATH, not the path that was typed:
338    // Node's loader calls `toRealPath` on the main module, so a script reached
339    // through a symlinked directory reports the link TARGET. (`process.argv[1]`
340    // is the opposite — it keeps the spelling; both measured on node v26.7.0.)
341    let entry = std::fs::canonicalize(path)
342        .map(|p| p.to_string_lossy().into_owned())
343        .unwrap_or_else(|_| stdlib::path::resolve_one(path));
344    module::install_entry_globals(&entry);
345    run_compiled(compile_or_load(&src)?)
346}
347
348/// Read and run a `.js` file under the DAP debugger.
349pub fn eval_file_debug(path: &str) -> Result<Value, String> {
350    let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
351    let prog = compile_debug(&src)?;
352    host::reset_host();
353    host::set_debug_mode(true);
354    let r = run_compiled(prog);
355    host::set_debug_mode(false);
356    r
357}