The FFI type contract

Rust-to-Julia type mapping lives in one place, src/ffi/ffi_contract.jl, and is documented — with the generated supported-type matrix — under The FFI Type Contract.

rusttype_to_julia is a thin shim over that table. Two spellings changed meaning when it stopped having a table of its own (#276): "str" is RustStr rather than Cstring, and "*const u8" is Ptr{UInt8} rather than Cstring. A Rust str is an unsized UTF-8 slice reached through a (ptr, len) fat pointer and a *const u8 is a plain byte pointer; neither is a NUL-terminated C string.

The reverse direction still has a table of its own, since a Julia type does not determine a Rust spelling:

# Julia to Rust type mapping
const JULIA_TO_RUST_TYPE_MAP = Dict{Type, String}(
    Int8 => "i8",
    Int16 => "i16",
    Int32 => "i32",
    Int64 => "i64",
    UInt8 => "u8",
    UInt16 => "u16",
    UInt32 => "u32",
    UInt64 => "u64",
    Float32 => "f32",
    Float64 => "f64",
    Bool => "bool",
    Cvoid => "()",
)

Contract table and lookups (src/ffi/ffi_contract.jl)

RustCall.FFI_ABI_KINDS — Constant
FFI_ABI_KINDS

The C ABI forms a Rust value can take when it crosses the boundary.

kindC slotsnotes
:voidnonethe Rust unit type ()
:by_valueone, the scalar itselfprimitives, #[repr(C)] aggregates
:pointerone, Ptr{T}raw pointers, opaque handles
:ptr_lenPtr{UInt8} + Csize_t&str and &[T] slices
:ptr_len_capPtr{UInt8} + 2 × Csize_tan owned Rust String / Vec<T> buffer
:callbackPtr{Cvoid}a C-ABI function pointer built from a Julia function, argument position only (#296)
:unknownundefinedthe type is not in the contract

The two multi-word kinds reach a ccall differently depending on direction: as separate argument slots in argument position, and as one #[repr(C)] aggregate (CRustStr / CRustString) in return position, since a ccall has exactly one return type. FFIContract records both — ccall_types for the calling convention, layout for the word list.

:unknown exists so that callers can fail closed (issue #276 acceptance criterion 2) rather than fall back to a guess, the way the removed call_rust_function_infer once did (#417).

source
RustCall.FFI_OWNERSHIP_KINDS — Constant
FFI_OWNERSHIP_KINDS

Who owns the memory a C slot refers to, and therefore who must release it.

kindmeaning
:nonenothing is owned; the value is a scalar passed by value
:borrowedthe pointee belongs to the other side and is only valid for the duration of the call
:owned_by_juliaJulia allocated the buffer; Julia frees it, and must keep it rooted (GC.@preserve) across the call
:owned_by_rustRust allocated it; Julia releases it within the call by calling free_symbol (#246)
:transferred_to_juliathe responsibility to release moved to Julia, which must do so by calling free_symbol — never through Julia's allocator
:unknownthe contract does not say — callers must fail rather than assume

:owned_by_rust vs :transferred_to_julia

The release mechanism is identical: both call the Rust export named by free_symbol, so the Rust destructor runs on the allocator that allocated the value. Julia never frees Rust memory itself — not with Libc.free, not with its own GC. Freeing a Box::into_raw handle any other way skips Drop and, once a crate installs a #[global_allocator], corrupts the heap (#249).

What differs is when, and therefore who holds the pointer:

  • :owned_by_rust — the value does not outlive the call. The wrapper copies it into Julia memory and calls free_symbol before returning, as _call_rust_owned_string already does in a finally (src/ffi/structs.jl). Julia never stores the raw pointer.
  • :transferred_to_julia — the value outlives the call. Julia keeps the handle (a Box::into_raw pointer inside a struct wrapper, from a generated constructor wrapper in rustcall_julia_core::codegen) and is responsible for calling free_symbol later, from a finalizer.

Both are in [FFI_OWNERSHIP_NEEDS_FREE], so both always name that symbol. A missing free_symbol on either is the root of #246 (leaked String returns) and #249 (the drop symbol picked from the Julia-side type tag instead of from the library that allocated the value).

source
RustCall.FFI_OWNERSHIP_NEEDS_FREE — Constant
FFI_OWNERSHIP_NEEDS_FREE

The ownership tags that oblige someone to release the value. The contract keeps the invariant that a position tagged with one of these always names the free_symbol that performs the release — an owned value with no way to free it is the shape of #246 and #249, and is refused rather than recorded.

source
RustCall.FFI_STRICT — Constant
FFI_STRICT :: Ref{Symbol}

What generated code does when the FFI contract cannot describe a return position:

valuebehaviour
:errorraise a RustError naming the signature (the default)
:warnwarn once per signature and emit Any, the pre-#276 behaviour
:noneemit Any silently

Any in a ccall return slot was never well defined — it is the guess #245 is about — so :warn and :none exist only to get an existing crate compiling again while its unsupported types are dealt with. write_bindings_to_file binds this per call through its strict keyword.

source
RustCall.FFI_SYMBOL_PREFIX — Constant

Prefix of every exported symbol that stands in for a user-written Rust item.

#[julia] is additive (#279): the annotated item keeps its name and the extern "C" entry point is emitted next to it under this prefix. Mirrors rustcall_julia_core::codegen::SYMBOL_PREFIX.

source
RustCall.FFI_TYPE_TABLE — Constant
FFI_TYPE_TABLE :: Dict{String, FFIType}

The single source of truth: Rust type spelling → FFIType.

Built by merging the domains of the five existing tables (see the header of this file). Every spelling accepted by any of them is present here, so a type that one layer accepts can no longer be silently mistranslated by the next (#245 item 2). Spellings the contract deliberately refuses are absent, and ffi_lookup returns nothing for them.

source
RustCall.RUST_CODEGEN_REFUSALS — Constant
RUST_CODEGEN_REFUSALS

Every skip_reason kind with which the Rust codegen refuses a #[julia] item outright — a compile_error! at the item — mapped to how the boundary report spells the refused item ("unsafe fn danger"). The kinds are rustcall_julia_core::manifest::skip_reason::CODEGEN_REFUSALS, decided in one place on the Rust side (rustcall_julia_core::refusal, #503); test/test_boundary_report.jl checks that the extractor produces each of them and that the report lists it.

source
RustCall.BoundaryCollector — Type
BoundaryCollector

What boundary_report is computed from (#454): every argument and return position the wrapper generators examined while they ran in collecting mode, in the order they examined them, with the reason for each one the contract cannot describe.

The generators are the report. Each records the positions it decides as it decides them: _string_arg_plan its arguments; _ffi_function_return, _ffi_method_return, _ffi_field_return and the ffi_*_or_throw family a return position; ffi_payload_symbols a Result / Option payload. A refusal that raises a RustError outside collecting mode is recorded instead (_boundary_refuse, _ffi_unsupported_return) and generation carries on with a placeholder, so the item's remaining positions are still examined. A rule added to a generator is therefore in the report by construction; nothing walks the manifest a second time.

item is the Rust item being generated — module-qualified, Struct::member for a method or a field (_boundary_label) — named by each emitter's entry point through _boundary_item!. A position recorded while no item is named is an error, so an emitter that forgets fails the report instead of misfiling its findings. Positions are keyed by (item, position): the emitters decide one position more than once (the surface symbol and the C slot, a field's getter and its setter, an expression and its source text), and the first refusal recorded for a key is the one kept.

source
RustCall.BoundaryNote — Type
BoundaryNote

Something a generator decided that the FFI contract does describe but that leaves a responsibility with the author (#490): the item, the position or "entry point" it concerns, the Rust spelling, and what to check. A note is not a refusal and is not counted among the positions; boundary_report lists notes after the findings. Recorded by _boundary_note!, from the generator that made the decision — the rules are _boundary_raw_pointer_return! and _boundary_unguarded_export! below.

source
RustCall.BoundaryPosition — Type
BoundaryPosition

One argument or return position a wrapper generator examined: the item it belongs to, the position's label ($"argument `x`"$, "return", "Ok payload", "Err payload", "Some payload", "field getter", "field setter"), the Rust spelling, the manifest abi column, and reason — nothing when the FFI contract describes it, otherwise why it does not.

source
RustCall.FFIByValue — Type
FFIByValue

Marker supertype for the #[repr(C)] mirror aggregates RustCall itself generates: the CResult_<fn> / COption_<fn> structs the wrapper generators emit next to a Result- or Option-returning function, in every flavour (macro-expanded and source-emitted, crate and inline).

They need no registration at all, and must not depend on one: the generated code may be precompiled into a downstream package, and a subtype relation is a static property of the type — it survives because it is the type. (The ffi_by_value_layout method table exists for the same reason, one level up: a method is precompiled too. This is the cheaper answer for types RustCall itself emits, because it needs no call at all.)

source
RustCall.FFIContract — Type
FFIContract

The contract for one position — a single argument, or the return value — of a function, i.e. an FFIType resolved for a direction and (optionally) for the manifest abi column.

Fields

  • rust_type::String — the Rust spelling this was resolved from.
  • direction::Symbol — :argument or :return.
  • abi::Symbol — the resolved [FFI_ABI_KINDS] entry.
  • ccall_types::Vector{Type} — what this position contributes to a ccall signature, which is direction-dependent for the multi-word ABIs:
    • :void return — empty;
    • :by_value / :pointer — one entry;
    • :ptr_len / :ptr_len_cap as an argument — the two or three separate argument slots the wrapper takes;
    • :ptr_len / :ptr_len_cap as a return — exactly one entry, the #[repr(C)] aggregate the wrapper returns, because a ccall has one return type. See aggregate_type.
  • aggregate_type::Union{Nothing,Type} — the single #[repr(C)] struct the C value is, when this position passes an aggregate. Set for :ptr_len / :ptr_len_cap in return position (CRustStr / CRustString, matching <fn>_RustCallBorrowedString / <fn>_RustCallOwnedString emitted by rustcall_julia_core::codegen), nothing otherwise — arguments are expanded into separate slots, not passed as an aggregate.
  • layout::Vector{Type} — the C field layout of the value, in order, for the multi-word ABIs ([Ptr{UInt8}, Csize_t] / [Ptr{UInt8}, Csize_t, Csize_t]). Direction-independent: it describes the value, not the calling convention. Empty for the single-word ABIs.
  • surface_type::Type — the Julia type the user sees at this position.
  • ownership::Symbol — one of [FFI_OWNERSHIP_KINDS].
  • free_symbol::Union{Nothing,String} — for :owned_by_rust, the name of the symbol that releases the value. The name is per-owner (<fn|Struct>_free_rust_string, emitted by rustcall_julia_core::codegen), so it is filled in only when the caller passes owner; nothing otherwise.
  • known::Bool — false when the Rust spelling is not in the contract. A caller that must fail closed checks this instead of inspecting the fallback.
source
RustCall.FFIType — Type
FFIType

One row of the contract: what a Rust type spelling means at the boundary.

Fields

  • rust::String — the canonical Rust spelling ("i32", "String", "&str", "()").
  • ccall_type::Type — the Julia type of the single C slot in the by value form. For multi-slot ABIs (:ptr_len, :ptr_len_cap) this is the type of the leading pointer slot; use ffi_argument_contract / ffi_return_contract for the full slot list.
  • surface_type::Type — the type a Julia caller sees.
  • julia_expr::Union{Symbol,Expr} — how the surface type is spelled in generated code, as a Julia AST fragment ready to splice with $: a Symbol for a plain name (:Int32, :Cvoid, :RustString) and an Expr for a parametric one (:(Ptr{Ptr{Int32}})). Kept separate from surface_type because Julia aliases erase spellings: Cvoid === Nothing and Csize_t === UInt64, and the existing generators emit :Cvoid / :Csize_t. Evaluating it in the RustCall module yields surface_type.
  • abi::Symbol — one of [FFI_ABI_KINDS], the ABI when the type appears as a plain by-value argument or return.
  • ownership::Symbol — one of [FFI_OWNERSHIP_KINDS].
  • note::String — why this row is the way it is, when that is not obvious.
source
RustCall._boundary_collector — Method
_boundary_collector() -> Union{Nothing, BoundaryCollector}

The collector of the current task, or nothing outside collecting mode — the generators' normal case, in which every recording helper below is a no-op and every refusal raises exactly as it always has.

source
RustCall._boundary_examined! — Method
_boundary_examined!(position, rust_type, abi, reason)

Record that generation examined position of the current item; reason is nothing when the contract describes it and the reason otherwise. Recording the same (item, position) again keeps the first reason and adds one where the earlier record had none, so a helper that examines a position on the way to the decision (the contract lookup) and the decision itself (an or_throw) count as one. A no-op outside collecting mode.

source
RustCall._boundary_item! — Method
_boundary_item!(label)

Name the Rust item whose wrapper the emitter is about to generate; every position recorded until the next call is filed under it. Called at each emitter's entry point — before its argument plan, which is the first thing that records. A no-op outside collecting mode.

source
RustCall._boundary_note! — Method
_boundary_note!(position, rust_type, note)

Record a note (BoundaryNote) against the current item: a decision the contract accepts that still leaves something to the author. The same (item, position, note) recorded twice — by the surface and the slot helper, say — is one note. A no-op outside collecting mode.

source
RustCall._boundary_raw_pointer_return! — Method
_boundary_raw_pointer_return!(position, rust_type, c::FFIContract)

Note a position that hands a raw pointer (*const T / *mut T) back to Julia (#490). Every owned value RustCall generates carries its release symbol (free_symbol, derived in one place); a raw pointer carries none, and whether it transfers ownership is not in the signature — so this is a note, not a refusal. Called by the generators that decide a return or payload position (_ffi_item_return, ffi_payload_symbols, _manifest_return_type); a field getter's pointer is borrowed from its struct and is not noted.

source
RustCall._boundary_refuse — Method
_boundary_refuse(position, rust_type, abi, message)

How a wrapper generator refuses a position of its own accord — beyond what the contract's or_throw helpers decide. Outside collecting mode this throws RustError(message), exactly as the generator always has; in collecting mode the refusal is recorded against the current item and the generator continues (the caller skips the position). Every such refusal goes through here, so it is in the report by construction.

source
RustCall._boundary_unguarded_export! — Method
_boundary_unguarded_export!(rust_type)

Note a hand-written #[no_mangle] extern "C" export that @rust can call with no generated panic boundary (#490). Called by _manifest_registry_entries, the generator that registers such an export's name and return type for @rust.

source
RustCall._collect_boundary — Method
_collect_boundary(f) -> BoundaryCollector

Run f() — the wrapper generators — in collecting mode on the current task and return what they examined. Task-local, like the callback frame stack (#296): a rust""" block expanding on another task meanwhile generates normally. Does not nest: a report is one run of the generators.

source
RustCall._ffi_by_value_agrees — Method
_ffi_by_value_agrees(T, layout) -> Nothing

Raise when T already carries an exact assertion recording a different layout than the one now being made.

A re-registration that says the same thing is idempotent — the same claim, made twice — and silently redefining the method would warn under --warn-overwrite=yes and be rejected during package precompilation. A re-registration that says something else is not a duplicate at all: one of the two callers is wrong about the Rust type, and quietly keeping either answer is how a layout assertion stops meaning anything.

Today :repr_c is the only layout there is, so this can only fire if a future kind is added — which is exactly when it must.

source
RustCall._ffi_by_value_needs_method — Method
_ffi_by_value_needs_method(T) -> Bool

Whether a ffi_by_value_layout method for exactly T still has to be defined. See register_ffi_struct for why only an exact duplicate is skipped.

Uses the state-owned method-definition gate, never STATE, because the macro form cannot hold the gate across its definition: a method definition has to be a top-level expression in the calling module, and a lock(...) do ... end body would make it a local. Serializing the check alone is enough there — a macro used at a module's top level expands while that module is being loaded, on one task.

source
RustCall._ffi_layout_method — Method
_ffi_layout_method(T) -> Union{Method, Nothing}

The ffi_by_value_layout method that register_ffi_struct(T) defined for exactly T, or nothing when there is none.

Exactness is the point, twice over. A user registration is always for one concrete type, but RustCall's own mirrors are asserted with covering methods (ffi_by_value_layout(::Type{<:RustPtr})), and which alone would hand one of those back — so a register_ffi_struct call could be elided as "already asserted", or an unregister_ffi_struct could delete the package's own claim about every RustPtr{T}. Comparing the signature to _ffi_layout_signature means each operation sees only the assertion register_ffi_struct(T) itself would make.

invokelatest, because the method may have been defined in this very world — which is also what lets ffi_by_value_registered answer for a registration made in the same top-level expression, with no bookkeeping on the side.

source
RustCall._ffi_layout_signature — Method
_ffi_layout_signature(T) -> Type

The ffi_by_value_layout method signature register_ffi_struct(T) defines: Tuple{typeof(ffi_by_value_layout), Type{T}}, for the one concrete type T and nothing else. Reconstructed rather than remembered, so unregister_ffi_struct can find a method a previous session defined and a precompile cache restored.

source
RustCall._ffi_registration_module — Method
_ffi_registration_module(T) -> Module

Where the ffi_by_value_layout method for T is defined: the module that owns T, so the method lands in that module's precompile cache and comes back with it.

A type Julia itself owns (a Tuple, whose parentmodule is Core) has no such home; the method goes to RustCall instead, and a registration of one from a package's top level is therefore session-local. Register the struct rather than the tuple when that matters.

source
RustCall._ffi_strict — Method
_ffi_strict() -> Symbol

The strictness in force: the emission's own (_with_emission_strict), or FFI_STRICT[] outside one.

source
RustCall._rust_refused_item! — Method
_rust_refused_item!(skip_reason, name) -> Bool

Whether the Rust codegen refuses the current item outright, as the manifest's skip_reason says (_rust_refuses) — a #[julia] function, method or struct the codegen refuses with a compile_error! (#491, #503). A wrapper generator asks at its entry point, after _boundary_item!, and emits no wrapper for such an item.

In collecting mode the refusal is a finding, recorded through _boundary_refuse at the item's "entry point"; the item's argument and return positions are not examined, since no wrapper exists to have them. Outside it the refusal is the codegen's own — a compile_error! at the item, gated by the item's #[cfg] — so nothing is raised here: a crate is scanned leniently, and raising would refuse a build that configures the item away.

source
RustCall._rust_refuses — Method
_rust_refuses(skip_reason) -> Bool

Whether a manifest skip_reason says the Rust codegen refuses the item outright (a kind of RUST_CODEGEN_REFUSALS: an unsafe fn, a generic or impl Trait signature the flavour cannot bind, a payload or a Self or a lowered &str the wrapper cannot express — #491, #503), so it gets no Julia binding. Pure: the recording form is _rust_refused_item!.

source
RustCall._validate_ffi_by_value — Method
_validate_ffi_by_value(T; repr_c = true, form = "register_ffi_struct")

Everything register_ffi_struct refuses, in one place, so the macro form refuses exactly the same things. form is how the call was spelled, so the message quotes back what the caller wrote.

Returns T, or throws ArgumentError.

source
RustCall.ffi_aggregate_type — Method
ffi_aggregate_type(abi::Symbol) -> Union{Type, Nothing}

The #[repr(C)] struct a multi-word ABI kind is returned as: CRustStr for :ptr_len, CRustString for :ptr_len_cap, nothing for every single-word kind.

These mirror the <fn>_RustCallBorrowedString { ptr, len } and <fn>_RustCallOwnedString { ptr, len, cap } helpers the wrapper generator emits (rustcall_julia_core::codegen) and that _call_rust_owned_string / _call_rust_borrowed_string already receive (src/ffi/structs.jl).

source
RustCall.ffi_argument_contract — Method
ffi_argument_contract(rust_type; abi = "", slice_element = "", slice_length = "") -> FFIContract

The contract for one argument position. Multi-word values are expanded into separate argument slots here, because that is how the generated wrapper takes them.

abi is the manifest Arg.abi column (PR #274); when non-empty it overrides the ABI derived from the Rust spelling, which is what makes the manifest normative (#270). It is also the only thing that selects the lowered string form: ffi_argument_contract("String") is unknown, abi = "string" makes it :ptr_len. A slice / slice_mut manifest entry additionally requires its slice_element representation and slice_length = "usize"; its pointer slot is typed by that representation, never inferred from the Rust spelling.

When the position cannot be described the returned contract has known = false, empty ccall_types and :unknown ownership — callers must raise rather than substitute a default.

c = RustCall.ffi_argument_contract("&str"; abi = "str")
c.ccall_types     # Type[Ptr{UInt8}, Csize_t]  — two argument slots
c.aggregate_type  # nothing
c.ownership       # :owned_by_julia  (Julia's buffer, rooted for the call)
source
RustCall.ffi_by_value_allowed — Method
ffi_by_value_allowed(T) -> Bool

Whether a value of T may cross the boundary by value: true for everything that is not an aggregate, for RustCall's own generated mirrors (FFIByValue), and for other aggregates only once asserted.

source
RustCall.ffi_by_value_error — Method
ffi_by_value_error(T, position) -> RustError

The error raised when an unregistered aggregate reaches the boundary by value. position names where it appeared, e.g. "argument 2" or "the return type".

source
RustCall.ffi_by_value_layout — Method
ffi_by_value_layout(::Type{T}) -> Symbol

:repr_c when someone has asserted that T may cross the boundary by value, :unknown otherwise. The registry of #245, expressed as a method table rather than a container.

is_supported_arg_type used to be isbitstype(T), and ccall_arg_type the identity — so any isbits Julia struct or tuple was passed by value on the assumption that its layout matches the Rust side's. Rust's default repr(Rust) layout is explicitly unspecified (fields may be reordered, niches exploited), so that assumption holds only until a rustc upgrade decides otherwise, and then it is silent corruption rather than an error. This function is the record of who asserted otherwise, and about which type.

Why dispatch and not a Set

Because a registration has to survive precompilation. register_ffi_struct is meant to be called at a package's top level, next to the struct it is about — and a push! into a global that lives in RustCall happens during that package's precompilation and is not replayed when the package is later loaded from its cache. The assertion would hold in the session that compiled the package and be gone in every session after it, with the by-value call failing before it reached Rust.

A method definition is precompiled: register_ffi_struct defines ffi_by_value_layout(::Type{Point}) = :repr_c in the module that owns Point, so the method is stored in that module's cache image and reinstated on load, exactly like any other method the package defines. Dispatch also expresses the narrow and the wide assertion natively — ::Type{Point{Float64}} for one instantiation, ::Type{<:Point} for all of them — which a keyed container has to fake.

Withdrawal (unregister_ffi_struct) deletes the method it is about, and only that one, so there is no exception list to keep in step with the table — and no bookkeeping container of any kind beside it.

source
RustCall.ffi_by_value_registered — Method
ffi_by_value_registered(T) -> Bool

Whether T carries a by-value assertion — a ffi_by_value_layout method covering it, whether that method was defined in an earlier session or a moment ago in this one.

source
RustCall.ffi_callback_plan — Method
ffi_callback_plan(callback_args, callback_return, ctx) -> NamedTuple

What a generated wrapper needs to build the @cfunction for a callback argument (#296): ret_expr and arg_exprs, the Julia spellings of the C slot types of the pointer's return and parameters (:Int64, :Cvoid, :(Ptr{UInt8})), and ret_type, the return slot as a Type, for the trampoline's conversion.

callback_args / callback_return are the manifest's Arg.callback_args / Arg.callback_return — the Rust spellings the extractor reported for the extern "C" fn(A...) -> R type; Julia never reads that syntax itself (#264). ctx names the position for the error.

The decision is the contract's, and it fails closed: every parameter and the return must be a type the contract passes by value or as a raw pointer in one slot whose slot type is its surface type — the numeric primitives, bool, usize/isize, *const T / *mut T, and () for the return. Refused with a RustError naming the position: strings (&str, String), char (its slot is a UInt32 code point, not a Char), aggregates, and any spelling outside the table. A refused signature fails at wrapper generation, never at call time.

source
RustCall.ffi_ccall_type — Method
ffi_ccall_type(rust_type::AbstractString) -> Union{Type, Nothing}

The Julia type of the single C slot this Rust type occupies, or nothing when the contract cannot say — either because the type is unknown, or because the spelling alone does not determine its ABI (the string rows). For multi-word ABIs use ffi_argument_contract / ffi_return_contract.

source
RustCall.ffi_char_code_point — Method
ffi_char_code_point(c) -> UInt32

The Unicode scalar value of a Julia Char (or of an integer already holding one), as it must reach a Rust char slot. Julia stores a Char as left-aligned UTF-8 code units, so its bit pattern is not the code point and reinterpreting it would hand Rust a different character (#245).

Rejects anything that is not a Unicode scalar value: Rust's char has that as a validity invariant, and constructing one from a surrogate or an out-of-range value is undefined behaviour there.

source
RustCall.ffi_char_from_code_point — Method
ffi_char_from_code_point(value) -> Char

The Julia Char a Rust char slot denotes — the inverse of ffi_char_code_point, and equally strict. A Rust char is always a Unicode scalar value, so a slot that is not one did not come from a char; it is refused rather than turned into an invalid Char.

source
RustCall.ffi_check_by_value — Method
ffi_check_by_value(R, arg_types)

Fail closed on any unregistered aggregate in a call's signature, before a ccall is generated for it. Called from call_rust_function, the one runtime entry point every @rust call goes through — not from the @generated body below it, because a generated method is not re-generated when register_ffi_struct is called later.

source
RustCall.ffi_check_by_value_signature — Method
ffi_check_by_value_signature(R, A)

ffi_check_by_value for a call whose whole signature is known as a type: the return type R and the argument tuple type A.

Same decision, taken at compile time in the case where it cannot depend on runtime state (#253). ffi_by_value_allowed is !ffi_is_aggregate(T) || T <: FFIByValue || ffi_by_value_registered(T), and only the last of those three reads state register_ffi_struct may add to later — it is reached only for an aggregate. So when no type in the signature is an aggregate, the answer is true for every element, unconditionally and for the whole session; a signature that does contain one keeps the runtime check in full, which is what makes a later register_ffi_struct still take effect.

This is not a second copy of the policy: the predicate it branches on is ffi_is_aggregate, the same one ffi_by_value_allowed consults.

Scalar calls paid 128 ns per call for this, against the 5.1 ns ccall it guards.

source
RustCall.ffi_describe — Method
ffi_describe(rust_type; direction = :return, abi = "") -> String

A one-line human-readable rendering of a contract, for error messages and for the documentation of the supported-type matrix (#245 item 4).

source
RustCall.ffi_free_symbol — Method
ffi_free_symbol(owner::AbstractString) -> String

The name of the symbol that releases an :owned_by_rust string produced by owner (a function or struct name): <owner>_free_rust_string, matching the helper rustcall_julia_core::codegen emits.

source
RustCall.ffi_is_aggregate — Method
ffi_is_aggregate(T) -> Bool

Whether T is an aggregate at the C boundary — a struct with fields, or a tuple — as opposed to a scalar whose ABI is fixed by its width.

Primitive types (Int32, Float64, a user primitive type), pointers and zero-field singletons are not aggregates: there is nothing about them a layout decision can change. Everything else has a field order, and Rust does not promise one without #[repr(C)].

source
RustCall.ffi_julia_symbol — Method
ffi_julia_symbol(rust_type::AbstractString) -> Union{Symbol, Expr, Nothing}

How the surface type should be spelled in generated code, as a Julia AST fragment, or nothing when the type is unknown.

A plain name comes back as a Symbol (:Cvoid, :Csize_t, :RustString); a parametric one comes back as an Expr (:(Ptr{Ptr{Int32}})), never as a Symbol of its printed form — Symbol("Ptr{Int32}") would splice into generated code as var"Ptr{Int32}", an undefined binding. Both forms can be interpolated into a quote directly:

T = RustCall.ffi_julia_symbol("*const *mut i32")   # :(Ptr{Ptr{Int32}})
:(x::$T)

Use ffi_julia_type when you want the Type itself rather than its spelling.

This replaced _rust_type_to_julia_type_symbol (src/macros/julia_functions.jl) and rust_to_julia_type_sym (src/ffi/structs.jl), both of which answered :Any for an unknown type; this answers nothing, so a caller can fail closed. Return sites should call ffi_return_symbol_or_throw, which does exactly that.

source
RustCall.ffi_julia_type — Method
ffi_julia_type(rust_type::AbstractString) -> Union{Type, Nothing}

The Type that ffi_julia_symbol's expression names — the surface type as a value, for callers that want to compare types without eval. nothing when the type is unknown.

RustCall.ffi_julia_type("*const *mut i32") === Ptr{Ptr{Int32}}
source
RustCall.ffi_known — Method
ffi_known(rust_type::AbstractString) -> Bool

Whether the contract has a row for this Rust type spelling.

Note that a row is not by itself enough to build a call: the string rows carry abi === :unknown because the spelling does not say whether the wrapper lowered them (see the Strings section above). Use ffi_argument_contract / ffi_return_contract, whose known field answers the question a call site actually asks — "can I build this position?" — and is false for a string spelling without a manifest abi.

source
RustCall.ffi_lookup — Method
ffi_lookup(rust_type::AbstractString) -> Union{FFIType, Nothing}

The contract row for a Rust type spelling, or nothing when the contract does not cover it. The spelling is normalized with ffi_normalize_spelling first, so core::primitive::u8 resolves like u8.

Raw pointer spellings (*const T, *mut T) are synthesised on demand: they map to Ptr{J} where J is the pointee's Julia type. The pointee is resolved recursively through ffi_lookup, so *const *mut i32 is Ptr{Ptr{Int32}}; only a pointee the contract genuinely cannot map (an opaque handle, or a multi-word type like String that has no single-word C form) degrades to Ptr{Cvoid}. This mirrors rustcall_julia_core's Type::Ptr => true (is_ffi_compatible_type in deps/rustcall_julia_core/src/types.rs), which accepts every pointer wholesale.

nothing is the fail-closed answer. Callers must not substitute a default for it; that is the guess this file exists to remove (#245 item 1).

source
RustCall.ffi_manifest_abi_kind — Method
ffi_manifest_abi_kind(abi::AbstractString) -> Union{Symbol, Nothing}

Translate the manifest abi column (Arg.abi, Method.return_abi; #270 and PR #274) into an [FFI_ABI_KINDS] entry, given the direction it appears in.

The column is a small closed vocabulary of strings:

columnargumentreturn
""as writtenas written
"string":ptr_len:ptr_len_cap
"str":ptr_len:ptr_len
"callback":callbackrefused

"" means "the Rust type spelling decides", and is returned as nothing. An unrecognised column value is an error rather than a fallback, and so is "callback" in return position: a Rust function handing a function pointer back to Julia has no owner for it (#296).

source
RustCall.ffi_method_symbol — Method
ffi_method_symbol(struct_name, method_name) -> String

The exported symbol of the wrapper of the #[julia] method Struct::method (rustcall_<Struct>_<method>, see deps/rustcall_julia_core/src/codegen.rs).

This is the fallback for a RustMethod built by hand rather than read from a manifest: its six-argument constructor cannot know the struct name, so it records no symbol and the emitters derive one here. A manifest-backed method always carries its own symbol and never reaches this (#279).

source
RustCall.ffi_normalize_spelling — Method
ffi_normalize_spelling(rust_type::AbstractString) -> String

The table key for a Rust type spelling: whitespace trimmed, and a core::primitive:: / std::primitive:: qualifier stripped so that core::primitive::i32 resolves like i32. A leading :: (the rooted form ::core::primitive::i32, which type_to_string preserves) is stripped first.

Only those two prefixes are stripped; see [FFI_PRIMITIVE_PATH_PREFIXES] for why an arbitrary mycrate::i32 — rooted or not — is not normalized even though rustcall_julia_core accepts it.

source
RustCall.ffi_owned_string_return — Method
ffi_owned_string_return(c) -> Bool
ffi_borrowed_string_return(c) -> Bool
ffi_owned_vec_return(c) -> Bool

Whether a return contract describes a lowered owned (CRustString, (ptr, len, cap)) or borrowed (CRustStr, (ptr, len)) string buffer.

Every generator branches on these rather than on return_abi == "string", on has_owned_string_helper, or on the Rust spelling — the three vocabularies #276 collapses. An owned contract also carries the free_symbol that releases it, which is the half #246 and #249 are about. ffi_owned_vec_return identifies the schema-10 CRustVec aggregate separately because it stays owned by Julia.

source
RustCall.ffi_owned_vec_contract — Method
ffi_owned_vec_contract(rust_type, element_type, free_symbol) -> FFIContract

Build the manifest-stated contract for a Vec<T> field getter. Unlike an owned String, a vector remains live on the Julia side as RustVec{T}, so its release function accepts the complete CRustVec aggregate and is retained by the resulting object together with the producing library generation.

source
RustCall.ffi_ownership — Method
ffi_ownership(rust_type::AbstractString) -> Symbol

The ownership tag of a Rust type in return position, or :unknown.

source
RustCall.ffi_panic_symbol — Method
ffi_panic_symbol(symbol::AbstractString) -> String

The panic-channel reader a generated wrapper exports next to itself: <wrapper symbol>_take_panic, matching rustcall_julia_core::codegen::panic_symbol (#244).

(out, cap) -> len semantics: the length of the pending panic message, or 0 when the wrapper did not panic. The message is copied into out and the slot cleared only when it fits in cap, so a caller that guessed too small a buffer calls again with the length it was told. Nothing crosses the boundary that has to be freed.

Derived from the wrapper symbol rather than carried in the manifest on purpose: the caller already resolved the symbol to make the call, so it can resolve the channel without a schema change. A library that predates #244 simply has no such symbol, and the lookup falls back to "no channel".

source
RustCall.ffi_payload_is_owned_string — Method
ffi_payload_is_owned_string(rust_type, abi) -> Bool

Whether a Result / Option payload travels as an owned string buffer.

The manifest states this in ok_abi / err_abi / inner_abi (schema 6, #268): a String or &str payload cannot be a field of the #[repr(C)] aggregate the wrapper returns, so it is lowered to the very <owner>_RustCallOwnedString { ptr, len, cap } buffer a string-returning wrapper hands back, released through <owner>_free_rust_string. Exactly the active payload is initialized, and exactly it must be released.

source
RustCall.ffi_payload_symbols — Method
ffi_payload_symbols(rust_type, abi, ctx; position, strict = FFI_STRICT[]) -> (surface, slot)

How one Result / Option payload is spelled in generated code: the Julia surface type the caller sees, and the C slot the aggregate field is declared with.

For a plain payload these are what the return-position helpers give (they differ only for char). For a lowered string payload the slot is CRustString — the buffer the wrapper wrote — and the surface type is String, decoded and released by RustCall._result_payload.

position names the payload for the boundary report (#454) — "Ok payload", "Err payload" or "Some payload" — and has no default: a payload is never the item's plain return, and the two payloads of one Result must not share a record.

source
RustCall.ffi_return_ccall_type — Method
ffi_return_ccall_type(rust_type; abi = "") -> Union{Type, Nothing}

The single Julia type to put in the return slot of a ccall for this Rust type, or nothing when the contract cannot describe the position (Cvoid for ()).

source
RustCall.ffi_return_contract — Method
ffi_return_contract(rust_type; abi = "", owner = nothing,
                    ownership = nothing, free_symbol = nothing) -> FFIContract

The contract for the return position. abi is the manifest Method.return_abi column (PR #274). See ffi_argument_contract.

A ccall has exactly one return type, so a multi-word value is not expanded here: ccall_types holds the single #[repr(C)] aggregate the wrapper returns (also available as aggregate_type), and layout holds its fields.

Stating ownership the spelling cannot express

A raw-pointer return defaults to :unknown ownership, because the spelling does not say: a generated constructor returns Box::into_raw (rustcall_julia_core::codegen), which Julia owns and must free, while another *mut T may point into memory Rust keeps. A consumer that has the metadata states it with ownership (and, where a release is required, the free_symbol that performs it):

c = RustCall.ffi_return_contract("*mut Point";
                                 ownership = :transferred_to_julia,
                                 free_symbol = "Point_free")
c.ownership    # :transferred_to_julia
c.free_symbol  # "Point_free"

The free-symbol invariant

A contract whose ownership is one of [FFI_OWNERSHIP_NEEDS_FREE] always names the free_symbol that releases the value; an owned value with no way to free it is the shape of #246 and #249 and is never recorded. Concretely:

  • declaring :owned_by_rust / :transferred_to_julia without a free_symbol is an ArgumentError;
  • a derived owned return with no symbol available (a lowered String return where the caller named no owner) reports :unknown ownership rather than an unfreeable :owned_by_rust.

owner is the function or struct name the wrapper belongs to. It supplies only the string release convention (<owner>_free_rust_string, emitted by rustcall_julia_core::codegen), so it stands in for free_symbol only on a lowered owned-string return (:ptr_len_cap). For a pointer return — where the releasing symbol is whatever the crate exports, e.g. Point_free — it does not apply and free_symbol must be given.

c = RustCall.ffi_return_contract("String"; abi = "string", owner = "shout")
c.abi             # :ptr_len_cap
c.ccall_types     # Type[CRustString]  — one return type
c.layout          # Type[Ptr{UInt8}, Csize_t, Csize_t]
c.ownership       # :owned_by_rust — Julia must free it through the owning library (#246)
c.free_symbol     # "shout_free_rust_string"
source
RustCall.ffi_return_slot_symbol_or_throw — Method
ffi_return_slot_symbol_or_throw(rust_type, abi, ctx; strict = FFI_STRICT[]) -> Union{Symbol, Expr}

The spelling of the C slot a return position occupies, where ffi_return_symbol_or_throw gives the Julia surface type it is read back as.

The two differ only for Rust char (a UInt32 Unicode scalar value read back as a Char), and a plain return never needs this: call_rust_function takes the surface type and does the lowering itself. It is needed where the value is a field of a #[repr(C)] aggregate — the CResult_<fn> / COption_<fn> payloads — because the field must be declared with the type Rust actually stored, and the conversion to the surface type happens after the call (convert_return).

source
RustCall.ffi_return_symbol_or_throw — Method
ffi_return_symbol_or_throw(rust_type, abi, ctx; strict = FFI_STRICT[], position = "return") -> Union{Symbol, Expr}

How the return position of ctx is spelled in generated code, as a Julia AST fragment ready to splice.

This is the single entry point every return site uses — the Expr generators of src/crate_bindings/crate_bindings.jl and the source-text emitters alike — so the two copies cannot drift apart again (#276 acceptance criterion 2). ctx is the signature the position belongs to ("mycrate::shout(s) -> String"), and it is what an unsupported type is reported against.

Multi-word returns are not handled here: a lowered String / &str return is a #[repr(C)] buffer with an owner, which the caller must take from ffi_return_contract so it also gets free_symbol. Asking for a single symbol for one is treated as unsupported.

The C slot is what generated code needs, which is not always the surface type: Rust char arrives as a UInt32 code point and must be converted, never reinterpreted as Julia's left-aligned UTF-8 Char.

source
RustCall.ffi_return_type_or_throw — Method
ffi_return_type_or_throw(rust_type, abi, ctx; strict = FFI_STRICT[]) -> Type

ffi_return_symbol_or_throw as a Type rather than as a spelling, for the sites that splice a concrete type into generated code instead of a name — src/ffi/structs.jl used to pass a Symbol through the call and re-resolve it at run time through a nine-entry table, which is how a u16 struct field became Any (#245).

source
RustCall.ffi_signature_context — Method
ffi_signature_context(name, arg_types, return_type; owner = nothing) -> String

The human-readable signature an unsupported type is reported against: "Struct::method(i32, String) -> Vec<f64>".

source
RustCall.ffi_slot_convert — Method
ffi_slot_convert(::Type{T}, x)

Convert a Julia value into the C slot type T the contract recorded for its position. Identity wherever the slot and the surface type agree; Rust char, whose slot is a UInt32 code point, is the one case that differs.

Used by the paths that convert at run time — monomorphized generics, which only learn their argument types after specialization. The generators splice the same conversion at macro-expansion time instead.

source
RustCall.ffi_slots — Method
ffi_slots(abi::Symbol) -> Vector{Type}

The C field layout of a multi-word ABI kind, in order. Direction-independent: it describes the value, not the calling convention. For how those words reach a ccall — separate argument slots, or one aggregate return type — see ffi_argument_contract / ffi_return_contract.

Scalar and pointer kinds depend on the concrete type and have no fixed layout here.

source
RustCall.ffi_string_argument — Method
ffi_string_argument(value, arg_name, context) -> String

The String a (ptr, len) argument slot is built from, checked to be valid UTF-8 before the pointer is handed to Rust (#246).

A Julia String is a byte vector: String([0xff, 0xfe]) is a perfectly ordinary value that is not UTF-8. The generated wrapper turns a string argument into slice::from_raw_parts plus String::from_utf8_lossy, so an invalid byte was silently replaced by U+FFFD and the Rust function ran on data the caller never wrote — a wrong answer with no error anywhere. The from_utf8_lossy on the Rust side stays as defence in depth (a &str built from invalid bytes is undefined behaviour, and nothing may reach it); this is the check that turns the same condition into a catchable Julia exception, at the call site, naming the argument that carries the bad bytes.

arg_name is the parameter as the Rust signature spells it and context the function or method it belongs to, so the message points at one argument of one function rather than at "a string". A caller that has only the position — a monomorphized generic, whose FunctionInfo records ABIs but not names — passes an Integer instead, and the message says argument #2.

source
RustCall.ffi_struct_free_symbol — Method
ffi_struct_free_symbol(struct_name::AbstractString) -> String

The destructor of a #[julia] struct: <Struct>_free, matching what deps/rustcall_julia_core/src/codegen.rs emits (crate_free_fn and its inline twin).

One place, because four call sites used to build this string by hand (src/ffi/structs.jl twice, src/crate_bindings/crate_bindings.jl for the in-memory module and for the emitted template) and a finalizer that calls the wrong symbol is a leak at best (#249, #277 Phase B4).

source
RustCall.ffi_surface_type — Method
ffi_surface_type(rust_type::AbstractString) -> Union{Type, Nothing}

The Julia type a caller sees for this Rust type, or nothing when unknown.

source
RustCall.ffi_type_expr — Method
ffi_type_expr(T::Type) -> Union{Symbol, Expr}

Render a Julia type as an AST fragment that names it: :Int32, :Cvoid, :(Ptr{Ptr{Int32}}). Parametric Ptrs are rendered recursively so the result is always valid Julia, never a Symbol of a printed type.

Cvoid is spelled :Cvoid rather than :Nothing, matching what the existing generators emit.

source
RustCall.register_ffi_struct — Method
register_ffi_struct(T::Type; repr_c::Bool = true) -> Type

Assert that values of T may be passed to and from Rust by value, because the Rust type they correspond to is declared #[repr(C)] and its fields match T's in order and in type.

This is the opt-in issue #245 asks for. Without it, @rust f(x) with an aggregate x raises rather than assuming the layouts agree: Rust's default repr(Rust) layout is unspecified, so an unannotated Julia struct that "works" today can be silently reordered by the next rustc.

The assertion is recorded as a method of ffi_by_value_layout, defined in the module that owns T. Calling this at a package's top level therefore survives precompilation — the method is stored in that package's cache image and reinstated when it is loaded, in every later session:

module MyPkg
using RustCall

struct Point   # matches #[repr(C)] pub struct Point { x: f64, y: f64 }
    x::Float64
    y::Float64
end
RustCall.register_ffi_struct(Point)
end

You do not need this for:

  • scalars, pointers, Cstring, Char, Bool — their ABI is their width;
  • the struct wrappers RustCall generates from a #[julia] struct (RustStructInfo, src/ffi/structs.jl), which cross the boundary as an opaque handle, never as a field-by-field copy;
  • RustCall's own #[repr(C)] mirrors: CRustString, CRustSlice and friends have ffi_by_value_layout methods here, and the CResult_<fn> / COption_<fn> aggregates the wrapper generators emit subtype FFIByValue.

repr_c = false is rejected: there is no layout to assert. The keyword exists so the call site states what is being claimed.

Concrete types only

T must be a concrete, immutable, isbitstype struct. A UnionAll or an abstract type is rejected: instantiations of Point{T} do not share a layout — a type parameter changes field sizes, alignment and even ABI register classes — and subtypes of an abstract type Shape{T} share even less. Registering a family would license values you never matched against a Rust struct, which is the fail-open behaviour this opt-in exists to remove. Register each concrete type you actually pass: register_ffi_struct(Point{Float64}) says exactly that, and says nothing about Point{Int32}.

Not precompile-safe for a type Julia owns

parentmodule(Tuple{Int32, Float64}) is Core, and there is no method RustCall may add there — so the method lands in RustCall itself, which is a cross-module mutation of a dependency and is not replayed from a downstream package's precompile cache. The assertion would hold in the session that compiled the package and be gone in every one after it.

Use @register_ffi_struct at a package's top level. It expands in the calling module and is precompile-safe for every T. This function is the runtime form: fine in the REPL, in a script, or inside a function.

See also @register_ffi_struct, unregister_ffi_struct, ffi_by_value_registered, ffi_by_value_layout.

source
RustCall.unregister_ffi_struct — Method
unregister_ffi_struct(T::Type) -> Bool

Take back the register_ffi_struct assertion for T. Returns whether there was one to take back.

It deletes the ffi_by_value_layout method that was defined for exactly T — register_ffi_struct accepts only concrete types, so that is the one Type{T} method — and nothing else: withdrawing Point{Float64} leaves a separate Point{Int32} assertion standing, and a covering method RustCall defines for its own mirrors is never matched. An assertion made in a previous session (restored from a precompile cache) is withdrawn just as well: the method is found by reconstructing its signature, not by remembering it.

Deleting a method invalidates code that dispatched through it, so this is not something to do in a loop; it is a correction, made by a test or by a user who changed their mind. It uses the same method-definition gate as register_ffi_struct, without holding STATE.

source
RustCall.@register_ffi_struct — Macro
@register_ffi_struct T

Assert that values of T may cross the boundary by value — the same claim register_ffi_struct(T) makes, recorded in a way that survives this module's precompilation whatever T is.

Use this at a package's top level. It expands to a method definition:

RustCall.ffi_by_value_layout(::Type{T}) = :repr_c

written in the calling module, so Julia stores it in that module's cache image and reinstates it on load, like any other method the package defines.

Why the macro exists

register_ffi_struct(T) is a function and cannot define a method in its caller's module; it uses parentmodule(T) instead. For a struct the package itself defines, that is the caller's module and everything works. For a type Julia owns — a Tuple{Int32, Float64}, whose parentmodule is Core — there is no such home, the method lands in RustCall, and a cross-module mutation of a dependency is not replayed from a downstream package's cache: the assertion would hold in the session that compiled the package and be gone in every one after it (#245 review). A macro has the caller's module by construction and has neither problem.

module MyPkg
using RustCall

struct Point
    x::Float64
    y::Float64
end

@register_ffi_struct Point
@register_ffi_struct Tuple{Int32, Float64}
end

The same rules apply as to the function: concrete, immutable, isbitstype struct types only, and the Rust type it mirrors must be #[repr(C)]. A UnionAll or an abstract type raises an ArgumentError where the macro's expansion runs — during precompilation, if that is where you wrote it, so a bad assertion fails the build rather than the first call.

See also register_ffi_struct (the runtime form), unregister_ffi_struct, ffi_by_value_layout.

source

Type translation (src/ffi/typetranslation.jl)

RustCall.juliatype_to_rust — Method
juliatype_to_rust(julia_type::Type) -> String

Convert a Julia type to the corresponding Rust type name.

Examples

juliatype_to_rust(Int32)   # => "i32"
juliatype_to_rust(Float64) # => "f64"
juliatype_to_rust(Bool)    # => "bool"
juliatype_to_rust(String)  # => "*const u8" (for FFI)
juliatype_to_rust(Cstring) # => "*const u8"
source
RustCall.rusttype_to_julia — Method
rusttype_to_julia(rust_type) -> Type

The Julia type a Rust type spelling maps to, as a Symbol or a String.

A thin shim over the FFI contract (src/ffi/ffi_contract.jl), which is the single source of truth since #276: this had its own 26-row table, and the two disagreed. Raises for a spelling the contract does not cover, rather than guessing.

Two spellings changed meaning with the migration, deliberately (#246):

spellingwasis
"str"CstringRustStr
"*const u8"CstringPtr{UInt8}

A Rust str is an unsized UTF-8 slice reached through a (ptr, len) fat pointer and a *const u8 is a plain byte pointer; neither is the NUL-terminated Cstring the old table claimed. Use ffi_argument_contract / ffi_return_contract when you need the calling convention rather than just the Julia type.

Examples

rusttype_to_julia(:i32)          # => Int32
rusttype_to_julia("*const i32")  # => Ptr{Int32}
rusttype_to_julia("String")      # => RustString
source