Skip to main content

Module host

Module host 

Source
Expand description

The JavaScript object heap and runtime, reached from fusevm through registered builtins (register_builtin) and the strict numeric hook.

node-js owns no VM and no JIT: the compiler lowers JS to fusevm::Chunk, and every JS-specific operation the VM can’t do natively is a builtin call that lands here. Local variables live in Rc<RefCell> environments chained parent-to-child, so a nested function/closure captures its enclosing scope by reference.

Value representation:

  • immediate: Value::Float (every JS number — one IEEE-754 f64 type), Value::Bool (true/false), Value::Undef (undefined);
  • heap Value::Obj(u32) handles: string, array, object, function, builtin-namespace, and the canonical null — the reference types.

Modules§

binop
Bitwise/shift op tags carried by ops::BINOP (JS ToInt32/ToUint32 rules).
member
DEF_MEMBER member-kind tags.
ops
Builtin ids emitted by the compiler and registered on every VM. The compiler (compiler.rs) and the handler table (builtins.rs::install) must agree on these exactly.
unop
Unary op tags carried by ops::UNARY.
unwind
SIG_UNWIND scope tags: what the emitting site is nested in.

Structs§

ClassVal
A live class constructor. The prototype object (holding instance methods) and the static-side own properties live on the heap; parent is the superclass constructor value (None for a base class).
EnvData
A local-variable environment, shared (by Rc) between a frame and any nested function that captures it.
Frame
One function activation.
FuncDef
A compiled function template: parameter shape + body chunk. Shared by every closure created from the same function/arrow.
FuncVal
A live closure value.
JsHost
The JavaScript runtime.
ParamSlot
One parameter slot. name is the simple bound name; a destructuring pattern is lowered to a synthetic .arg{i} name plus body prologue code.
ProcListener
One process.on/process.once registration. once is not decoration: a once listener must be UNREGISTERED before it runs, so a second emit of the same event does not reach it. Treating once as an alias of on made process.once('e', f); process.emit('e'); process.emit('e') call f twice and leave it in process.listeners('e') — node v26.7.0 calls it once and reports zero listeners afterwards.
PromiseCell
A Promise’s settled state and pending reactions.
PropAttrs
The three ECMAScript own-property attributes. PropAttrs::default() is the all-true shape a plain o.k = v assignment produces, which is why only deviations need storing.
RegExpObj
A RegExp object: the compiled fancy_regex::Regex plus the JS-visible source, flag booleans, and the mutable lastIndex cursor (used by g/y matching). fancy-regex adds lookaround + backreferences on top of the Rust regex fast path, so the JS grammar node-js can accept is a near-superset.
Timer
A scheduled macrotask (setTimeout/setInterval/setImmediate). Ordering is by (delay, seq) — a deterministic virtual clock, never wall time.
TryDef
A compiled try/catch/finally block. Bodies are bare chunks run in the current scope.

Enums§

GenReq
One queued [[AsyncGeneratorQueue]] request. ECMA-262 27.6.3.6 AsyncGeneratorEnqueue records a completion, not just a sent value, which is why .return() and .throw() queue behind pending .next() calls instead of unwinding the body on the spot.
GenStep
Outcome of resuming a generator: a yielded value (not done), or the final completion value (done).
JsObj
A heap object.
MapKey
A Map/Set key under SameValueZero: NaN collapses to one key, -0 and +0 are the same key, primitives compare by value, objects by heap identity.
ObjKind
PromiseReaction
A pending Promise reaction: a user .then (JS handlers + a result promise) or a native continuation (Promise chaining / async await resumption).
PromiseState
Signal
A non-local control signal. Break/Continue carry the optional loop label and are only raised when the target loop lives in an ENCLOSING chunk (a break inside a try block, which the host runs as its own chunk); a same-chunk break is a plain compiler-resolved jump.
SuperRef
The result of resolving super.name: a getter to invoke (accessor property) or a directly-usable value (method / data property).
Task
A queued unit of work: either a JS callback invocation (queueMicrotask, nextTick, timer body) or a native step (Promise reaction / async resume).
ThisState
The [[ThisBindingStatus]] of a function environment (9.1.1.3), as far as it is observable: only a DERIVED class constructor starts with this uninitialized, and only super() binds it.

Constants§

CODE_MARK
The marker plain_coded_error hides a code behind, and synth_error strips.
DOM_MARK
Marks an error string as a DOMException carrying a WHATWG error NAME rather than one of the ECMAScript error classes. WebCrypto and the abort APIs reject with these, and the name (NotSupportedError) is not a class synth_error could otherwise recognise.
ERROR_NAMES
The set of builtin error constructor names forming the error hierarchy.
FIELDS_MARK
Marks the start of the extra string own properties a plain_coded_error_with error carries after its message.
MAX_STRING_LENGTH
V8’s String::kMaxLength on a 64-bit build, in UTF-16 code units — the largest string the engine will materialize.
ORD_MARKER
Prefix of the hidden property-map entry that reserves an accessor’s slot in own-key insertion order (see set_accessor).
WELL_KNOWN_SYMBOLS
Which variant a heap object is, carrying none of its contents.

