Front doors: rust"""...""", @rust

The front doors a user writes. The pipeline behind them — the rustc invocation and the ccall expressions generated from the FFI manifest — is on Compiler and codegen.

rust"""...""" (src/macros/ruststr.jl)

RustCall.CachedTarget — Type
CallTargetCache()

One call site's memory of the CallTarget it last resolved (#253).

Not a second way to resolve a call: the thing it holds is a whole resolve_call_target snapshot, taken under one lock in the one place allowed to take one, and it is handed back only while ARTIFACT_EPOCH proves no state write has happened since. The generation rule of #277 is therefore unchanged — a call still uses one snapshot of one image, and still never assembles one from pieces. What changes is only how often an unchanged answer is recomputed.

A cache belongs to a call site, not to a name: the generated wrapper of a #[julia] item gets one, and so does every @rust expansion. The object is spliced into the expansion rather than bound in the caller's module, so it needs no name of its own, cannot collide, and a redefinition gets a fresh one.

source
RustCall.RustBlockSnapshot — Type
RustBlockSnapshot

What a rust""" block records in the calling module's __RUSTCALL_LIBS: the source and the cfg / compiler configuration it was expanded under, so a reload after precompilation (ensure_loaded) rebuilds exactly the library the emitted Julia wrappers were generated for.

source
RustCall._cargo_block_id — Function
_cargo_block_id(expanded_source, dependencies, cargo_env = "") -> ArtifactId

Identity of a Cargo-backed block, as an ArtifactId: expanded source, the dependency set (artifact_dependency_strings, which folds a local path dependency in by content rather than by location, so editing one rebuilds), the Cargo/RUSTFLAGS environment the build runs under (cargo_env, see _cargo_cfg_env_key), the release profile, and — new in #278 — the toolchain fingerprint and the identity of the compiler that runs, both defaulted by ArtifactId.

cargo_config is the digest of the effective .cargo/config.toml chain above the directory the build will run in (_cargo_config_digest); the caller passes it because it must be the same digest the whole evaluation uses. cargo_lock is the content digest of the Cargo.lock the build is made with — the resolved graph, persisted per dependency set (lockfile_path, ensure_cargo_lockfile!, #256) — so two builds of one source and one requested range that resolve differently are two artifacts.

artifact_key of this record is the in-memory library name, the disk cache key, the build key and the save key — one value per block evaluation (the generated project's package name is derived from the dependency set, cargo_block_package, so a persisted lockfile fits every block declaring it). The Cargo path used to hash the block once and then re-mix that digest under a second formula for the cache key (#278); the first fix then left build_cargo_project_cached deriving a richer key than the one the outer lookup used, so a Cargo-config change still hit the old binary (#287).

source
RustCall._cargo_block_identity — Function
_cargo_block_identity(expanded_source, deps_hash, cargo_env = "") -> String

The artifact_key of a Cargo-backed block described by an opaque dependency digest (hash_dependencies) rather than by the specs themselves. Kept for callers — and tests — that only have the digest; _cargo_block_id is the richer form the compile path uses, and the two deliberately produce different keys because they describe the dependency set differently.

source
RustCall._compile_and_load_rust — Method
_compile_and_load_rust(code::String, source_file::String, source_line::Int)

Internal function to compile Rust code and load the resulting shared library. Uses caching to avoid recompilation when possible.

Phase 3: Automatically detects dependencies in the code and uses Cargo for building when external crates are required.

source
RustCall._compile_and_load_rust_with_cargo — Method
_compile_and_load_rust_with_cargo(code::String, source_file::String, source_line::Int)

Internal function to compile Rust code that has external dependencies using Cargo. Phase 3: Supports rustscript-style dependency specifications.

Dependency Specification Formats

  1. Document comment format:

    //! ```cargo
    //! [dependencies]
    //! ndarray = "0.15"
    //! ```
  2. Single-line comment format:

    // cargo-deps: ndarray="0.15", serde="1.0"
source
RustCall._manifest_registry_entries — Method
_manifest_registry_entries(signatures) -> (symbols, return_types)

The registry rows a manifest implies: name => exported symbol pairs and name => Julia return type pairs for every exported, non-generic function.

Computing them is deliberately separate from installing them. The rows are derived here, outside any lock (recovering a return type consults the FFI contract and the function registry), and handed to load_artifact! / register_artifact_metadata!, which install them in the same critical section that publishes the library handle — so a task which finds the library in RUST_LIBRARIES also finds how to resolve its names (#279, #277 Phase B).

Identity mappings are included, so a plain #[no_mangle] fn f is explicitly f => f for its library and cannot pick up another library's f => rustcall_f.

A manifest may report one symbol twice. @rust_crate and the hot reload scan an external crate leniently — only target predicates are decided, because the crate's own features and build script are not RustCall's to evaluate — so mutually exclusive #[cfg(feature = ...)] variants of one #[julia] fn both survive. The symbol mapping is the same either way and is recorded, but the return type is not: source order is not evidence of which variant was built, and a wrong primitive hint is a wrong ABI. Such a call falls through to inference or an explicit ::T instead. Deciding an external crate's features exactly needs the crate's own build configuration, which #277 Phase B owns.

source
RustCall._manifest_return_type — Method
_manifest_return_type(sig::RustFunctionSignature) -> Union{Type, Nothing}

The Julia return type to record for an exported function so that @rust calls may omit ::ReturnType, or nothing when the return type has no single-slot Julia counterpart and the call must be explicit.

source
RustCall._record_module_symbols! — Function
_record_module_symbols!(table, lib_name, symbols, module_name)

Record that lib_name exports symbols for one module, refusing a name the module already exports from a different, still-loaded library.

Two blocks in one module that both export add are a genuine ambiguity: the Julia wrapper of the second silently replaced the first, and which library the call reached depended on load order (#250). Rust-side clashes inside one block are already refused by the extractor (symbol_collisions, #279); this is the Julia-side half, across blocks.

Re-running the same block is not a collision — the identity, and therefore the library name, is unchanged. Neither is re-running an edited block whose previous library has been unloaded.

source
RustCall._register_manifest — Method
_register_manifest(expanded::ExpandedInline, lib_name::String;
                   policy, load_path = nothing) -> Bool

Register everything the manifest of a compiled block tells us:

  • the name-to-symbol mapping and the return type of every exported function, so @rust f(...) resolves rustcall_f (#279) and works without ::T;
  • generic free functions and generic struct wrappers, for on-demand monomorphization. The registered code is the whole expanded block and the function is addressed by its qualified name, so specialize instantiates it in place with sibling items, imports and super:: paths intact.

Pass load_path to open and publish a freshly compiled (or cached) library at the same time: the load goes through load_artifact! (src/loading/loadpolicy.jl), which opens the file under policy and installs the handle together with the manifest-derived lookup tables in one REGISTRY_LOCK critical section. That is what makes a concurrent ensure_loaded / @rust f(...) safe: a task that sees the library in RUST_LIBRARIES also sees that f is exported as rustcall_f, instead of resolving f to itself and failing (or, worse, hitting another library's f). No call site inserts into RUST_LIBRARIES itself (#277 Phase B).

Omit load_path when re-registering the volatile tables of a library that is already loaded. The existence check then happens inside the same critical section (register_artifact_metadata!(...; require_loaded = true)), so an unload_library or hot reload racing between a caller's haskey and this call cannot leave metadata and CURRENT_LIB[] pointing at a library that is no longer in RUST_LIBRARIES. Returns false when the library turned out to be gone and nothing was registered; the caller then falls through to compiling and loading it again.

The block's generic functions are prepared outside the lock (_prepare_generic_function may shell out to the extractor to recover a signature, which must not run with the global registry lock held) and installed inside the same transaction as the symbol mappings and return-type hints (install_library_metadata!, #520), so no caller sees the library without its own generics. A generic struct's wrapper group is still published after it, process-wide, by its stem-qualified wrapper names.

source
RustCall._resolve_call — Method
_resolve_call(lib_name::String, func_name::String) -> (Ptr{Cvoid}, String)

The function pointer for func_name and the library it came from.

lib_name is tried first; failing that, every other loaded library is searched as a fallback, which is what lets one rust""" block call another's functions. Each library resolves the name through its own symbol mapping (#[julia] is additive, so f may be exported as rustcall_f, #279).

