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 compiler::compile(&stmts, false)
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 compiler::compile_completion_strict(&stmts, false, caller_strict)
94}
95
96/// Compile with per-statement DAP line markers enabled (`node --dap`).
97pub fn compile_debug(src: &str) -> Result<compiler::Program, String> {
98 let stmts = parser::parse(src)?;
99 compiler::compile(&stmts, true)
100}
101
102/// Rebase a freshly compiled program's func/try ids above those already loaded
103/// on the host, install its functions/tries, and return the (rebased) main
104/// chunk to run.
105pub fn load_merged(mut prog: compiler::Program) -> fusevm::Chunk {
106 let (func_off, try_off) = host::with_host(|h| h.program_offsets());
107 compiler::rebase_program(&mut prog, func_off, try_off);
108 let compiler::Program {
109 main,
110 functions,
111 tries,
112 strict,
113 } = prog;
114 let funcs: Vec<host::FuncDef> = functions.into_iter().map(|(_, f)| f).collect();
115 host::with_host(|h| {
116 h.load_program(funcs, tries);
117 // A strict top level marks the frame it is about to run on, so a
118 // refused write throws there the way it does inside a strict function.
119 // A function's strictness rides in its `FuncDef`; the top level had
120 // nowhere to put it, so the module frame stayed sloppy.
121 if strict {
122 h.set_current_strict();
123 }
124 });
125 main
126}
127
128/// Run an already-compiled program on the current host.
129pub fn run_compiled(prog: compiler::Program) -> Result<Value, String> {
130 host::run_main(load_merged(prog))
131}
132
133/// `process.exitCode` as the program left it, or `None` if it was never set.
134///
135/// The binary reads this after a run completes to pick its own status — Node
136/// exits with `process.exitCode` when the loop drains normally, so a script
137/// that signals failure that way (rather than by throwing or calling
138/// `process.exit`) is reported as a failure rather than as success.
139pub fn exit_code() -> Option<i32> {
140 host::with_host(|h| h.exit_code)
141}
142
143/// Run the `exit` event for a program that died on an uncaught exception, and
144/// report the status to leave with.
145///
146/// Node fires `exit` on this path too, and an uncaught exception FORCES the
147/// code to 1 — overriding any `process.exitCode` the script had already set —
148/// while a code the handler itself assigns still wins. Verified on node
149/// v26.7.0: `process.exitCode = 3; process.on('exit', c => console.log(c));
150/// throw new Error('z')` prints `1` and exits 1, and
151/// `process.on('exit', () => { process.exitCode = 9 }); throw new Error('z')`
152/// exits 9.
153pub fn exit_code_after_failure() -> i32 {
154 host::with_host(|h| h.exit_code = Some(1));
155 let _ = stdlib::process::emit_exit_event(1);
156 host::with_host(|h| h.exit_code).unwrap_or(1)
157}
158
159/// Compile `src` and run it on the LIVE host — no reset, no event-loop drain —
160/// in the GLOBAL scope, returning its completion value.
161///
162/// This is the ONE runtime-source evaluator on this frontend. Every construct
163/// that turns a source string into a running program funnels through here:
164/// the CommonJS module wrapper (`module::compile_wrapper`), `vm.runInThisContext`
165/// / `vm.Script` / `vm.compileFunction`, `new Function` / `Function(...)`
166/// (`builtins::dynamic_function`), and the internal JS factories
167/// (`util.promisify`, `stream/promises`, `stream/consumers`,
168/// `performance.timerify`, `module.builtinModules`). Each of those used to carry
169/// its own `compile_completion` → `load_merged` → `run_chunk_on` triple — seven
170/// copies of the same three lines — and every one of them inherited the same
171/// bug: `run_chunk_on` executes on whatever frame is CURRENT, so nested source
172/// saw the calling function's locals. Measured against node v26.7.0,
173/// `function outer(){ let secret = 1; return require('./m.js'); }` with `m.js` =
174/// `module.exports = typeof secret` is `"undefined"` there and was `"number"`
175/// here; `vm.runInThisContext('typeof loc')` likewise. `run_chunk_in_global_scope`
176/// fixes it once, for all of them.
177pub fn eval_in_global_scope(src: &str) -> Result<Value, String> {
178 let prog = compile_completion(src)?;
179 let chunk = load_merged(prog);
180 host::run_chunk_in_global_scope(chunk)
181}
182
183/// Transparent bytecode cache: return the cached compiled `Program` for `src`
184/// (skipping lex/parse/lower entirely), else compile it, store it in the
185/// `~/.node-js/scripts.rkyv` shard, and return it. This runs on EVERY ordinary
186/// `node foo.js` / `node -e` invocation, so scripts are rkyv-cached automatically
187/// — not only under `--build`. Set `NODE_JS_TRACE=1` to log hit/miss to stderr
188/// (silent otherwise; normal runs print nothing).
189pub fn compile_or_load(src: &str) -> Result<compiler::Program, String> {
190 if let Some(prog) = cache::load(src) {
191 if std::env::var_os("NODE_JS_TRACE").is_some() {
192 eprintln!(
193 "node-js: cache HIT ({} ops, {} functions) — skipped lex/parse/lower",
194 prog.main.ops.len(),
195 prog.functions.len()
196 );
197 }
198 return Ok(prog);
199 }
200 let prog = compile(src)?;
201 let _ = cache::store(src, &prog);
202 if std::env::var_os("NODE_JS_TRACE").is_some() {
203 eprintln!(
204 "node-js: cache MISS — compiled + stored ({} ops, {} functions)",
205 prog.main.ops.len(),
206 prog.functions.len()
207 );
208 }
209 Ok(prog)
210}
211
212/// Parse/load, compile, and run a JS source string on a fresh host (rkyv-cached).
213///
214/// This is the `node -e` entry point; [`eval_str_from`] names the other
215/// source-on-the-command-line one, which reports a different `__filename`.
216pub fn eval_str(src: &str) -> Result<Value, String> {
217 eval_str_from(src, "[eval]")
218}
219
220/// [`eval_str`] with the entry-point NAME node reports for it: `[eval]` for
221/// `-e`, `[stdin]` for source piped in. The two are observably different —
222/// `__filename`, `module.id` and a stack frame's file all carry it.
223pub fn eval_str_from(src: &str, origin: &str) -> Result<Value, String> {
224 host::reset_host();
225 // `node -e` resolves top-level `require` from the current working directory.
226 if let Ok(cwd) = std::env::current_dir() {
227 module::set_entry_dir(cwd);
228 }
229 module::install_entry_globals(origin);
230 run_compiled(compile_or_load(src)?)
231}
232
233/// `node -p <src>`: evaluate as `-e` does, then write the program's COMPLETION
234/// value through the `console.log` formatter, exactly as Node's
235/// `--print` does (`node -p '[1,2]'` prints `[ 1, 2 ]`, `node -p '"s"'` prints
236/// the bare `s`). Side effects still happen, so `node -p 'console.log("x")'`
237/// prints `x` and then `undefined`.
238///
239/// Deliberately compiled with [`compile_completion`] rather than through the
240/// source-keyed rkyv cache: the cache is keyed by source TEXT alone, so a
241/// `-p`-shaped chunk and an `-e`-shaped chunk for the same string would alias.
242pub fn eval_str_print(src: &str, origin: &str) -> Result<(), String> {
243 host::reset_host();
244 if let Ok(cwd) = std::env::current_dir() {
245 module::set_entry_dir(cwd);
246 }
247 module::install_entry_globals(origin);
248 let value = run_compiled(compile_completion(src)?)?;
249 // One argument means no directive processing at all (node returns a lone
250 // argument as-is), so this call has nothing that can throw.
251 let line = stdlib::util::format(std::slice::from_ref(&value))?;
252 host::with_host(|h| h.write_out(&format!("{line}\n"), false));
253 Ok(())
254}
255
256/// Run a JS source string on a fresh host with `globals` bound and the
257/// program's output captured in-process, returning the program's outcome
258/// alongside everything it wrote.
259///
260/// This is the entry point for an embedder rather than for the `node` binary,
261/// and it exists because [`eval_str`] cannot serve one: it resets the host
262/// first, which wipes any global installed beforehand, and it lets
263/// `console.log` reach the real stdout, which corrupts a host that owns the
264/// terminal. Both are fixed here — the globals are seeded *after* the reset,
265/// and every write the program makes lands in the returned string.
266///
267/// The outcome and the output are returned separately (rather than the output
268/// only on success) because a program that prints and *then* throws produced
269/// both, and an embedder generally wants to show both.
270///
271/// Globals are given as text and interned as real JS strings here. They are
272/// deliberately *not* `Value`: strings live on this host's heap as
273/// `JsObj::Str`, so a `Value::Str` a caller builds is at best coerced and at
274/// worst method-less. Handing the host text and letting it intern removes that
275/// trap, and matches the sibling runtimes' embedder entry points.
276///
277/// ```no_run
278/// let (result, out) = nodejs::eval_str_captured("console.log(stdin.toUpperCase())", &[("stdin", "hi")]);
279/// assert!(result.is_ok());
280/// assert_eq!(out, "HI\n");
281/// ```
282pub fn eval_str_captured(src: &str, globals: &[(&str, &str)]) -> (Result<Value, String>, String) {
283 host::reset_host();
284 if let Ok(cwd) = std::env::current_dir() {
285 module::set_entry_dir(cwd);
286 }
287 host::with_host(|h| {
288 for (name, text) in globals {
289 let value = h.new_str(*text);
290 h.set_global(name, value);
291 }
292 h.begin_capture();
293 });
294 let result = compile_or_load(src).and_then(run_compiled);
295 let output = host::with_host(|h| h.end_capture());
296 (result, output)
297}
298
299/// Read and run a `.js` file (transparently rkyv-cached — see `compile_or_load`).
300pub fn eval_file(path: &str) -> Result<Value, String> {
301 let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
302 host::reset_host();
303 // Top-level `require` in `node app.js` resolves from the entry file's dir.
304 let dir = std::path::Path::new(path)
305 .parent()
306 .filter(|p| !p.as_os_str().is_empty())
307 .map(std::path::Path::to_path_buf)
308 .or_else(|| std::env::current_dir().ok())
309 .unwrap_or_default();
310 let dir = std::fs::canonicalize(&dir).unwrap_or(dir);
311 module::set_entry_dir(dir);
312 // `__filename` is the entry script's REALPATH, not the path that was typed:
313 // Node's loader calls `toRealPath` on the main module, so a script reached
314 // through a symlinked directory reports the link TARGET. (`process.argv[1]`
315 // is the opposite — it keeps the spelling; both measured on node v26.7.0.)
316 let entry = std::fs::canonicalize(path)
317 .map(|p| p.to_string_lossy().into_owned())
318 .unwrap_or_else(|_| stdlib::path::resolve_one(path));
319 module::install_entry_globals(&entry);
320 run_compiled(compile_or_load(&src)?)
321}
322
323/// Read and run a `.js` file under the DAP debugger.
324pub fn eval_file_debug(path: &str) -> Result<Value, String> {
325 let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
326 let prog = compile_debug(&src)?;
327 host::reset_host();
328 host::set_debug_mode(true);
329 let r = run_compiled(prog);
330 host::set_debug_mode(false);
331 r
332}