Generics and #[julia] functions
The generic function registry and monomorphization through rustcall-extract specialize, and the Julia wrappers generated for #[julia] free functions (Result/Option aware). See Generics for the user-facing guide.
Generics (src/macros/generics.jl)
RustCall.GENERIC_FUNCTIONS_BY_LIB — Constant
Generic functions keyed by (library name, Julia name) — the owner-qualified counterpart of GENERIC_FUNCTION_REGISTRY (#520).
GENERIC_FUNCTION_REGISTRY is keyed by the bare name, so it is process-wide: a second module whose block defines a generic f replaced the first module's registration, and @rust f(x) from the first module then specialized the second module's source. This table keeps each library's own registration, and resolve_rust_call consults it for the libraries of the caller's own blocks before anything process-wide. Rows are installed and dropped with the library's other metadata, in the same transaction (install_library_metadata!, clear_library_metadata!).
Guarded by REGISTRY_LOCK.
RustCall.GENERIC_FUNCTION_REGISTRY — Constant
Registry for generic functions. Maps function name to GenericFunctionInfo.
RustCall.GENERIC_IMAGE_PATHS — Constant
GENERIC_IMAGE_PATHSRegistry name of a monomorphization image → the file it was opened from.
release_generics needs it for one thing (#397): a batch image is opened from a process-private copy that _BATCH_LIBRARY_COPIES remembers, and opening that same path again hands back the retired image — same handle, same flag — so the memo has to be dropped with the image. The registry does not keep a library's path, and a retirement recorded by unload_artifact! has none to give, so the loader of an instantiation writes it here in the transaction that publishes the instantiation. Written under REGISTRY_LOCK; a stale entry for a name that was unloaded some other way is overwritten the next time that name is loaded.
RustCall.MONOMORPHIZATION_OWNERS — Constant
MONOMORPHIZATION_OWNERSArtifact key of an instantiation → the MonomorphizationOwner it belongs to.
MONOMORPHIZED_FUNCTIONS is keyed by the artifact identity, which folds the source, the bindings and the toolchain into one digest — the right key for a lookup, and one nothing can enumerate by generic. release_generics(f) has to find every instantiation of f without being told their types, so each instantiation records its owner when it is published (#397). The bindings are recorded too, not recomputed: release_generics(f, T) selects rows by them, and an identity recomputed now would miss an instantiation built under a different default compiler or a since re-registered source (#397 review). Written and cleared in the same transactions as MONOMORPHIZED_FUNCTIONS.
RustCall.MONOMORPHIZED_FUNCTIONS — Constant
Registry for monomorphized function instances.
Keyed by artifact_key of the monomorphization ArtifactId (_monomorphization_id), which records the parameter bindings in declaration order together with the source, the compiler snapshot and the toolchain. The previous key was (func_name, tuple(sort(values(type_params))...)): sorting the values discarded which parameter got which type, so pair<T=i32, U=i64> and pair<T=i64, U=i32> shared one entry and the second call ran the first one's machine code (#247).
RustCall.RELEASED_GENERIC_IMAGES — Constant
RELEASED_GENERIC_IMAGESGeneric name → the images (ReleasedGenericImage) a non-closing release_generics of that generic retired and left mapped, one entry per retired image.
A release in two steps is the safe way to reclaim: retire now, so no new call reaches the image, and close later, once nothing holds a pointer or an object from it. By then the retirement has purged every row and owner, so the closing call would find no instantiation to select; this is what it drains instead (#397 review). An entry is recorded in the transaction that precedes the retirement and withdrawn if that retirement did not happen, so a concurrent closing release can never find the rows gone and the record not yet there. A closing release closes the entries whose image is retired now, keeps the ones whose image is still live (a retirement in flight), and forgets the rest — an image closed or replaced by other means.
RustCall._BATCH_LIBRARY_COPIES — Constant
_BATCH_LIBRARY_COPIESlibrary_key → the one path this process opens that batch from.
A batch library holds several instantiations, and load_artifact! keys the handle and the liveness flag on the path, so every member has to name the same file or the batch stops being one image. That file cannot be the cached one (see _restore_generic_artifact), so it is a copy — made once, remembered here, and used by every member for the life of the process.
RustCall.GenericFunctionInfo — Type
GenericFunctionInfoInformation about a generic Rust function that needs monomorphization.
RustCall.GenericStructSnapshot — Type
GenericStructSnapshotOne generic struct member and every member of its group, as one locked read of the registries saw them (_read_generic_struct_snapshot, #522). An instantiation of the group uses only this: the members are never read again by name, so an unload that drops the owner's rows between the lookup and the instantiation cannot leave a constructor-only group (PR #523 review). members is sorted by name and includes member. Immutable, so it cannot be half updated.
RustCall.MonomorphizationOwner — Type
MonomorphizationOwnerWho an instantiation belongs to: the registered generic's name and the concrete types it was instantiated with, in the generic's parameter order (_owner_binding). Parameter names are not part of it: a re-registration may spell f<T> as f<U>, and an impl wrapper in a struct group may name the struct's parameter differently from the struct — the same instantiation either way (#397 review). Immutable, so it can sit in a state table.
RustCall.OwnLibraryState — Type
OwnLibraryStateWhat one of a caller's own libraries answers for one name, as one locked read saw it (_own_definition_snapshot, #522): whether it is loaded, the generation of its image, the generic it registered under the name, and whether it exports a function of the name (a symbol mapping). A library's rows are installed and dropped with the library in one transaction, so these fields are consistent with each other. Immutable.
RustCall.ReleasedGenericImage — Type
ReleasedGenericImageOne image a non-closing release_generics retired: the library name it was registered under, the handle and generation that identify that image (a name is reused by the next image of the same instantiation; a handle value can be too, once closed — the pair is the identity, as in _image_is_current), and the bindings of this generic it carried.
RustCall.TraitBound — Type
TraitBoundRepresents a single trait bound with optional type parameters.
Fields
trait_name::String: Name of the trait (e.g., "Copy", "Add")type_params::Vector{String}: Type parameters for the trait (e.g., ["Output = T"] for Add<Output = T>)
RustCall.TypeConstraints — Type
TypeConstraintsRepresents all trait bounds for a type parameter.
Fields
bounds::Vector{TraitBound}: List of trait bounds (e.g., [Copy, Clone, Add<Output = T>])
RustCall._cache_generic_library — Method
_cache_generic_library(library_key, lib_path, source, members, compiler)
-> Union{String, Nothing}Publish a freshly built monomorphization library under library_key and return the path inside the cache, or nothing when it could not be published.
Publishing is best-effort and never changes what the caller loads: a build opens the file it just produced, as it always has. Only a later restore reads the cache (_restore_generic_artifact).
RustCall._cached_generic_artifact — Method
_cached_generic_artifact(cache_key, member) -> Union{Nothing, NamedTuple}The record and the verified cached library an earlier session left for cache_key, or nothing when there is none that covers member (#254).
Both halves are required. The library is verified against its checksum by load_cached_library; a record with no library, a library with no record, an unreadable record, a record of another format version and a record that does not carry member all read as a miss, and a miss only costs the rebuild that used to happen unconditionally.
artifact_key decides identity, and it folds in the toolchain fingerprint — the extractor digest and the rustcall_julia_core sources — so a cached library can never have been emitted by a different symbol scheme than the record describes.
This is the probe: it materializes nothing, so asking whether an instantiation is already cached costs a TOML parse and a checksum, not a copy of the library. _restore_generic_artifact is the half that produces a file to open.
RustCall._call_monomorphized — Method
_call_monomorphized(info::FunctionInfo, args...)Call a monomorphized function through its FunctionInfo. String arguments (info.arg_abis) are checked to be valid UTF-8 (ffi_string_argument, #246) and passed as (ptr, len) byte pairs kept alive for the duration of the call, and a string return (info.string_return) is copied out of the owned or borrowed buffer, exactly as the generated wrappers of non-generic #[julia] functions do.
RustCall._drop_obsolete_group_members! — Method
_drop_obsolete_group_members!(members)Remove from the bare-name registry every member of a generic struct group that members publish anew — same group, same owner — whose name is no longer among them, so a struct that lost a method loses its registration too. Other owners' members of a same-named group are untouched (#522). Caller holds REGISTRY_LOCK.
RustCall._generic_binding — Method
_generic_binding(generic_info, instantiation) -> Dict{Symbol, Type}One instantiation of precompile_generics, normalized to the parameter map monomorphize_function takes. A bare Type binds a single-parameter generic, a Tuple of types binds the parameters in declaration order, and a mapping — a Dict, a single param => type pair, or any collection of them — binds them by name.
Every spelling is checked against the declared parameters before it is used: a map that leaves one unbound or names one that does not exist is an ArgumentError here, rather than a specialization the extractor is asked to produce for a parameter the generic does not have.
RustCall._generic_group_members — Method
_generic_group_members(registered) -> Vector{GenericFunctionInfo}The members of the generic struct group registered belongs to: the same group symbol and the same owner (#522), sorted by name, registered itself included. The owner-qualified rows (GENERIC_FUNCTIONS_BY_LIB) come first — a reload alias holds the very same records — and the bare-name registry supplies the rest of the owner's members, for an owner whose rows went with an unloaded library. Another owner's same-named members are never among them.
Caller holds REGISTRY_LOCK.
RustCall._generic_snapshot_member — Method
_generic_snapshot_member(snapshot, name) -> Union{GenericStructSnapshot, Nothing}The member name of the group snapshot holds, as a snapshot of the same group — no registry read.
RustCall._instantiate_generic_struct_group — Method
_instantiate_generic_struct_group(group, members, func_name, type_params)Build (or reuse) the instantiation of members — one owner's whole group, as the caller read it — and return func_name's FunctionInfo. Reads no generic registration (#522): which members are in the group is decided by the caller's one read, never again here.
RustCall._manifest_signature_for — Method
_manifest_signature_for(func_name, code) -> Union{RustFunctionSignature, Nothing}Signature of the top-level function func_name in code according to the extractor, or nothing when the code cannot be parsed or has no such function.
RustCall._monomorphization_bindings — Method
_monomorphization_bindings(params, values, item) -> Vector{Pair{String, String}}The Rust spelling of every type argument of one instantiation. A Julia type julia_type_to_rust_string cannot name is reported against item — the function or struct wrapper being specialized — so the message says what failed, not only which type (#595).
RustCall._monomorphization_id — Method
_monomorphization_id(generic_info, func_name, type_params, compiler) -> ArtifactIdThe identity of one instantiation of a generic function: the registered source (context plus generic code), the parameter bindings in declaration order, and the compiler snapshot the instantiation is built under. Cargo-backed registrations additionally identify their dependencies, captured environment, configuration and exact lockfile; direct rustc registrations leave those empty.
Throws ArgumentError when type_params does not bind every declared parameter.
RustCall._monomorphize_generic_struct_group — Method
_monomorphize_generic_struct_group(registered, func_name, type_params)Compile every wrapper of one generic struct instantiation into one cdylib. The constructor and free wrapper therefore use the same allocator, and all methods share the same generation snapshot (#291).
The members are those of registered's own group and owner (_generic_group_members, #522): another module's struct of the same name has the same group symbol and the same wrapper names, and its members must not join this instantiation. The artifact identity is unchanged by that — it is the source, the bindings, the compiler and the group symbol, as before — so an unchanged struct keeps its cache key, and two same-named structs share an instantiation only when their sources are the same.
RustCall._monomorphized_call_args — Method
_monomorphized_call_args(info, args) -> TupleEvery argument converted to the C slot the manifest recorded for it (info.arg_types, resolved through the FFI contract at specialization time).
Without this the ccall signature was derived from the runtime Julia types of the arguments, so fn f<T>(x: T, c: char) called with a Julia Char passed that Char's left-aligned UTF-8 bit pattern where Rust expects a UInt32 code point (#245, #276). A count mismatch is left alone: the receiver-passing paths build their own argument lists and the call itself reports the mismatch.
RustCall._own_definition_snapshot — Method
_own_definition_snapshot(libs, name) -> Tuple{Vararg{OwnLibraryState}}The state of every library in libs for name, read in one REGISTRY_LOCK transaction. resolve_rust_call decides from this alone whether one of the caller's own blocks defines name — never from a row read and a liveness check made in separate transactions, which an unload and a restore landing between them could make disagree (PR #523 review).
RustCall._own_images_unchanged — Method
_own_images_unchanged(states, blocks) -> BoolWhether every own block in states is still the image the snapshot saw — loaded, at the same generation. Read in one transaction, after the resolution's cold symbol lookups: a lookup that found nothing proves nothing about a library that was unloaded, or replaced, while it ran.
RustCall._publish_generic_struct_group! — Method
_publish_generic_struct_group!(group, members)Publish the member wrappers of one generic struct as one set, replacing whatever that group of that owner had before, in one transaction.
A group is identified by its group symbol and its owner (GenericFunctionInfo.owner, the library whose block registered it, #522): two modules' same-named structs share both the symbol and every wrapper name, so the symbol alone would let one module's registration delete the other's members, and a lookup by bare name would build one module's object from the other module's source. Like a block's generic function (_publish_library_generic!), the members go to two places: the bare-name GENERIC_FUNCTION_REGISTRY (the process-wide fallback and the public API), and GENERIC_FUNCTIONS_BY_LIB under the owning library, which is what the defining module resolves through (resolve_rust_call) and which goes with the library (clear_library_metadata!). The owner-qualified rows are written only while the owner is still loaded.
RustCall._restore_generic_artifact — Method
_restore_generic_artifact(cache_key, member) -> Union{Nothing, NamedTuple}The file to open and the specialization metadata for an artifact an earlier session already produced for cache_key, or nothing when _cached_generic_artifact finds none covering member.
Which file is opened, and why it matters
load_artifact! gives the same path the same handle and the same liveness flag ("one image, one flag"), so the file a restore opens decides whether two instantiations share an image — and whether rebuilding after an unload gets a fresh one.
- An artifact private to one instantiation (
library_key == cache_key) is opened from a private copy, exactly as a freshly compiled one is opened from its own build directory. Retiring an instantiation and asking for it again therefore still produces a new image with its own statics and its own liveness flag, which is whattest/test_generic_struct.jlasserts for #291. Reading the cache must not change that; it only removes the compile. - A batch (
library_key != cache_key, written by_batch_monomorphize) is opened from one copy shared by the whole batch —_shared_batch_copy. Several instantiations naming one library is what a batch is, so they must share one mapped image, in the session that built it and in every later one; one path per batch is what gives them one.
Nothing is ever mapped from the cache directory itself. The cache is a mutable store: a concurrent publisher of the same batch calls save_cached_library(..., force = true) on exactly that path, clear_cache() removes it, and on Windows the replacement fails outright while something has it open. A copy is also what the freshly-built path has always done, and src/loading/loadpolicy.jl records why (#253 review of #254).
RustCall._specialized_return_type — Method
_specialized_return_type(rust_type::String, ctx::AbstractString) -> TypeJulia return type of a monomorphized function, from the FFI contract (src/ffi/ffi_contract.jl). A raw pointer keeps its pointee (*mut i32 is Ptr{Int32}, an opaque pointee degrades to Ptr{Cvoid}), and char is the surface Char, which call_rust_function reads out of its UInt32 slot.
A fixed type the contract does not cover goes through the same ffi_return_type_or_throw every other return site uses, so FFI_STRICT[] governs it: :error raises naming the specialized signature, :warn warns once and falls back to Any. It used to become Any silently, which is not a well-defined ccall return slot (#276).
RustCall.call_generic_function — Method
call_generic_function(func_name::String, args...)Call a generic Rust function, automatically monomorphizing if needed.
Arguments
func_name: Name of the generic functionargs...: Arguments (types will be inferred from these)
Example
# Assuming identity<T> is registered
result = call_generic_function("identity", Int32(42))
# Automatically monomorphizes to identity<Int32> and calls itRustCall.get_monomorphized_function — Method
get_monomorphized_function(func_name::String, type_params::Dict{Symbol, Type}) -> Union{FunctionInfo, Nothing}Get a monomorphized function instance if it exists.
Computes the same key as monomorphize_function (_monomorphization_id), which needs the declared parameter order — so an unregistered generic, an incomplete set of bindings, or an unidentifiable toolchain all mean "not cached" rather than an error.
RustCall.infer_type_parameters — Method
infer_type_parameters(func_name::String, arg_types::Vector{Type}) -> Dict{Symbol, Type}Infer type parameters for a generic function from argument types.
Each Rust argument type recorded in the manifest that is exactly a type parameter name (x: T) binds that parameter to the Julia type of the corresponding argument. Parameters that never appear as a bare argument type cannot be inferred and must be supplied explicitly.
Example
# For function: fn identity<T>(x: T) -> T
# Called with: identity(Int32(42))
# Returns: Dict(:T => Int32)RustCall.is_generic_function — Method
is_generic_function(func_name::String) -> BoolCheck if a function is registered as a generic function.
RustCall.julia_type_to_rust_string — Method
julia_type_to_rust_string(jt::Type) -> StringRust spelling of a Julia type used to instantiate a generic parameter (Int32 -> "i32", Point{Float64} -> "Point<f64>"). Throws an ErrorException for a type RustCall cannot name, listing what it can (#595).
RustCall.monomorphize_function — Method
monomorphize_function(func_name::String, type_params::Dict{Symbol, Type}) -> FunctionInfoMonomorphize a generic function with specific type parameters.
Arguments
func_name: Name of the generic functiontype_params: Mapping from type parameter symbols to concrete types
Returns
- FunctionInfo for the monomorphized function
Example
# Register generic function
RustCall.register_generic_function("identity", "pub fn identity<T>(x: T) -> T { x }", [:T])
# Monomorphize with Int32
info = RustCall.monomorphize_function("identity", Dict{Symbol, Type}(:T => Int32))
info.name # "rustcall_identity_i32_<id>"
info.return_type # Int32RustCall.precompile_generics — Method
precompile_generics(func_name, instantiations...) -> Vector{FunctionInfo}Instantiate the registered generic function func_name at every listed set of concrete types, compiling all of the instantiations that are still missing into one shared library with one rustc (or Cargo) invocation, and persist them so that later sessions need none at all (#254).
Each instantiation is a type (for a single-parameter generic), a tuple of types in declaration order, or a param => type mapping:
RustCall.precompile_generics("identity", Int32, Int64, Float64)
RustCall.precompile_generics("pair", (Int32, Int64), (Int64, Int32))Instantiations this session already holds, and those an earlier session left in the cache, are not rebuilt — so a second call, or a second session, compiles nothing. Lazily instantiating a batched type later in the same session, or in any later one, finds the batch library and opens exactly that one image, rather than one image per type.
A generic struct group is left alone: every wrapper of one instantiation of a group already shares a single cdylib, and its members must stay together for allocation and destruction to share an allocator (#291). Instantiations of a group are therefore built one at a time, through the ordinary path.
Returns the FunctionInfo of each requested instantiation, in the order given.
RustCall.register_generic_function — Function
register_generic_function(func_name, code, type_params, constraints, context)Register a generic Rust function for later monomorphization.
Arguments
func_name: Name of the functioncode: Rust function code (with generics)type_params: List of type parameter symbolsconstraints: Trait bounds for type parameters (TypeConstraints or legacy Dict{Symbol, String})context: Additional code (e.g. struct definitions) needed for compilation
Examples
# With TypeConstraints (recommended)
constraints = Dict(:T => TypeConstraints([TraitBound("Copy", []), TraitBound("Clone", [])]))
register_generic_function("identity", code, [:T], constraints)
# Legacy format (still supported)
register_generic_function("identity", code, [:T], Dict(:T => "Copy + Clone"))
# No constraints
register_generic_function("identity", code, [:T])RustCall.release_generics — Method
release_generics(func_name; close = false) -> Int
release_generics(func_name, instantiations...; close = false) -> IntRetire the images behind the instantiations of the registered generic func_name — every one of them, or only the listed ones, spelled as for precompile_generics — and return how many instantiations left the registry (#397). That can exceed the number asked for: releasing is per image, and an image built by precompile_generics holds several instantiations (see below), so release_generics(f, Int8) against a batch of Int8 and Int16 returns 2.
Lazy instantiation maps one image per type and, until this existed, nothing ever unmapped one: a long session touching many types accumulated them for its lifetime. This is the explicit answer, because the implicit one is not decidable — an instantiation hands out a raw function pointer, and a generic struct instantiation hands out objects holding a destructor pointer and the image's liveness flag (#291), so the registry cannot know when nothing refers to an image any more. You can.
What "retire" means here
Exactly what it means for unload_library: the instantiation leaves the registry, so the next call at those types produces a new image with its own statics and its own liveness flag, and the old image stays mapped — retired, not closed — so a pointer or object still holding it keeps working, and an object that is finalized later frees through the image that allocated it. close = true also closes the retired images, flipping their liveness flags first so that any surviving object goes inert instead of calling into unmapped code; pass it only when you know no call into them is in flight and no object from them is still in use, as for unload_library(name; close = true).
Released in two steps is the safe way to reclaim: release_generics(f) now, so no new call reaches the old images, and release_generics(f; close = true) once you know nothing holds a pointer or an object from them. The closing call also closes the images an earlier non-closing release of f retired and left mapped (the typed form, those that carried one of the named types); its return value still counts only the instantiations it retires itself.
Two consequences of how instantiations are laid out:
- Instantiations built together by
precompile_genericsshare one library. Releasing one of them retires that library, so the others leave the registry with it; each comes back — from the cache, without a rebuild — on its next call, as a fresh image. Releasing is per image, and the batch is the image. - A generic struct group is one library per instantiation, with every member wrapper in it (#291). Naming any member's generic releases the instantiation the way the members share it.
Nothing about the on-disk cache changes: a released instantiation is restored from it on the next call and runs neither the extractor nor rustc (#254).
#[julia] functions (src/macros/julia_functions.jl)
Strings in #[julia] functions
#[julia] free functions may take String / &str arguments and return String / &str (#242). The generated extern "C" wrapper — rustcall_<fn>, emitted next to the function, which is itself left untouched (#279) — receives every string as a (ptr, len) UTF-8 byte pair (no NUL terminator, embedded NULs allowed), returns String as an owned buffer that the Julia wrapper copies and releases through <fn>_free_rust_string, and returns &str as a borrowed view that is copied immediately. The Julia wrapper accepts any AbstractString and returns a String; this works for inline rust\"\"\" blocks and for @rust_crate alike. String inside Result / Option is not supported yet.
rust\"\"\"
#[julia]
pub fn shout(input: String) -> String { input.to_uppercase() }
\"\"\"
shout("hello") # "HELLO"RustCall.COptionType — Type
COptionType{T}C-compatible struct for Option<T> returned by FFI functions. Generated by #[julia] proc-macro as COption_<function_name>.
RustCall.CResultType — Type
CResultType{T, E}C-compatible struct for Result<T, E> returned by FFI functions. Generated by #[julia] proc-macro as CResult_<function_name>.
RustCall.RustFunctionSignature — Type
RustFunctionSignatureSignature of a Rust free function as recorded in the FFI manifest produced by rustcall-extract (see src/macros/manifest.jl). Julia never derives this from source text.
Fields
name,arg_types,return_type: as written in Rustarg_names: the Julia parameter names of the arguments, in order —julia_parameter_namesof the Rust names, applied by the constructor, so every emitter reads a name that parses (end→end_,r#for→for_, #516)is_generic,type_params,constraints: generic parameters and their trait boundssymbol: exported C symbol (rustcall_<ffi_name>, #279/#300)ffi_name: the stem every generated symbol of the function hangs off (manifestFunction.ffi_name, schema 7, #300):nameat the crate root, module-qualified otherwise (a::run->a__run). The string release function is<ffi_name>_free_rust_stringattribute::juliaor:noneexported: whether the compiled library exportssymbolreturn_kind::plain,:unit,:resultor:optionok_type/err_type/inner_type: components ofResult/Optionreturnssource: function source (generic functions only), used for monomorphizationmodule_path: enclosing inline modules (["api", "deep"])has_owned_string_helper/has_borrowed_string_helper: the function returnsString/&str; the wrapper returns<fn>_RustCallOwnedString(freed with<fn>_free_rust_string) /<fn>_RustCallBorrowedString(#242). Derived fromreturn_abisince manifest schema 4return_abi: manifestFunction.return_abi—"string"(owned buffer),"str"(borrowed view) or""(as written). The normative description of how the wrapper returns its value (#276)ok_abi/err_abi/inner_abi: how eachResult/Optionpayload travels —"string"for an owned<fn>_RustCallOwnedStringbuffer,""as written (manifest schema 6, #268)arg_slice_elements/arg_slice_lengths: per argument, the manifest representation and length slot forslice/slice_mutborrows (#570); empty for every other argumentcallback_args/callback_returns: per argument, for anarg_abisentry of"callback", the parameter and return spellings of the C-ABI function pointer (Arg.callback_args/Arg.callback_return, #296); empty otherwise
RustCall._binds_julia_struct — Method
_binds_julia_struct(info) -> BoolWhether a struct gets a Julia type, and so a name in the generated module: not one the Rust codegen refuses (a generic #[julia] struct of a crate, #462, #503). The struct emitters report such a struct through _rust_refused_item!, and the layout checks skip it through this predicate.
RustCall._binds_julia_wrapper — Method
_binds_julia_wrapper(sig) -> BoolWhether a function gets a static Julia wrapper, and so a binding in the generated module: not a generic (inline, it is monomorphized per call; in a crate, the proc macro refuses it), and not an item the Rust codegen refuses (#491, _rust_refuses). The one predicate the emitters (_function_skipped!) and the layout checks (_check_module_names, _static_method_collisions) share, so a name is checked exactly when it is bound.
RustCall._boundary_label — Method
_boundary_label(sig) -> String
_boundary_label(info, member) -> StringThe item a boundary-report position is filed under (#454): the Rust item as Rust names it, module-qualified below the crate root — f, a::f, a::S::method, S::field.
RustCall._default_arg_abis — Method
_default_arg_abis(arg_types) -> Vector{String}The abi column for signatures constructed by hand (tests, legacy callers): the extractor classifies argument types on the Rust side (Arg.abi: "string", "str" or ""); this reconstructs the column from the FFI contract (src/ffi/ffi_contract.jl), which is the same table the wrapper generators consult, so a hand-built signature and a manifest one agree.
RustCall._ffi_context — Method
_ffi_context(sig_or_method, owner = nothing) -> StringThe signature an unsupported return type is reported against, for ffi_return_symbol_or_throw.
RustCall._ffi_field_return — Method
_ffi_field_return(info, field_name, field_type) -> FFIContractThe return contract of a struct field getter. Field.abi says whether the getter hands back an owned String or Vec buffer. String release is derived from the struct's FFI name; a Vec carries its element and exact release symbol in schema 10 so the resulting RustVec retains the producing allocator (#303).
RustCall._ffi_function_return — Method
_ffi_function_return(sig) -> FFIContractThe return contract of a free function, with the owner set: the string helpers are named after the Rust item's FFI name, so <ffi_name>_free_rust_string comes out of the contract rather than being spelled at the call site (#246, #249, #300).
RustCall._ffi_method_return — Method
_ffi_method_return(m::RustMethod, owner) -> FFIContractThe return contract of a struct method, with the owner of its string buffers (_method_string_owner). A method that returns the struct itself (returns_boxed_struct) hands back a handle bound to the generation that allocated it: its spelling (Self) is not a contract position, so nothing is recorded for it, and the emitter must not resolve it as one either.
RustCall._function_skipped! — Method
_function_skipped!(sig) -> BoolWhether a function emitter skips sig (!_binds_julia_wrapper(sig)). The emitter is still where a refusal the Rust codegen makes on its own is recorded (#491), a generic #[julia] unsafe fn included, so the report names it.
RustCall._generate_single_wrapper — Method
_generate_single_wrapper(sig::RustFunctionSignature) -> Union{Expr, Nothing}Generate a Julia wrapper function for a single Rust function signature. Uses direct function call instead of @rust macro for better scope handling.
RustCall._generated_local — Method
_generated_local(base, arg_names) -> SymbolName for a local the generated wrapper introduces (func_ptr, c_result, ...): _emitter_local(base), which no Rust argument or crate item can spell, so the two never meet (PR #527 review). arg_names is no longer consulted.
RustCall._handle_type_ref — Method
_handle_type_ref(h::RustHandleArg, scope, escape) -> AnyHow a wrapper names the Julia handle type of the struct a borrowed argument names (#565). scope is the module path of the Julia module the wrapper is defined in — every crate submodule mirrors a Rust module (#300) — and the type is reached from there by parentmodule / getfield, so the reference needs no name of the root module; nothing is an inline rust string block, which binds every struct in its caller's module. Both emitters print the expression.
RustCall._in_callback_frame — Method
_in_callback_frame(frame, call::Expr) -> Exprcall, or — when the plan pushed a CallbackFrame — call inside a try … finally that pops it, so the frame is gone whether the call returns, panics or raises (#296). Every wrapper generator wraps the expression that performs the ccall with this; the source-text emitter's twin is _emit_in_callback_frame.
RustCall._inline_wrapper_exprs — Method
_inline_wrapper_exprs(signatures, struct_infos) -> (struct_defs, function_wrappers)The Julia definitions of one rust""" block: an expression per #[julia] struct (emit_julia_definitions, with the block-wide static-method collisions of #323) and the block's function wrappers. @rust_str splices them into its expansion; inline_boundary_report runs them in collecting mode (#454), so what the report examines is what the block defines.
block is the block's RustBlockSnapshot as @rust_str records it: a generic struct's generated code finds its members through it (#522).
RustCall._is_string_abi — Method
_is_string_abi(abi) -> BoolWhether an argument travels as a (ptr, len) byte pair (Arg.abi of the manifest is "string" or "str"; covers &'a str and other spellings).
RustCall._payload_free_symbol — Method
_payload_free_symbol(owner, abis) -> StringThe <owner>_free_rust_string a Result / Option wrapper must resolve with its function pointer, or "" when no payload is an owned string buffer (#268). Both payloads of one wrapper share the owner's single buffer type, so there is never more than one release symbol to snapshot.
RustCall._string_arg_plan — Method
_string_arg_plan(sig) -> (bindings, preserved, call_args, frame)How the Julia wrapper of sig passes its arguments: bindings converts each argument (String(x) for string arguments, Int32(x) and friends for primitives), preserved lists the string bindings to keep alive during the call, and call_args are the expressions handed to the ccall (pointer(s), sizeof(s) for strings, a constant slot-function pointer for a callback). frame is nothing, or — when the signature has callback arguments (#296) — the symbol of the CallbackFrame the last binding pushes for the call; the site wraps the call with _in_callback_frame(frame, call), whose finally pops it. escape wraps user-visible symbols (esc in macro context, identity inside a generated module).
Every argument is a position of the boundary report (#454): each is recorded as it is decided, and in collecting mode a refusal — a callback signature the plan cannot build, one callback past CALLBACK_SLOTS — is recorded and the argument skipped rather than thrown.
RustCall._string_temp_prefix — Method
_string_temp_prefix(arg_names) -> StringPrefix for the temporaries that hold the converted strings: rustcall′str′, in the namespace of the names an emitter binds itself (_emitter_local), which no Rust identifier — so no argument, and no item of the crate — can spell (PR #527 review). arg_names is no longer consulted.
RustCall._uses_string_ffi — Method
_uses_string_ffi(sig) -> BoolWhether the wrapper of sig needs the preserving wrapper: string arguments, a String / &str return, or a callback argument whose CFunction must stay rooted for the call (#296). The plain wrapper has no GC.@preserve region.
RustCall.convert_c_option_to_rust_option — Method
convert_c_option_to_rust_option(c_option, inner_type::Type) -> RustOptionConvert a C-compatible option struct to RustOption{T}.
RustCall.convert_c_result_to_rust_result — Method
convert_c_result_to_rust_result(c_result, ok_type::Type, err_type::Type) -> RustResultConvert a C-compatible result struct to RustResult{T, E}.
RustCall.emit_julia_function_wrappers — Method
emit_julia_function_wrappers(signatures::Vector{RustFunctionSignature}) -> ExprGenerate Julia wrapper functions for the given Rust function signatures.
For a function like:
#[julia]
fn add(a: i32, b: i32) -> i32 { ... }generates an add(a, b) that converts its arguments to the FFI slot types, takes the call's generation snapshot (cached_call_target, #253, #277), calls the exported wrapper through ccall and checks its panic channel (guard_rust_panic_ptr). Strings, Result / Option returns, by-value aggregates and callbacks each have their own generator (_generate_single_wrapper dispatches). Generic signatures are skipped.
RustCall.generate_c_option_struct_type — Method
generate_c_option_struct_type(func_name::String, inner_type::Symbol) -> ExprGenerate a Julia struct definition for the C-compatible Option type.
RustCall.generate_c_result_struct_type — Method
generate_c_result_struct_type(func_name::String, ok_type::Symbol, err_type::Symbol) -> ExprGenerate a Julia struct definition for the C-compatible Result type.
RustCall.qualified_name — Method
qualified_name(sig_or_info) -> Stringmodule_path::name of a manifest entry, as accepted by rustcall-extract specialize.
Julia names of Rust items (src/macros/julia_names.jl)
The one decision of the name every Rust item — function, method, field, struct, module — is bound under in Julia (#514): a raw identifier loses its r#, and a name Julia reserves gets a trailing underscore.
RustCall.JuliaDefinition — Type
JuliaDefinition(name, scope, owner, what, parent)One definition a generated module makes, as the emitter makes it (#514). name is the Julia name, scope says what Julia keys the definition by, owner is the Rust item it comes from, what names that item in a message, and parent is the Julia type a method, constructor or accessor belongs to ("" for anything else).
:binding— a type or a submodule: a constant of the module;:free— a method with untyped positional arguments: a free function, a constructor (S(args...)), the bare form of a static method, a PyO3-host static method;(:static, T)—name(::Type{T}, args...);(:self, T)—name(self::T, args...): an instance method, a field accessor;(:prop, T)— a property ofT(agetproperty/setproperty!branch), which lives on the type, not in the module;:registry— a key of the@rustname table of arust"""block (the exported functions, hand-written exports included, and the generics).
Every other scope is a method of the module-level generic function name, so all of them share the module's one namespace with the types and submodules.
RustCall._check_julia_definitions — Method
_check_julia_definitions(defs, where_)Refuse a module whose definitions (JuliaDefinition) would replace one another. A module has one namespace: every type, submodule and module-level generic function shares it, and a method of any struct is a method of the module's function of that name. Two rules decide it. Both read only the definitions, never a list of item kinds.
One key, one owner. Two definitions with the same name and scope, made by different Rust items, are one method defined twice. The later one replaces the earlier. This covers:
fn r#forbesidefn for_;struct r#forbesidestruct for_;- a method
get_xbeside the accessor of a fieldx; - a free function beside a PyO3-host static method bound without its type.
Different scopes are ordinary overloading. Instance methods of two structs, or a free function beside an instance method, add methods to one generic function.
A type or module name is taken whole. A name bound to a type or a submodule may be used by no function, except the type's own constructors and methods (
parent), which add methods to the type after it is defined. Sostruct Awith a method bound asfor_besidestruct for_is refused, and so is a free function named like a struct. Otherwise the emitter would define a function where the type goes, and the type definition would fail as a constant redefinition.
RustCall._check_julia_name_clashes — Method
_check_julia_name_clashes(functions, structs, where_; modules, accessors)_check_julia_definitions over julia_definitions of these items. rust""" (src/macros/ruststr.jl) and the crate layout check (_check_module_names) run it before emitting anything, and the PyO3 host runs the same check over its own definitions (_pyo3_host_definitions).
RustCall._is_plain_julia_identifier — Method
_is_plain_julia_identifier(name::AbstractString) -> BoolWhether Julia reads name on its own as a plain identifier. Base.isidentifier accepts the reserved words (for, end, function, ...), so the name is also parsed: exactly a usable identifier parses to a Symbol — a keyword parses to an incomplete expression and true / false to a Bool. The set of reserved words is therefore Julia's own, not a list kept here.
RustCall._rename_parameters — Method
_rename_parameters(functions, structs, emit) -> (functions, structs)The items with each parameter named so that no definition an emitter makes from them reads a name its parameter would shadow (#526). emit(functions, structs) runs the emitter over the items and returns what it defines — an Expr, or the source text of the source-text emitter, which is parsed.
It is run once on placeholder parameters (rustcall′arg′<k>, a name no Rust identifier spells), with the emission's own options (_probe_emission: its strictness, and collecting only when it collects, into a throwaway collector), without logging; for every definition that takes a placeholder, each other symbol it contains — what it reads, calls or binds, its other parameters, its type variables — is reserved for that item. Each item's names are then julia_parameter_names of its own against its reserved set. A refusal the emitter raises is the emission's own and propagates.
RustCall._spells_julia_identifier — Method
_spells_julia_identifier(name::AbstractString) -> BoolWhether every character of name may appear in a Julia identifier at its position — true for the reserved words as well, including true / false, which Base.isidentifier rejects.
RustCall.julia_binding_name — Method
julia_binding_name(spelled::AbstractString) -> StringThe name a Rust item is bound under in Julia — the one decision, for every item kind (#514):
- a raw identifier loses its prefix (
r#type→type):r#fooandfooare one Rust name, and#would start a comment in a written module; - a name Julia reserves (
Meta.parsedoes not read it as a plain identifier:for,end,function,quote,true, ...) gets a trailing underscore (r#for→for_,end→end_), so the binding parses and can be called by name; - every other name is kept as it is.
A name that is not a Julia identifier at all has no spelling and is refused. The trailing underscore can meet a name the crate already binds (r#for beside for_); the layout checks compare the names this function returns, so that crate is refused with both items named rather than bound with one replacing the other. The exported Rust symbols do not depend on this name.
RustCall.julia_definitions — Method
julia_definitions(functions, structs; modules = String[], accessors = false)
-> Vector{JuliaDefinition}What a #[julia] emitter defines in one module for these items. The emitters are rust""" (_inline_wrapper_exprs) and both crate emitters (_crate_wrapper_exprs, emit_crate_module_code).
The definitions are: free functions, struct types and their constructors, static methods (the typed form, and the bare form unless _static_method_collisions withholds it — the helper the emitters use), instance methods and properties. With accessors, also the get_<f> / set_<f>! helpers of the crate expression emitter. modules are the Rust segments of the child modules.
Every name is the one the emitter binds (julia_function_name, julia_method_name, julia_field_name, julia_struct_name, _julia_module_name).
RustCall.julia_field_name — Method
julia_field_name(field::AbstractString) -> StringThe Julia property name of a struct field, and the stem of its accessors (get_<name>, set_<name>!): julia_binding_name of the Rust field name. The accessor symbols keep the Rust side's spelling (field_getters).
RustCall.julia_function_name — Method
julia_function_name(f::RustFunctionSignature) -> StringThe Julia name of a free function: julia_binding_name of its Rust name.
RustCall.julia_method_name — Method
julia_method_name(m::RustMethod) -> StringThe name a method is bound under in Julia: julia_binding_name of the manifest's julia_name — a trait impl's method that shares its name with another method of the struct, Far_m (#506) — or of the Rust name. The one reader, for every emitter and the layout checks.
RustCall.julia_parameter_names — Method
julia_parameter_names(rust_names) -> Vector{String}The Julia parameter names of a function's or method's arguments, in order — the one decision for every emitter (#516). The RustFunctionSignature and RustMethod constructors apply it, so arg_names is already this list wherever a wrapper is generated: inline rust""", the crate expression and source-text emitters, and the PyO3 host.
- an argument is named by
julia_binding_name(r#for→for_,end→end_), so a written bindings file parses; - an argument with no readable Julia name — a pattern (
(a, b): (i32, i32)),_, or a spelling that is no Julia identifier — is namedarg<i>after its position; - a name another parameter already has gets further underscores (
endbesideend_isend__). Names that need no change are claimed first, so they are never the ones renamed; - a name in
reservedgets underscores too: the emitters pass every other name the wrapper's own definition contains (_rename_parameters, #526), sofn echo(pointer: &str)isecho(pointer_)where the wrapper callspointer, andInt64: i64isInt64_where it converts throughInt64.
Every result is a plain, readable identifier and distinct from the others, and applying the function to its own result changes nothing. The locals a wrapper introduces are chosen against this list (_generated_local).
RustCall.julia_struct_name — Method
julia_struct_name(info::RustStructInfo) -> StringThe Julia type name of a struct: julia_binding_name of its Rust name. The exported symbols hang off info.ffi_name, which is not a Julia name.
RustCall.rust_name — Method
rust_name(name::AbstractString) -> StringThe Rust name of an item as one name, whatever its spelling: a raw identifier without its r# (r#type → type), every other name as it is. r#type and type are one Rust name, and a type spelling (PyRef<'_, r#type>), a symbol (rustcall_type_new) or a Python attribute (type) carries it without the prefix. The manifest keeps the item's own spelling — the extractor finds items by it again (specialize) — so every Julia-side lookup, key or comparison of a manifest name goes through this, and the Julia binding is derived from it by julia_binding_name (#514).