Candidates are deduplicated by pointer: one loaded handle may legitimately sit in RUST_LIBRARIES under two names — _alias_reloaded_library registers a reloaded library under the identity a precompiled module stored as well as the one the reload derived — and finding the same function twice through the same handle is not an ambiguity. Genuinely different functions of the same name in different libraries still are, and are refused rather than guessed.

Returning the owning library is the point of this function: the caller needs the pointer and the return-type hint to come from the same library, or a Result-returning f in one library gets typed by a primitive-returning f in another.

source
RustCall._rustc_block_identity — Method
_rustc_block_identity(wrapped_source, compiler, cfg_text) -> String

Identity of a block built by rustc directly. A thin adapter over generate_cache_key, which is artifact_key of an ArtifactId: wrapped source, the compiler snapshot it was expanded for (target, opt-level, debug info), the cfg text the wrappers were derived from, the tracked rustc environment (RUSTC_BUILD_ENV_NAMES), the toolchain fingerprint and the identity of the compiler that runs. cfg_text === nothing means the current strict snapshot, as in expand_inline.

Since #278 this is the same value as the on-disk cache key of the artifact: the library name is artifact_short_id of it, never a second digest.

source
RustCall._snapshot_compiler — Method
_snapshot_compiler(target, level) -> RustCompiler

