Skip to main content

Module native

Module native 

Source
Expand description

Native function interface — how Gleam reaches into Rust.

A registry where Rust functions are registered under MFA names. When the interpreter hits a call to a registered native, it invokes the Rust function directly — same process, no IPC, no serialisation. BIFs (built-in, ship with the VM) and NIFs (registered by the host) use the same mechanism but have different ownership (per D6).

§GC-safe BIF allocation pattern

A NativeFn receives its arguments as copied Term values in &[Term]. Those copies are not GC roots. Any BIF that keeps heap terms from args (lists, tuples, maps, binaries, bigints, floats, closures, references, external pids/refs, or any term read out of those structures) and then calls ProcessContext::ensure_heap_space directly or indirectly through alloc_tuple, alloc_cons, alloc_binary, alloc_bigint, alloc_list, alloc_map, or another allocation helper must root the live terms first. Immediate terms such as atoms, small integers, local pids, and [] do not need rooting solely because they are not heap pointers.

The required sequence is:

  1. Validate/count without allocating.
  2. Save every live heap-term argument (and any boxed term that will be copied into the result) into x-registers with context.process_mut()?.set_x_reg.
  3. Call context.ensure_heap_space(total_words)? or the first allocator that may trigger GC.
  4. Re-read the terms with context.process_mut()?.x_reg(n) before dereferencing or copying them into allocated data, then use pre-reserved allocation helpers when building multiple heap objects from that budget.

For example, stdlib_stubs::collection_bifs::bif_lists_reverse is the canonical implementation: it counts the list, saves the input in x(0), calls ensure_heap_space(count * 2), re-reads x(0), and only then walks the list to build cons cells. Binary data has the same hazard: do not hold a slice borrowed from a heap binary across alloc_binary; either copy bytes into owned Rust memory before allocating, or re-borrow from the re-read rooted Term after GC.

Re-exports§

pub use capability::AllCapabilitiesPolicy;
pub use capability::Capability;
pub use capability::CapabilityPolicy;
pub use capability::CapabilitySet;
pub use capability::LeastAuthorityPolicy;
pub use code_management_bifs::CodeManagementFacility;
pub use distribution_bifs::GlobalNameFacility;
pub use ets_bifs::EtsFacility;
pub use group_leader::GroupLeaderFacility;
pub use io_message::IoMessageFacility;
pub use links::LinkFacility;
pub use process_info_bifs::ProcessInfoFacility;
pub use process_info_bifs::ProcessInfoItem;
pub use process_info_bifs::ProcessInfoStatus;
pub use process_info_bifs::ProcessInfoValue;
pub use process_info_bifs::ProcessMonitorInfo;
pub use registry::RegistryFacility;
pub use select::SelectFacility;
pub use spawn::SpawnFacility;
pub use spawn::SpawnMonitorResult;
pub use spawn::SpawnOptions;
pub use spawn::SpawnOptionsResult;
pub use supervision::SupervisionFacility;
pub use system_info_bifs::SystemInfoFacility;
pub use crate::loader::UnresolvedImport;
pub use crate::loader::UnresolvedImportReport;

Modules§

bifs
Built-in function implementations.
capability
Capability metadata and policies for native imports.
code_management_bifs
Code management native facilities and BIFs.
dictionary_bifs
Process dictionary BIFs.
distribution_bifs
Distribution-related BIFs.
etf_bifs
ETF-related Erlang BIFs.
ets_bifs
Erlang Term Storage BIFs.
exception_bifs
Exception BIFs — erlang:raise/3.
file_bifs
Completion-ring backed file BIFs.
file_meta_bifs
File metadata BIFs.
gate3_bifs
Gate 3 erlang BIFs — element, send, make_ref, spawn/1, type queries, type conversion, process registry, and demonitor/2.
gleam_ffi
Process utility BIFs for gleam_erlang_ffi.
group_leader
Group leader process metadata facility.
inet_bifs
Socket-oriented inet BIFs for FdResource-backed TCP/UDP descriptors.
io_message
Scheduler-backed process message delivery for native I/O protocol BIFs.
links
Link facility trait — how BIFs manage bidirectional process links.
meridian_ffi
Meridian workflow NIFs — Rust functions callable from Gleam workflows.
otp_stubs
OTP module stub BIFs for gleam_otp support.
process_bifs
Process lifecycle BIFs — self, spawn, spawn_link, spawn_monitor, link, unlink, process_flag, monitor, demonitor, exit.
process_info_bifs
Process introspection BIFs — process_info/1,2.
registry
Registry facility trait – how BIFs manage the process name registry.
select
Select facility — mailbox access for selector BIFs.
selector_ffi
Selector system BIFs for gleam_erlang_ffi.
spawn
Spawn facility trait — how BIFs request process creation.
stdlib_stubs
Utility stub BIFs for OTP modules — logger, unicode, sys, gleam_stdlib, maps, lists, and timer.
supervision
Supervision facility trait — how BIFs manage monitors and exit signals.
system_info_bifs
VM introspection BIFs — erlang:system_info/1 and related stubs.
tcp_bifs
Completion-ring backed TCP listener BIFs and socket option BIFs.
udp_bifs
Completion-ring backed UDP socket BIFs.

Structs§

AionTimeoutContinuation
Aion timeout continuation state — carries an opaque state ID and a resume function. No heap Terms are held, so GC tracing is a no-op.
BifRegistryImpl
Built-in function registry populated by the VM before module loading.
DirtyNif
FileIoCompletion
File I/O completion delivered back to a suspended process.
NativeEntry
A registered native function and dispatch metadata.
NifRegistry
Host-provided native implemented function registry.
ProcessContext
RemoteSpawnResult
Successful remote spawn reply, ready to allocate as an external PID.
RootedTerms
Handle to a contiguous run of terms registered as GC roots by ProcessContext::with_rooted.
SuspendRequest
Suspend request from a BIF that wants the process to wait.
TrampolineRequest
Trampoline request from a BIF that needs interpreter re-entry.

Enums§

ExceptionClass
Exception classes that BIFs can request when returning Err(reason).
FileIoContinuation
File I/O continuation data used when a suspended file BIF resumes.
NativeContinuation
Native continuation state for collection BIFs that call closures repeatedly.
NativeRegistrationError
Errors returned while registering native functions.
RemoteSpawnError
Error returned by remote spawn facilities.

Traits§

BifRegistry
Trait used by import resolution to query built-in functions.
FileIoFacility
Completion facility used by file BIFs to submit ring work and retrieve resume completions.
RemoteSpawnFacility
Facility used by node-qualified spawn BIFs to request process creation on a remote node.
SuspensionRegistrar
Scheduler-side registry that makes a host-await suspension’s call identity visible to completion publishers (Scheduler::wake_with_result*) before the requesting native even returns, closing the race in which a host completion arrives while the process is still mid-slice.
TcpIoFacility
Active TCP read-loop submission facility used by socket option BIFs.
WasmAsyncNifFacility
Single-threaded host facility for WASM async native functions.

Functions§

lookup_native
Looks up a native function using import-resolution precedence: BIFs first, then host-registered NIFs.

Type Aliases§

NativeFn
Function pointer type used by BIFs and NIFs.
NativeKey
Registry key for a native module/function/arity tuple.