Compiler and codegen
What the front doors run: the rustc invocation, the JSON reader for Cargo's machine-readable output, and the ccall expressions generated from the FFI manifest.
Compiler (src/build/compiler.jl)
RustCall.RustCompiler — Type
RustCompilerConfiguration for the Rust compiler.
Fields
target_triple::String: Target triple for compilationoptimization_level::Int: Optimization level 0-3emit_debug_info::Bool: Whether to emit debug infodebug_mode::Bool: Enable debug mode (keep intermediate files, verbose output)debug_dir::Union{String, Nothing}: Directory to keep debug files (default: nothing = use temp dir)
RustCall.RustCompiler — Method
RustCompiler(; kwargs...)Create a RustCompiler with the specified settings.
Keyword Arguments
target_triple::String: Target triple for compilation (default: auto-detect)optimization_level::Int: Optimization level 0-3 (default: 2)emit_debug_info::Bool: Whether to emit debug info (default: false)debug_mode::Bool: Enable debug mode (default: false)debug_dir::Union{String, Nothing}: Directory to keep debug files (default: nothing)
RustCall._unique_source_name — Method
_unique_source_name(code::String, compiler::RustCompiler) -> StringGenerate a unique base filename for a compilation unit. When debug_dir is set, uses a hash of the code to avoid overwriting files from different compilations. Otherwise returns a fixed name since each compilation uses its own temp directory.
RustCall.check_rustc_available — Method
check_rustc_available() -> BoolCheck if rustc is available using RustToolChain.jl.
RustCall.compile_rust_to_shared_lib — Method
compile_rust_to_shared_lib(code::String; compiler=get_default_compiler()) -> StringCompile Rust code to a shared library and return the path.
Arguments
code::String: Rust source code
Keyword Arguments
compiler::RustCompiler: Compiler configuration (default: default compiler)
Returns
- Path to the generated shared library
Throws
CompilationErrorif compilation fails
RustCall.get_default_compiler — Method
get_default_compiler() -> RustCompilerGet or create the default RustCompiler instance.
RustCall.get_default_target — Method
get_default_target() -> StringGet the default target triple for the current platform.
RustCall.get_library_extension — Method
get_library_extension() -> StringGet the shared library extension for the current platform.
RustCall.get_rustc_version — Method
get_rustc_version() -> StringGet the version of rustc using RustToolChain.jl.
RustCall.rustc_command — Method
rustc_command(args) -> CmdThe rustc RustToolChain.jl resolves, run with args appended — its whole command, not just the executable. With the artifact toolchain RustToolChain returns $`rustc --sysroot <prefix>`$ (Unix) or a setenv(...) command (Windows); keeping only exec[1] dropped both, so a build or probe ran a compiler with no standard library while the rustc --print cfg probe, which used the full command, saw a different one (#460). Every place RustCall runs rustc directly builds its command here, so the compile, the generic-group check and the cfg probe cannot disagree.
base is for tests; it defaults to rustc().
RustCall.set_default_compiler — Method
set_default_compiler(compiler::RustCompiler)Set the default RustCompiler instance.
RustCall.wrap_rust_code — Method
wrap_rust_code(code::String) -> StringWrap Rust code to ensure it has the necessary FFI exports. This adds common imports and ensures extern "C" functions are properly exposed.
Reading Cargo's JSON (src/build/json.jl)
cargo metadata and --message-format=json output, read as data.
RustCall.JSONParseError — Type
JSONParseErrorRaised when parse_json is handed text that is not valid JSON, with the byte position where reading stopped.
RustCall.parse_json — Method
parse_json(text::AbstractString) -> AnyParse one JSON document into Dict{String, Any} / Vector{Any} / String / Float64 / Int / Bool / nothing.
Used for Cargo's machine-readable output: cargo metadata and the build-script messages of --message-format=json (pyo3.jl).
Code generation (src/ffi/codegen.jl)
RustCall.CALLBACK_SLOTS — Constant
CALLBACK_SLOTSHow many callback arguments one #[julia] function or method may take: one plain slot function exists per position, and a wrapper with more callback parameters than this is refused at generation.
RustCall.FUNCTION_REGISTRY — Constant
Registry for function information. Maps function name to FunctionInfo.
RustCall.FUNCTION_REGISTRY_BY_LIB — Constant
Library-scoped registry for function information. Maps (library name, function name) to FunctionInfo.
RustCall.FUNCTION_RETURN_TYPES_BY_LIB — Constant
Registry for function return types (for functions without full signature registration), keyed by (library name, function name).
There is deliberately no name-only fallback table, and no cross-library search. A name-keyed hint outlives the library that wrote it: clearing or reloading that library would leave its return type answering for every other library's function of the same name, and a rebuilt library that no longer declares the function that way would be typed by the stale value (#279). Lookups go through the library _resolve_call took the pointer from, so a call's pointer and its ABI always come from the same build.
Guarded by REGISTRY_LOCK.
RustCall.FUNCTION_SYMBOLS_BY_LIB — Constant
Rust item name to exported C symbol, keyed by (library name, Rust name).
#[julia] is additive since #279: the annotated function keeps its own name and the library exports the wrapper rustcall_<name> next to it. @rust add(1, 2) names the Rust function, so the lookup has to go through this mapping, which is filled from the manifest (Function.symbol) — never by string surgery on the name.
The mapping is strictly per library, and identity mappings are recorded too. One library exporting #[julia] fn f as rustcall_f must not decide how f resolves in another library that exports a plain #[no_mangle] fn f under its own name; a library with no entry for a name resolves it to the name itself. Entries are dropped with the library (clear_library_metadata!), so an unloaded library cannot leave a stale mapping behind.
Guarded by REGISTRY_LOCK.
RustCall.PANIC_CHANNELS — Constant
PANIC_CHANNELS(library name, wrapper symbol) → the pointer to that wrapper's panic-channel reader, or C_NULL when the library exports none.
A #[julia] wrapper catches the panic, records the message in a thread-local slot and exports <symbol>_take_panic to read it (#244). This is the legacy, name-keyed memo of that lookup, written only by panic_channel_pointer (which records the negative answer too: an artifact built before #244, or a raw #[no_mangle] function, has no channel and is not probed again). No generated call site uses it any more: a call resolves its channel inside its generation snapshot (resolve_call_target), which reads this memo first and otherwise the image's own pointer cache, so a channel always comes from the image the call captured.
Entries are dropped with their library (purge_library_state!), so a reloaded library re-resolves against the image that is actually mapped rather than calling a pointer into a dlclosed one.
A StateView into STATE: every access takes the state lock (REGISTRY_LOCK).
RustCall.ArtifactGeneration — Type
ArtifactGenerationThe per-object half of a snapshot: what a #[julia] struct captures at construction so its finalizer needs no lookup at all (#249).
free_ptr, free_channel and alive must come from one generation: taken separately, an object could capture the destructor of the image it was allocated by and the liveness flag of the image that replaced it, and would then either skip a free it should have made or make one into an image that had been closed.
RustCall.CallTarget — Type
CallTargetEverything one FFI call needs, taken from one generation of a library.
Why this is a struct and not three lookups
A library can be replaced between any two lookups — that is what a hot reload is — and the pieces of a call belong to different generations if they are resolved separately. Resolving the function pointer, then the panic channel by (library name, symbol), meant a call could enter the retired image and read the replacement's channel: the panic it raised would be invisible, and a panic the new image left there would be reported against a call that never made it. The same split applied to a struct's destructor and its liveness flag, and to an owned-String result whose release function was resolved after the wrapper had already returned.
So every entry point takes one snapshot under one lock and uses only that. The rule for the whole package: nothing after the snapshot may look anything up by library name.
Fields
func_ptr— the wrapper to call.channel— that wrapper's panic channel (C_NULLwhen it has none).free_ptr— the release function for an owned-Stringresult, when the caller asked for one (C_NULLotherwise).alive— the liveness flag of that image. A constructor needs it: the object it returns was allocated by this generation, so it must capture this generation's destructor and this generation's flag, not whatever the library name resolves to after the call returns.handle— the image they were resolved on. What finds the right liveness flag later, when the library's name may have moved on.lib_name— the library the pointers came from, for diagnostics.return_type— the return-type hint that library registered for this function (nothingwhen it registered none), andfunc_info— the richerFunctionInfowhen one is registered. Both are part of the snapshot: the return ABI decides how theccallreads the return slot, so taking it from a later lookup could call a pointer from the retired generation while reading its result with the replacement's ABI — a scalar read as a struct, which is memory corruption rather than a wrong answer.generation— which generation oflib_nameall of the above came from.free_channel— the release/destructor's panic channel from that same image, captured before allocation so an object's finalizer never resolves it later.
RustCall.CallbackFrame — Type
CallbackFrameThe trampolines of one call in progress, slot by slot; see CallbackTrampoline. Pushed by the wrapper before the call (_push_callback_frame!), popped in its finally (_pop_callback_frame!).
RustCall.CallbackSlot — Type
CallbackSlot{K, R}The function Rust calls for callback argument K whose C return type is R: a singleton, so @cfunction(CallbackSlot{K, R}(), R, (...)) is a constant pointer with no closure (#296). It looks up the K-th trampoline of the innermost call in progress and calls it; the trampoline converts the result and catches every exception.
Nothing may raise out of it, because it runs on a Rust stack. When no trampoline is there to call (see _callback_trampoline), or the trampoline's result is not an R (a frame from another call on top), the failure is recorded exactly like an exception a callback threw — re-raised by the guard after the next Rust call on this task — and Rust gets _callback_zero(R) (#460). The return type is a parameter rather than a lookup for exactly this reason: the fallback value has to have the slot's type.
RustCall.CallbackTrampoline — Type
CallbackTrampoline{R}(f)The callable a generated wrapper wraps a user's function in (#296): it calls f, converts the result to the C slot type R (nothing for Cvoid), and never lets a Julia exception escape — the frames below it are Rust's, and unwinding through them is undefined behaviour. An exception is stored for the task (_store_callback_error!) and a zero of R is returned as a sentinel; the wrapper that made the call re-raises the exception once the Rust call has returned (guard_rust_panic_ptr). Only the first exception of a call is kept.
How a Julia function becomes a C function pointer without a closure
@cfunction($f, ...) — a closure trampoline — is not available on every platform Julia runs on (aarch64 raises cfunction: closures are not supported on this platform), so no generated wrapper uses one. Instead the wrapper pushes a CallbackFrame holding the call's trampolines onto a task-local stack for the duration of the call, and passes Rust a constant pointer to one of the plain slot functions _callback_slot_1 … _callback_slot_N (CALLBACK_SLOTS), each compiled by @cfunction for the exact slot types of that argument. Slot k calls the k-th trampoline of the frame on top of the stack. Nested calls push their own frames and pop them on return, so the top is always the innermost call in progress — which is the one Rust is running right now, because a callback may only be invoked while the call that passed it is on the stack (synchronous borrow) and on the thread that made the call.
RustCall.FunctionInfo — Type
FunctionInfoInformation about a registered Rust function.
RustCall._release_owned_return — Method
_release_owned_return(value, free_ptr)Release the owned buffer a call returned and nobody will decode, because the guard is about to raise (#460). A CRustString is freed through free_ptr; a Result / Option aggregate (is_ok / ok_value / err_value, or is_some / value) releases its active payload only — the inactive one is zeroed on the Rust side and freeing it would be a double free. Anything else owns nothing here.
RustCall.call_rust_function — Method
call_rust_function(func_ptr::Ptr{Cvoid}, ret_type::Type, argt::Type{<:Tuple}, args...)Call a Rust function with a tuple type for arguments.
Arguments
func_ptr::Ptr{Cvoid}: Function pointer to the Rust functionret_type::Type: Expected return typeargt::Type{<:Tuple}: Tuple type containing argument typesargs...: Arguments to pass to the function
Returns
- The return value of the Rust function
RustCall.call_rust_function — Method
call_rust_function(func_ptr::Ptr{Cvoid}, ret_type::Type, args...)Call a Rust function with the given return type. Uses a generated ccall based on normalized argument types.
Arguments
func_ptr::Ptr{Cvoid}: Function pointer to the Rust functionret_type::Type: Expected return type of the functionargs...: Arguments to pass to the function
Returns
- The return value of the Rust function, converted to the specified
ret_type
Example
target = resolve_call_target("mylib", "add")
result = call_rust_function(target.func_ptr, Int32, 10, 20) # Returns Int32RustCall.call_rust_function — Method
call_rust_function(func_ptr::Ptr{Cvoid}, ret_type::Type, arg_types::Vector{Type}, args...)Call a Rust function with explicit argument types.
Arguments
func_ptr::Ptr{Cvoid}: Function pointer to the Rust functionret_type::Type: Expected return typearg_types::Vector{Type}: Vector of argument typesargs...: Arguments to pass to the function
Returns
- The return value of the Rust function
Example
target = resolve_call_target("mylib", "multiply")
result = call_rust_function(target.func_ptr, Float64, [Float64, Float64], 3.14, 2.0)RustCall.check_rust_panic_ptr — Method
check_rust_panic_ptr(channel::Ptr{Cvoid}, func_name)guard_rust_panic_ptr for a call whose result is decoded separately — a CResult_* / COption_* payload, or a string buffer. Same rule: the channel must already be resolved, and nothing may run between the wrapper call and this.
RustCall.clear_library_metadata! — Method
clear_library_metadata!(lib_name)Drop everything the registries record about one library: its name-to-symbol mappings, its return-type hints, its panic channels and the generic functions its block defined (GENERIC_FUNCTIONS_BY_LIB).
Called wherever a library leaves RUST_LIBRARIES or is replaced under the same name (unload, hot reload, re-registration of a rust""" block). A stale mapping would redirect a later lookup to a symbol that is no longer loaded, and a stale hint would type a call to a function the rebuilt library no longer declares that way — so the two must go together, in the same transaction that removes the handle (#279).
Both registries are keyed by library, so dropping a library's rows is all there is to it: nothing it recorded can outlive it under a name-only key.
RustCall.copy_library_metadata! — Method
copy_library_metadata!(from, to)Give the library to the same name-to-symbol mappings, return-type hints and owner-qualified generic registrations as from, replacing whatever it had.
Used when one loaded handle is registered under a second name (@rust's reload alias, _alias_reloaded_library): both registries are per library, so the alias needs its own entries. Without the mappings a lookup through it would resolve f to f and miss the rustcall_f the library actually exports; without the hints an untyped @rust f(...) through the alias would fall back to the unscoped table and pick up whatever another block last registered for that name (#279).
RustCall.exported_symbol — Method
exported_symbol(lib_name, name) -> StringThe exported C symbol of the Rust item name in lib_name, or name itself when that library recorded nothing for it (a library loaded outside the manifest pipeline, or a name that is already the exported symbol). Never consults another library's mapping.
RustCall.get_function_info — Method
get_function_info(lib_name::String, name::String) -> Union{FunctionInfo, Nothing}Get registered function info scoped to a library. Falls back to name-only registry for backward compatibility.
RustCall.get_function_info — Method
get_function_info(name::String) -> Union{FunctionInfo, Nothing}Get the registered function info for a function name.
RustCall.get_function_return_type — Method
get_function_return_type(lib_name::String, func_name::String) -> Union{Type, Nothing}The return type lib_name itself registered for func_name, or nothing.
Only that library's own entry is consulted. No name-only fallback, and no search of the other libraries: a hint must never describe a function in a library other than the one the call actually reaches. lib_name here is the owning library — the one _resolve_call took the pointer from — so the pointer and the ABI it is called with always come from the same build.
Borrowing would be worse than having no hint: a library whose f returns Result<i32, i32> deliberately records nothing (the wrapper returns a CResult_f struct, and @rust callers must be explicit), so any hint found elsewhere for the name f is not merely unrelated but the wrong ABI. Absent a hint the caller infers from the arguments or demands an explicit ::T (#279).
RustCall.guard_rust_panic_ptr — Function
guard_rust_panic_ptr(value, channel::Ptr{Cvoid}, func_name)value, unless the wrapper whose channel is channel panicked — in which case the sentinel value is discarded and RustPanicError is raised — or a callback the call drove threw a Julia exception, which is re-raised here, as itself, once the Rust frames are gone (#296).
Why the channel is a pointer and not a (library, symbol) pair
The channel is a thread-local in the loaded image, so the wrapper call and the channel read have to happen on the same OS thread. A Julia task moves between threads only at a yield point, so the rule is that nothing between the two may yield — and resolving the channel from a Dict under REGISTRY_LOCK does yield when the lock is contended. That is exactly long enough for the task to be rescheduled elsewhere, where it would read an empty slot and miss the panic entirely, while a later task landing on the original thread would pick up a message that does not belong to it.
So the resolution happens before the wrapper call, where yielding is harmless — the channel is part of the call's generation snapshot — and this function is what runs immediately after it: one ccall into a thread-local read, no lock, no allocation, no logging. The shape every call site uses is
target = resolve_call_target(lib, name) # may yield: before the call
value = call_rust_function(target.func_ptr, T, args...) # cannot yield
guard_rust_panic_ptr(value, target.channel, name) # cannot yieldC_NULL means the artifact has no channel (built before #244, or a raw #[no_mangle] function the user wrote), and the guard is then a no-op.
RustCall.install_library_metadata! — Method
install_library_metadata!(name, metadata::PreparedLibraryMetadata)Replace a library's symbol mappings, return-type hints and generic functions atomically. The caller must hold REGISTRY_LOCK and publish the handle in that same transaction. Prepare caller-supplied iterators with prepare_library_metadata outside the lock; this publication step accepts only materialized rows.
The generics go in the same transaction as the rest (#520): clearing a library's rows and publishing its generics in two steps left a window in which a call from the defining module found the library without its own generic and fell through to another module's generic of the same name.
RustCall.panic_channel_pointer — Method
panic_channel_pointer(lib_name, symbol) -> Ptr{Cvoid}The panic-channel reader of symbol in lib_name, resolved once and cached (C_NULL when the library has none).
RustCall.purge_library_state! — Method
purge_library_state!(lib_name)Drop every registry row that belongs to lib_name: its symbol mappings and return-type hints (clear_library_metadata!), its FUNCTION_REGISTRY_BY_LIB entries, the MONOMORPHIZED_FUNCTIONS entries whose function pointers point into it (stale pointers into an unloaded image are a use-after-free, #73) — together with their MONOMORPHIZATION_OWNERS rows and the image's GENERIC_IMAGE_PATHS record (#397).
The caller must hold REGISTRY_LOCK. Called from unload_artifact!, which is the only place a library leaves RUST_LIBRARIES (#277 Phase B).
RustCall.register_function — Method
register_function(name::String, lib_name::String, ret_type::Type, arg_types::Vector{Type})Register a function with its type signature for later calling.
RustCall.register_function_symbol — Method
register_function_symbol(lib_name, name, symbol)Record that the Rust item name of lib_name is exported as symbol. Identity mappings are recorded as well: a plain #[no_mangle] extern "C" fn f is explicitly f => f for its own library, which is what keeps another library's f => rustcall_f from leaking into it.
RustCall.take_rust_panic — Method
take_rust_panic(channel::Ptr{Cvoid}) -> Union{String, Nothing}Read and clear the pending panic message of one wrapper, or nothing when it did not panic.
Two ccalls at most, and the first one allocates nothing: passing a null buffer asks the channel for the length only, which it reports without clearing the slot. That matters because the answer is almost always "no panic", and because the probe has to happen with nothing at all between it and the wrapper call that preceded it — see guard_rust_panic_ptr.
The second call, made only when there is a message, passes a buffer of exactly the length the channel reported and clears the slot.
RustCall.@rust_ccall — Macro
@rust_ccall(func_name, ret_type, arg_types, args...)Low-level macro for calling a Rust function with explicit types.
Example
@rust_ccall(add, Int32, (Int32, Int32), 10, 20)Names the generated code uses (src/ffi/emitted_names.jl)
A generated module binds the crate's items under their own names, so the code it emits reaches Base, Core, RustCall and PythonCall only through names no Rust identifier can spell: a GlobalRef in @rust_crate and the PyO3 host, a rustcall′Base / rustcall′RustCall alias in a file written by write_bindings_to_file (#528).
RustCall._emitted_aliases_source — Method
_emitted_aliases_source() -> Vector{String}The lines that bind the source-text emitter's aliases at the top of a generated module (and of each submodule): the only statements that name Base and RustCall by their plain names, before any crate item is defined.
RustCall._emitted_global — Method
_emitted_global(s::Symbol, rustcall::Module) -> Union{Nothing, GlobalRef, Symbol}What a free name s of an emitted template refers to outside the generated module: a GlobalRef into Base (every name Base exports, Core's included) or into RustCall (_EMITTED_RUSTCALL_NAMES), the host module's alias for PythonCall, or nothing when it is none of those — a helper the generated module defines itself (_call_target, _pyo3_module), which stays bare.
RustCall._emitted_source — Method
_emitted_source(ex) -> Stringex as the source-text emitter writes it: every GlobalRef spelled through the generated module's rustcall′ aliases (rustcall′Base.getfield, rustcall′RustCall.ffi_string_argument) rather than by the module's plain name, which a crate item could take.
RustCall._emitted_type — Method
_emitted_type(spelling) -> Union{Symbol, Expr, GlobalRef}A type spelling from the FFI contract (:Int32, :(Ptr{Cvoid}), :(RustCall.RustVec{Float64})) with every name it takes from Base or RustCall made a GlobalRef, for a hole of an emitted template. A contract spelling names no crate item, so every free name in it is one of those.
RustCall._emitted_type_source — Method
_emitted_type_source(spelling) -> StringA contract spelling as the source-text emitter writes it: _emitted_type, then _emitted_source. A string is taken as already written.
RustCall._rust_spellable — Method
_rust_spellable(name) -> BoolWhether name is a Rust identifier's spelling, and so a name a crate item can be bound under: an XIDStart character or `, then XID_Continue characters (approximated by their Unicode general categories).rustcall′Baseis not — U+2032 is punctuation (Po) — and neither is an operator, a macro name or a#`-name.
RustCall.@_emitted — Macro
@_emitted quote ... end
@_emitted :(...)A template of emitted code whose free references to Base, Core and RustCall are GlobalRefs (#528): rewritten once, when RustCall itself is loaded, so no binding of the module the code lands in can capture them. Interpolations ($x) are left alone — they carry the crate's own names and values — and so is every name the template binds or defines itself.