The default compiler with the target triple and optimization level captured at macro-expansion time (the settings that decided the cfg snapshot); the default compiler itself when no snapshot is given.

source
RustCall.cached_call_target — Method
cached_call_target(cache, mod, func_name) -> CallTarget

The CallTarget for func_name as called from mod, reusing cache while the artifact epoch it was resolved at still stands.

The fast path is an atomic load, an integer comparison and nothing else — no lock, which is what lets @rust calls from several threads proceed at once instead of queueing on REGISTRY_LOCK.

source
RustCall.cached_target_hit — Method
cached_target_hit(cache) -> Union{CallTarget, Nothing}

cache's snapshot if it is still current, nothing otherwise. The whole fast path: one atomic load and one integer comparison, no lock.

source
RustCall.cached_target_hit — Method
cached_target_hit(cache, R) -> Union{CallTarget, Nothing}

The same, for a call site that declared ::R — a hit also requires the entry to have been validated against this R.

@rust f(x)::T takes its annotation from an expression, so one call site can ask for a different type on every call while sharing one cache. Handing it an entry checked for another type would read the return slot at the wrong width, which is undefined behaviour rather than a conversion (#245, #390 review).

source
RustCall.ensure_loaded — Method
ensure_loaded(lib_name::String, block) -> String

Ensure that a Rust library is loaded in the current session; block is the RustBlockSnapshot stored by the macro (a plain source string is accepted for modules precompiled by older versions, and is rebuilt under the current default compiler). Returns the name of the loaded library. Useful for precompiled modules that need to reload libraries at runtime.

source
RustCall.get_function_pointer — Method
get_function_pointer(lib_name::String, func_name::String) -> Ptr{Cvoid}

Get a function pointer from a loaded library.

If the function is not found in the specified library, searches all other loaded libraries as a fallback. This enables using functions from multiple rust""" blocks. See _resolve_call, which a caller that also needs the return type should use instead so that both come from the same library.

source
RustCall.list_library_functions — Method
list_library_functions(lib_name::String) -> Vector{String}

The Rust function names the manifest recorded for a loaded library, sorted.

Read from FUNCTION_SYMBOLS_BY_LIB, the per-library name-to-symbol table the manifest fills when the library is registered (#279). A library that is not loaded, or whose manifest recorded no functions, yields an empty list. (Until 0.3.0 this consulted the module registry of the removed LLVM IR path, which nothing ever wrote to, so it always returned an empty list; #265.)

source
RustCall.module_symbol_library — Method
module_symbol_library(mod::Module, symbol::AbstractString) -> String

The library this module's block exported symbol from, or the session's current library when the module recorded nothing for it.

This is what makes a generated wrapper call its own function. Resolving from get_current_library() alone meant the wrapper started its search at whichever block was compiled last anywhere, so a second module defining the same Rust name captured the first module's calls (#250).

source
RustCall.publish_call_target! — Function
publish_call_target!(cache, epoch, target, checked = nothing) -> CallTarget

Record target as cache's answer for epoch. epoch must have been sampled before target was resolved.

checked is the ::T annotation the caller validated this snapshot against, and a later call asking for a different one will not be given this entry.

source
RustCall.resolve_call_target — Method
resolve_call_target(lib_name, func_name; free_symbol = "", fallback = true) -> Union{CallTarget, Nothing}

Everything one call needs — the function pointer, its panic channel, and optionally the release function for an owned-String result — resolved from one generation of one library. The handle, cached pointers and return ABI are captured in one REGISTRY_LOCK critical section; missing pointers are then resolved on that captured handle outside the lock.

This is the entry point every FFI call goes through. A library can be replaced between any two name lookups (that is what a hot reload is), so resolving the pointer and then the channel separately means the call can enter the retired image and read the replacement's channel: a panic raised by the call is invisible, and a panic the new image happens to have left there is reported against a call that never made it. Same for the release function of a String result, which used to be resolved by library name after the wrapper had already returned.

free_symbol, when given, is resolved on the same handle — the <owner>_free_rust_string of a function returning an owned String, or the <Struct>_free of a constructor, whose result must capture this generation's destructor. It is only ever the <owner>_free_rust_string of the function being called, which by construction lives in the same image as the buffer it releases — the allocator contract (docs/src/panics.md).

Resolution starts at lib_name and falls back to the other loaded libraries, which is what lets one rust""" block call another's functions. With fallback = false it does not: the answer is lib_name's own export or nothing — how resolve_rust_call asks whether one of the caller's own blocks defines a name before anything else is consulted (#520). Candidates are deduplicated by pointer: one handle may sit in RUST_LIBRARIES under two names (alias_artifact!), and finding the same function twice through the same handle is not an ambiguity. Genuinely different functions of the same name in different libraries are refused rather than guessed.

source
RustCall.unload_all_libraries — Method
unload_all_libraries(; close = false)

Retire every loaded Rust library. close = true also closes every retired image — see unload_library.

source
RustCall.unload_library — Method
unload_library(lib_name::String; close = false)

Retire a Rust library: remove everything the registries record about it.

A thin wrapper over unload_artifact! (src/loading/loadpolicy.jl), which is the one place a library leaves the registry (#277 Phase B). It drops everything the registries record about the library — its name-to-symbol mappings and return-type hints (a stale mapping would keep redirecting lookups to a symbol that is no longer reachable, #279), its FUNCTION_REGISTRY rows, the monomorphizations whose pointers point into it (#73) and its panic channels.

The image stays mapped. Unloading is the same act as a hot reload replacing a library, and unsafe to close for the same reason: a call that started a moment ago may still be inside it. The image is retired (RustCall.retired_handles) and keeps its liveness flag, so an object it allocated still runs its destructor through it.

close = true reclaims it — the caller stating that no call into it is in flight. That, and only that, makes objects from the image inert (#249, #277).

source
RustCall.@rust_str — Macro
@rust_str(code)

Compile Rust code and load it as a shared library.

Example

rust"""
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    a + b
}
"""
source

@rust (src/macros/rustmacro.jl)

RustCall._OwnDefinitionVanished — Type
_OwnDefinitionVanished(what)

What one attempt of _resolve_own_definition returns when the caller's own defining library went away between restoring it and reading its rows: the answer is unknown, and nothing process-wide may stand in for it (#522).

source
RustCall._alias_reloaded_library — Method
_alias_reloaded_library(mod, stored_name, actual_name)

A reload derived a different library name than the one a precompiled module stored (the identity covers the toolchain fingerprint, compiler snapshot and cfg text, any of which may have changed since precompilation). Register the loaded handle under the stored name too, so the next ensure_loaded finds it instead of reloading, and symbol lookups through the stored name hit this library directly rather than the global fallback search. The module's active library moves to the actual name, under which the manifest was registered.

source
RustCall._call_and_guard — Method
_call_and_guard(func_ptr, R, channel, func_name, args...)

Make the call and read its channel, with the return type as a type parameter.

@rust f(a, b) without an annotation learns its return type from the snapshot, so that type is a runtime value and the call through it is a dynamic dispatch. This is the barrier that keeps it to exactly one: everything inside is specialised on R and on the argument arity, where calling call_rust_function with a runtime Type left the whole chain behind it dynamic — the @generated _call_rust_function reached by a specialisation lookup on every call (#253).

An annotated call (::T) and a #[julia] wrapper know their type statically and do not come through here.

source
RustCall._check_return_annotation — Method
_check_return_annotation(target, func_name, declared)

Raise when a ::T annotation disagrees with the return type the manifest recorded for func_name, naming both (#245).

An annotation exists to supply a return type RustCall does not know. When it is known, a differing annotation is not an override — the ccall would read the return slot at the wrong width or in the wrong register class, which is undefined behaviour, not a cast. Cvoid === Nothing and Cstring === Ptr{UInt8} are the same type to ===, so aliases never trip this, and neither does a surface annotation over the slot the manifest records (_return_annotation_agrees).

source
RustCall._dispatch_with_target — Method
_dispatch_with_target(target, lib_name, func_name, args...)

The half of _rust_call_dynamic that runs once a snapshot is in hand: pick the return type the snapshot recorded, call, and read that snapshot's channel.

Shared with the cached call sites (#253), which reach the same snapshot without re-resolving it, so the two cannot drift in what they do with one.

source
RustCall._module_binding — Method
_module_binding(mod, name) -> Any

The value bound to name in mod, or nothing when there is none. For an adopted legacy caller's runtime tables, return its STATE-owned view instead of the historical raw constant.

getfield is invoked in the latest world. A rust""" block defines __RUSTCALL_LIBS and __RUSTCALL_ACTIVE_LIB in mod, and a @rust call in the same top-level expression — or a test that builds a module and calls straight into it — reads them from a world older than the one that defined them. Julia 1.12 warns about that access ("in a world prior to its definition world") and says it will become an error; invokelatest is the documented way to say "resolve this now", which is what these two bindings need: they are plain mutable containers whose identity is what matters, not something the compiler should specialize on.

source
RustCall._resolve_lib — Method
_resolve_lib(mod::Module, lib_name::String)

Resolve the actual library name to use, handling session-aware reloading for precompiled modules.

When a module has multiple rust""" blocks, all libraries are loaded to enable the fallback function lookup across libraries in get_function_pointer.

source
RustCall._resolve_own_definition — Method
_resolve_own_definition(attempt) -> result

Run attempt() — which restores the caller's blocks and reads their rows — until it returns something other than _OwnDefinitionVanished, at most _OWN_DEFINITION_ATTEMPTS times, then raise a RustError naming what vanished. The one rule for both lookups by owner (#522): resolve_rust_call (a name the caller's own block may define) and _generic_struct_snapshot (a member of the block that emitted a struct). Once the caller's own definition is in question, the process-wide registration is never consulted for that call — it may be another module's definition of the same name.

source
RustCall._return_annotation_agrees — Method
_return_annotation_agrees(declared, recorded) -> Bool

Whether a ::T annotation says the same thing as the return type the manifest recorded.

Identity is not the test, because the manifest records the C slot while an annotation names the surface type a caller sees, and the two differ where the contract says they do: Rust char is a UInt32 code point in the slot and a Char on the surface, bool is a UInt8 and a Bool. @rust f()::Char on a -> char was a correct call before #245 added this check and must stay one.

Two types agree when they lower to the same ccall return slot: the generated call is then byte-for-byte the same and only convert_return differs, which is the conversion the annotation was asking for. ::Float64 on a -> i32 does not agree — different slot, and reading one as the other is undefined behaviour.

source
RustCall._rust_call_dynamic — Method
_rust_call_dynamic(lib_name::String, func_name::String, args...)

Call a Rust function with dynamic type dispatch. Automatically handles generic functions by monomorphizing them.

source
RustCall._rust_call_dynamic_cached — Method
_rust_call_dynamic_cached(cache, mod, lib_name, func_name, args...)

@rust f(a, b) with this call site's snapshot cache (#253).

The generic question stays on the slow path deliberately. A name resolve_rust_call resolves to a generic is specialized and never populates the cache — so a cache hit is by construction a name that already answered it with "a function", and the per-call registry lookup is gone for everyone else. A generic registered later is a state write, which moves the epoch and sends the next call back through resolve_rust_call.

source
RustCall._rust_call_symbol — Method
_rust_call_symbol(lib_name, symbol, ret_type, args...)

Call the exported FFI symbol symbol — a generated wrapper such as rustcall_S_scale — with the return type its generator spliced in.

Not a name @rust resolves: a generated wrapper already knows the exact symbol it calls, so it never goes through resolve_rust_call, whose job is to decide what a user-facing name means and which consults the generic registries first. Routing wrappers through it let a generic free function whose Julia name happened to equal a wrapper symbol (fn rustcall_S_scale<T> beside S::scale) capture the method call (#520 review). The symbol is resolved as the one snapshot resolve_call_target takes, starting at lib_name.

source
RustCall._rust_call_typed — Method
_rust_call_typed(lib_name::String, func_name::String, ret_type::Type, args...)

Call a Rust function with explicit return type.

source
RustCall._rust_comparison_operand — Method
_rust_comparison_operand(mod, expr)

Process an operand of a comparison in @rust. If the expression looks like a Rust call (or qualified call), expand it via rust_impl; otherwise just escape it so plain Julia values pass through unchanged.

source
RustCall._snapshot_return_type — Method
_snapshot_return_type(target) -> Union{Type, Nothing}

The return type the resolved generation records for this symbol: the richer FunctionInfo first, then the per-library hint, and nothing when neither says anything. Read from the snapshot only — never looked up again by name, which is the #277 rule.

source
RustCall.resolve_rust_call — Method
resolve_rust_call(mod, lib_name, func_name) -> Union{GenericFunctionInfo, Tuple{Int, CallTarget}}

What @rust func_name(...) called from mod reaches — the one place that decides it, for every form: typed and untyped, generic and not, lib::f qualified or not (#520). Returns the generic registration to specialize, or the epoch sampled before resolving together with the resolved snapshot.

The order:

  1. The caller's own blocks. For an unqualified call, every library a rust""" block of mod loaded, most recently recorded first; for lib::f, that library alone (and, with mod === nothing — the entry points that take a library name — just lib_name). A block defines func_name either as a function its library exports — asked of that library alone, resolve_call_target(...; fallback = false) — or as a generic it registered (GENERIC_FUNCTIONS_BY_LIB), and each block is asked about both kinds together: the first block that defines the name answers, with whichever kind it defines. So a later block redefines a name for its module — a function or a generic, over a function or a generic — as the module's active block always did for functions; one block cannot define both (_check_julia_name_clashes).
  2. The documented fallback (docs/src/generics.md), only when none of the caller's own blocks defines the name: a generic registered process-wide under the bare name (register_generic_function, or another module's block), then any other loaded library that exports it — the cross-block call, which refuses two different libraries exporting it.

The typed path used to try the symbol tables first and the generic registry only on failure, and the untyped path the other way round, both through a process-wide registry: an unrelated block's plain f shadowed a module's own generic f under ::T, and that generic captured another module's untyped @rust f(x) (#520).

_resolve_lib runs first, outside anything that could mistake its failure for a missing name: it replays a precompiled caller's recorded blocks, which is what registers that module's generics at all, and a block that fails to load must say so (#390 review). The epoch is sampled after it — restoring loads, and a load is a state write — and before anything is resolved, so a write landing in between leaves a published entry stale rather than current (#253). A caller that verifies the snapshot (::T) does so before publishing it.

source
RustCall.@rust — Macro
@rust expr

Call a Rust function from Julia.

Syntax

  • @rust func(args...) - Call a function with automatic type inference
  • @rust func(args...)::RetType - Call with explicit return type
  • @rust lib::func(args...) - Call from a specific library

Examples

# Simple call (types inferred from arguments)
@rust add(10i32, 20i32)

# With explicit return type
@rust add(10, 20)::Int32

# From specific library
@rust mylib::multiply(3.0, 4.0)
source
RustCall.@rust_register — Macro
@rust_register(func_name, ret_type, arg_types...)

Register a Rust function with its type signature for optimized calling.

Example

@rust_register(add, Int32, Int32, Int32)
source