Functions§

array_index
If k is an array-index property key, return its numeric value. Per ECMAScript, a String property key P is an array index iff ToString(ToUint32(P)) === P and ToUint32(P) !== 2^32 - 1 — i.e. a canonical decimal (no leading zeros, no sign) in the range 0..=2^32-2.
async_gen_enqueue
AsyncGeneratorEnqueue — queue one request against an async function* and hand back the promise its {value, done} record (or rejection) will settle.
async_gen_step
One .next(v) of an async function*.
async_step
One step of a for await loop: return a Promise that settles to a {value, done} record. For a native async iterator this is iter.next() (already a promise of the record). For the sync fallback it pops the next raw value, awaits it, and packages {value: resolved, done:false} (or {done:true} at exhaustion).
await_value
The AWAIT op body (runs inside the async coroutine): suspend, yielding the awaited value; on resume, unwrap the settlement packet (throwing on reject).
bigint_to_f64
Coerce a BigInt to f64 (for Number(bigint) and mixed relational compares); out-of-range magnitudes become ±Infinity, matching Node.
build_class
Build a class constructor value from its parts. The compiler emits (via MKCLASS) the evaluated parent (or undefined) and the constructor closure (or undefined for a default constructor); methods/getters/setters/statics/fields are installed afterward by DEF_MEMBER/DEF_FIELD.
builtin_is_callable
Property read that walks the prototype chain (used by iteration helpers). Whether the builtin named n is CALLABLE. Most are (Array, parseInt, Math.floor); the exceptions are the namespace objects a script can only read properties off (Math, JSON, every require()d core module), which report typeof === "object" and carry no name/length.
call_method
recv.name(args).
call_named
Resolve a bare name and call it (f(args), parseInt(args)).
call_site_text
Rewrite a <subject> is not a function / is not a constructor message with the SOURCE TEXT of the callee at the currently executing op, as V8 does.
canonicalize_own_keys
Reorder an object’s own-property map into OrdinaryOwnPropertyKeys order in place: array-index keys ascending first, then the remaining keys in their existing (insertion) order. A no-op unless at least one index key is present, so the overwhelmingly common all-string-key object keeps its exact order and pays nothing. IndexMap::sort_by is a stable sort.
child_env
A fresh empty scope chained under parent.
clear_call_sites
clear_yield_sites
close_iterator
Call iterator.return() if it has one, as IteratorClose does.
coded_error
A Node coded error raised from the JS layer: Name [ERR_CODE]: message.
construct
Construct an instance with new — creates a fresh object, binds it as this, runs the constructor, and returns the object (unless the constructor returns its own object).
construct_nt
new with an explicit new.target (differs from ctor when a derived class calls super(...) — the target stays the originally-newed class).
current_static_this
The constructor the running builtin static was called on, if it was reached through a subclass rather than directly.
define_field
Register an instance-field initializer thunk on a class (DEF_FIELD).
define_member
Install a method / getter / setter on a class (DEF_MEMBER). kind is a member::* tag; is_static targets the constructor side.
dom_error
A DOMException error string: name is the WHATWG error name.
error_proto
error_proto_of
Error prototype lookup with a borrowed host (used inside a with_host block).
fmt_number
Format a JS number exactly as Number.prototype.toString does for the common range (no exponential-notation threshold handling for very large/small).
func_key
Pool key for the body of user function def_id.
gen_close
Force a generator to completion (used by .return() and abandoned loops): marks it done without running further.
gen_resume
Resume a generator until its next yield or its body returns. Preserves the shared host: the coroutine is taken out so the body re-enters with_host freely, and the volatile context is swapped so the caller’s frames/signal survive the switch.
gen_return
generator.return(v): force the generator to complete, running any pending finally. If it is already done (or never started) it just reports {value:v, done:true} without executing the body.
gen_throw
generator.throw(e): inject a throw at the suspension point, running any pending finally and letting an enclosing try/catch in the body handle it.
gen_yield
yield v — suspend the running generator, handing v to the resumer; returns the value the next gen_resume(x) supplies (a .next(x) argument).
get_async_iterator
Obtain an async iterator for for await. If src has a Symbol.asyncIterator method, use it (its .next() returns a promise of {value, done}); otherwise fall back to the sync iterable, materialized into a JsObj::Iter whose values are awaited one at a time by async_step.
get_prop_chain
init_one_field
Evaluate ONE instance-field initializer thunk and install the result on inst.
instance_of
obj instanceof ctor — walk obj’s prototype chain looking for ctor.prototype.
invalid_arg_type
TypeError [ERR_INVALID_ARG_TYPE]: The "<name>" <kind> must be of type <expected>. Received … — Node’s single most common argument rejection.
invalid_string_length
The error V8 raises for a string operation whose RESULT would exceed MAX_STRING_LENGTH. It is raised from the length arithmetic, before any allocation: 'a'.repeat(2**40) throws promptly on node where node-js used to sit building a 1 TiB String until it was killed.
invoke
Call any callable value.
is_async_generator
Whether v is an async function* object (its .next() yields promises).
is_callable
Whether h.get(v) is any callable kind. A Proxy is callable exactly when its target is (10.5: the [[Call]] slot is installed only for a callable target), so typeof and every is_callable guard agree on one answer.
is_primitive
Whether v is an ECMAScript primitive, i.e. ToPrimitive is the identity on it. undefined, null, booleans, numbers, strings, symbols and bigints qualify; every other heap cell (objects, arrays, functions, Map/Set, native-tagged instances) is an object and must be converted.
is_symbol_key
Whether the internal key k came from a SYMBOL used as a property key (@@sym:<id>, or a well-known @@iterator), as opposed to one of node-js’s hidden slots (@@native, @@bytes, @@ms, @@kind, …). Only the former is an observable JavaScript property.
iter_all
iter_for_each
Drive an iterator object (one with a .next() returning {value, done}) to exhaustion. Step src’s iterator, handing each value to f, and CLOSE the iterator if f exits abruptly (7.4.9 IteratorClose).
iter_take
Fully materialize any iterable into a vector of values. Pull at most n values, then close the iterator — 8.6.2 IteratorBindingInitialization, which is what an array destructuring pattern without a ...rest element performs.
join_stack_pop
Pop the innermost join_stack_push.
join_stack_push
V8’s JoinStackPush: record that v is being joined, or report false if it already is.
key_order_cmp
Compare two own-property keys for OrdinaryOwnPropertyKeys enumeration order: integer-index keys sort ascending-numeric and precede all string keys; two non-index keys compare Equal so a stable sort leaves them in insertion order. (Symbols are stored as @@…/#… string keys and are non-index, so they also fall into the stable-insertion-order tail.)
lookup_accessor
Find a getter/setter accessor for key on recv or up its prototype chain.
lookup_chain
map_key
Convert a Map/Set key value into a MapKey under SameValueZero.
name_call_site
not_a_function_message
V8’s “not a function” wording for a value that was expected to be callable. A number/string/boolean is named WITH its value (number 1 is not a function, string "s" is not a function); every other type is named by type alone (object is not a function, symbol is not a function).
own_enum_entries_deep
The own enumerable (key, value) pairs of v with every enumerable own accessor’s getter invoked — the observable shape Object.values, Object.entries, object spread and JSON.stringify all need. Must be called outside a with_host borrow because a getter re-enters the host.
parked_iters
The number of loop iterators parked on the stack at the op currently executing, for the abrupt-completion close in b_yield.
parse_bigint_str
Parse a string to a BigInt under JS StringToBigInt rules: trimmed, empty → 0n, decimal or 0x/0o/0b prefixed; any junk → None.
plain_coded_error
A Node coded error raised from the native layer: .code is set, but the name is never bracketed, so String(err) is the plain Name: message.
plain_coded_error_with
plain_coded_error plus extra enumerable string own properties, set after code in the order given — new URL('x', 'nope') throws with Object.keys(e) reading ["code","input","base"].
plain_error_text
An error string as a person reads it: TypeError: Invalid URL, with the internal code and field markers of plain_coded_error / plain_coded_error_with removed. An uncaught native error is printed from its string, and printed the wire format (\u{1}code:ERR_INVALID_URL…).
promise_of
A promise for v: v itself if it is already a promise, else a promise resolved with v.
promise_then
Register a user .then reaction (JS handlers + result promise).
protocol_lookup
Walk recv’s own props then its prototype chain for key, returning the stored value (methods, inherited data props). Does NOT invoke accessors. A PROTOCOL lookup — Symbol.toPrimitive, Symbol.hasInstance, toJSON, then and the rest — which the spec performs with [[Get]].
range_error
ref_error
register_call_sites
Record every call site of a freshly built chunk.
register_yield_sites
reject_promise_val
reset_host
Reset the host to a clean slate (fresh module frame).
resolve_promise_val
The Promise “resolve” operation: adopt value’s state if it is a promise, else fulfill with it.
restore_site_tables
Put a snapshot back — what a cache hit does in place of compiling.
run_chunk_in_global_scope
Run chunk in the GLOBAL scope instead of the caller’s.
run_chunk_keyed
Run the chunk filed under key, building it with make only if no VM is already holding it. A recycled VM re-runs the chunk it kept, so a repeated call copies no bytecode at all.
run_chunk_on
Register every node-js builtin + the numeric hook on a VM, then run it.
run_event_loop
Drive the event loop to quiescence.
run_main
Run the top-level program chunk, then drain the event loop (microtasks + timers) until quiescent — matching Node, which keeps the process alive while pending async work remains.
run_user_func
Execute a user function/closure body on a fresh frame.
run_user_func_nt
As run_user_func, but with an explicit new.target (set by new).
run_user_func_of
run_user_func with the function VALUE the call came through, which the arguments object needs for its callee.
set_debug_mode
Enable/disable DAP debug execution (node --dap).
set_error_proto
Register a builtin error prototype (for instanceof Error etc.).
set_inspect_break_length
Set the util.inspect breakLength for the next render.
set_inspect_compact
Set the util.inspect compact option for the next render (0 for false).
set_inspect_custom
Set the util.inspect customInspect option for the next render.
set_inspect_max_array_length
Set the util.inspect maxArrayLength for the next render.
set_inspect_max_depth
Set the util.inspect depth for the next render (restore to 2 after).
set_inspect_show_hidden
Set the util.inspect showHidden option for the next render.
set_inspect_sorted
Set the util.inspect sorted option for the next render.
site_tables
Snapshot both registries.
split_error_fields
Split a plain_coded_error_with message back into the message and its fields. A message with no field mark comes back whole with no fields.
stack_exhausted
Whether the native stack is too close to its floor for one more nested run.
stack_overflow_error
The error V8 raises when the call stack is exhausted. Catchable, and with the RangeError constructor node uses — not a panic!.
string_ctor_value
String(v) — 22.1.1.1. Identical to to_string_value except that a SYMBOL argument is allowed and renders as Symbol(desc) (step 2a).
subscribe_native
Register a native reaction on promise id (schedules immediately if already settled).
super_construct
Run a parent constructor as part of super(...): dispatch on the parent’s kind (class vs plain function vs builtin) using the existing instance. Run the parent constructor against inst.
take_exc_or_error
The JS value of a just-caught error: the live exc (a real thrown value) or a synthesized Error from the internal message.
tdz_error
The error a read of a lexical binding still in its TEMPORAL DEAD ZONE raises. Distinct from ref_error on purpose: node says which of the two happened, and the difference is how a reader tells a misspelled name from a let used above its declaration.
this_before_super_error
The ReferenceError for touching this in a derived constructor before super() — or returning from one without calling it.
to_array_length
ToUint32-validated array length — ECMA-262 10.4.2.2 ArrayCreate step 1 and 10.4.2.4 ArraySetLength step 3.
to_number_value
ToNumber(v) — ECMA-262 7.1.4 — with the object case going through ToPrimitive(v, number) first, so +{ valueOf() { return 7 } } is 7 and +new Date(0) is 0. JsHost::to_number alone cannot do this: it runs under the host borrow and so can never invoke a JS valueOf.
to_primitive
ToPrimitive(v, hint) — ECMA-262 7.1.1. hint is "default", "number" or "string".
to_property_key
ToPropertyKey(v) — ECMA-262 7.1.19. A symbol keeps its stable internal key; anything else is ToPrimitive(v, string) then ToString, so obj[{ toString() { return 'k' } }] really reads obj.k.
to_string_value
ToString(v) with ToPrimitive method dispatch: an object is converted with the string hint (so a user toString — or valueOf, if toString is absent or returns an object — is invoked), then rendered by str_of. Returns a heap string value.
try_key
Pool key for one part of try statement try_id: 0 = the block, 1 = the handler, 2 = the finalizer.
type_error
user_iterator_fn
If v has an own/inherited Symbol.iterator method (internal key @@iterator), return it. Arrays/strings use the native fast path instead.
with_host
Run f with mutable access to the thread-local host.
with_static_this
Run f with recv recorded as the receiver of a builtin static call.

Type Aliases§

Accessor
An accessor property: (getter, setter), either optional.
Env
IoTask
A unit of I/O work handed from a background I/O thread to the main-thread event loop. It is a boxed closure so host.rs stays agnostic of net/http: the I/O thread captures only plain Send data (bytes, ids, TcpStreams) and the closure runs the JS-touching dispatch on the main thread (where the thread-local host lives). I/O threads NEVER touch the host directly.
SiteTables
Every call site and yield site registered so far, as the cache stores them: (op_hash, ip) keys with their recorded value.
VarMap
The map behind a scope. Hashing these with FxHash instead of the default was measured SLOWER, not faster — fib went 652ms to 1086ms and a 5M-iteration counting loop 1894ms to 2381ms on the same machine — so the default stands.