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