Skip to main content

HostFn

Type Alias HostFn 

Source
pub type HostFn = Box<dyn for<'i> FnMut(&mut Interp<'i>, Value, &[Value]) -> JsResult<Value>>;
Expand description

A host function: a native function plus the state it captured.

NativeFn is a bare fn pointer, so a builtin that needs state (an open-file table, a timer queue, a sink to write to) has nowhere to put it. HostFn boxes the closure instead, and Callable::Host keeps it on the function object.

§Why the closure must not capture a Gc

The collector finds live objects by walking the object graph through Trace. A closure is opaque Rust, so nothing inside it is walked: a Gc<JsObject> captured here would be invisible to the collector and could be freed while the closure still holds it — a use-after-free.

Keep Rust-side state (file descriptors, timer ids, deadlines) in the closure, and keep every JavaScript value somewhere the collector already scans: a property of a real JS object, or a table hanging off Interp. os.setTimeout(fn, ms) stores fn in the interpreter’s timer table for exactly this reason.

Aliased Type§

pub struct HostFn(/* private fields */);