External crates

@rust_crate bindings to an existing crate. See External Crate Bindings for the user-facing guide; hot reload of a crate's library is on Hot reload API (guide: Hot Reload), and PyO3 extension modules are on PyO3 crates.

Crate bindings

src/crate_bindings/crate_bindings.jl includes the components below into the RustCall module. Public names and the written-bindings format are shared across them.

The explicit-binding runtime contract is:

  • @rust_crate and RustCall.load_crate_bindings return a RustCall.CrateBindings value.
  • Property access preserves non-function bindings such as types and constants.
  • Callable exported functions remain proxy-backed so calls stay world-age-safe.
RustCall.CrateBindingOptions — Type
CrateBindingOptions

Options for binding generation.

Fields

  • output_module_name::Union{String, Nothing}: Name for the generated module (default: crate name)
  • output_path::Union{String, Nothing}: Path to write generated Julia code
  • use_wrapper_crate::Bool: Whether to create a wrapper crate for building
  • build_release::Bool: Build in release mode
  • cache_enabled::Bool: Enable caching of compiled libraries
source
RustCall.CrateInfo — Type
CrateInfo

Information about a Rust crate for binding generation.

Fields

  • name::String: Crate name from Cargo.toml
  • path::String: Path to the crate root directory
  • version::String: Crate version
  • dependencies::Vector{DependencySpec}: Crate dependencies
  • julia_functions::Vector{RustFunctionSignature}: Functions marked with #[julia]
  • julia_structs::Vector{RustStructInfo}: Structs marked with #[julia]
  • source_files::Vector{String}: Paths to .rs source files
  • pyo3_functions::Vector{RustFunctionSignature}: #[pyfunction] / #[pymodule] items found by the PyO3 scan of #275 — items the crate does not mark with a RustCall attribute. Nothing wraps them yet; each carries a skip_reason (empty when a Phase-2 wrapper crate could wrap it).
  • pyo3_structs::Vector{RustStructInfo}: #[pyclass] items, likewise.
source
RustCall._crate_manifest — Method
_crate_manifest(crate_path; cfg = :lenient, cfg_text = nothing, build_env = nothing,
                allow_cargo = true) -> (cargo_toml, source_files, manifest)

The extractor's crate-mode manifest of the crate at crate_path, read the way scan_crate reads it: the crate's module tree from its library root, under the crate's edition. Shared by scan_crate and boundary_report (#441).

source
RustCall._crate_scan_inputs — Method
_crate_scan_inputs(crate_path, cargo_toml, source_files) -> (lib_root, tree_files)

The files the extractor is given for a crate, and the root its module tree hangs off.

A [lib] path outside src/ is not in source_files, so the root has to be added even when the per-file #[julia] pass never sees it. Factored out because scan_crate and the #275 Phase-2 wrapper generator must be handed the same list: the wrapper is generated from a re-run of the very scan scan_crate reported, and a different file list would let the two disagree about which items exist.

source
RustCall._package_field — Method
_package_field(crate_path, cargo_toml, key, fallback; allow_cargo = true, env = ENV)

The value of the [package] field key of cargo_toml, with { workspace = true } inheritance resolved from the workspace root's [workspace.package] table by reading that manifest.

A member that inherits edition or version is a common layout, and reading the root is what keeps the probe-free scan of #425 from running cargo metadata for it. When the root cannot be found or does not declare the field, fallback is what a caller that may not invoke Cargo gets; with allow_cargo = true Cargo is asked instead, which remains the authority for the layouts a manifest read cannot decide.

source
RustCall.crate_lib_root — Method
crate_lib_root(crate_path, cargo_toml) -> Union{String, Nothing}

The crate's library root source file: [lib] path when the manifest sets one, otherwise Cargo's default src/lib.rs. nothing when neither exists (a binary-only crate).

This is the file the PyO3 scan of #275 follows the module tree from, so a crate that puts its root somewhere else — [lib] path = "src/core/lib.rs", or a path outside src/ altogether — is resolved from the right place instead of having every source file treated as its own root.

source
RustCall.create_wrapper_crate — Method
create_wrapper_crate(info::CrateInfo, opts::CrateBindingOptions) -> String

Create a wrapper crate that depends on the target crate and re-exports #[julia] items.

Returns

  • String: Path to the created wrapper crate directory
source
RustCall.rustcall_runtime_crate_path — Method
rustcall_runtime_crate_path() -> String

This installation's deps/rustcall_julia_macros, the crate every generated wrapper names for its quiet-panic boundary guard (PanicHook::Runtime, #304).

Every Cargo.toml RustCall writes for a crate that contains generated wrappers declares this dependency, and they all have to declare the same one: two packages of this name from different sources would each bring a copy of #[no_mangle] __rustcall_install_panic_hook into one cdylib, which is a duplicate symbol at link time. A crate of the user's that also uses #[julia] therefore has to point at this same directory — docs/src/panics.md says so.

Raises when the directory is missing rather than falling back to a registry version. The generated source names ::rustcall_julia_macros unconditionally, so a manifest without this entry does not compile, and a rustc resolution error naming a crate the user never wrote is a much worse way to learn that this installation is incomplete.

source
RustCall.scan_crate — Method
scan_crate(crate_path::String) -> CrateInfo

Scan a Rust crate and extract information about #[julia] marked items.

Arguments

  • crate_path::String: Path to the crate root directory (containing Cargo.toml)

Returns

  • CrateInfo: Information about the crate including functions and structs

Example

info = scan_crate("/path/to/my_crate")
println("Found $(length(info.julia_functions)) Julia functions")
source
RustCall.CrateBuildRecord — Type
CrateBuildRecord

Everything a build of a @rust_crate library was made from — and therefore everything a hot reload must reproduce before it may publish another image under that library's registry name (#474):

  • crate_dir — the crate the module was generated from (absolute);
  • lib_name — the registry name the library is loaded as (_LIB_NAME);
  • release, features, default_features — the profile and the feature selection (crate_build_options);
  • kind — how the library was produced: :direct (the crate is its own cdylib), :wrapper (a generated wrapper crate around an rlib) or :pyo3_wrapper (#275);
  • build_env, cargo_config, toolchain — the part of the artifact identity that is not a file: the allowlisted variables, the effective Cargo configuration's digest and the toolchain fingerprint ("" when it could not be read, which then is not compared);
  • python — whether build_env carries the Python selection of a module that links libpython (_recorded_build_env(; python)).

A generated module holds exactly one, as _BUILD_RECORD, emitted by both crate emitters from one call (crate_build_record); _LIB_NAME is read from it. Hot reload takes every rebuild input from it and nothing else: the module form of enable_hot_reload_for_crate reads it once and compares caller arguments against it (_check_record_arguments), and every reload compares the current environment with it (_build_record_mismatch) before building. Immutable, so a reload cannot drift from what the module was generated for.

source
RustCall._build_env_changed_message — Method
_build_env_changed_message(lib_name, crate_path, changed, origin) -> String

The one diagnostic for a generated crate module whose recorded build environment no longer matches (#531). What went wrong is the same for both origins; the remedy is not. A @rust_crate module is rebuilt when its package is precompiled again. A file written by write_bindings_to_file records the environment in its own source (_BUILD_RECORD), so re-precompiling reads the same record and fails the same way: the file must be written again, after which a package that includes it re-precompiles on its own.

source
RustCall._build_env_changes — Function
_build_env_changes(recorded, crate_path, recorded_cargo_config = "",
                   recorded_toolchain = ""; python = false,
                   snapshot) -> Union{Nothing, Vector{String}}

What differs between the build environment a generated module recorded (the build_env, cargo_config and toolchain of its CrateBuildRecord) and the one snapshot holds — every value, the Cargo configuration and every interpreter read from it, never from ENV (#481): the names of the changed allowlisted variables, plus <effective Cargo configuration> and <Rust toolchain> when those moved. nothing when the current environment cannot be read. The one comparison both a module's __init__ (_warn_if_build_env_changed) and a hot reload of that module (_build_record_mismatch) make.

source
RustCall._build_record_mismatch — Method
_build_record_mismatch(record::CrateBuildRecord, snapshot) -> Vector{String}

What differs between the environment record was built under and the one snapshot holds (_build_env_changes): the changed variables, <effective Cargo configuration>, <Rust toolchain>. Empty when nothing does, or when the environment cannot be read. A rebuild passes the snapshot its subprocesses are then derived from (_record_build_subprocess_env), so the check and the build see one environment (#481).

source
RustCall._crate_precompile_dependencies — Method
_crate_precompile_dependencies(crate_path) -> Vector{String}

Every path on disk that the crate's artifact identity is computed from — files and the directories that hold them — as absolute paths.

A module generated in memory by @rust_crate may be compiled into a package's precompile image (#339), and Julia decides that image is stale from what the module declared with Base.include_dependency. Declaring only the built library is not enough: the library is content-addressed, so editing src/lib.rs produces a different cache path and leaves the old file untouched — the image would still be valid and the package would go on calling the previous build (#339 review). Declaring the inputs instead makes an edit to the crate invalidate the image, which is what sends the next using back through @rust_crate.

The list is deliberately the same set compute_crate_hash reads: the crate directory's own input files, every local path dependency's, the effective Cargo configuration, the contents of PYO3_CONFIG_FILE when one is set (both the wrapper path and a plain build of a crate that depends on pyo3 read it), the workspace root's manifest and lockfile when the crate is a workspace member, and a library root that lives outside the package directory ([lib] path = "../shared/lib.rs").

Directories are in the list because files alone cannot see an addition. include_dependency tracks a directory by join(readdir(path)), so declaring each directory that holds an input catches a new file appearing beside the ones that were there — a source file a build script globs, or a .cargo/config.toml created where none existed — which changes crate_content_digest and therefore the artifact, while touching no file the image already knew (#339 review). Two gaps remain, both deliberate: a .cargo/ created in an ancestor of the crate is not seen, and neither is one appearing in CARGO_HOME, because tracking those directories would mean tracking directories whose contents churn for unrelated reasons and re-precompiling the package for each.

A path that is not on disk is dropped — include_dependency raises on an unreadable path, and a missing input already changes the digest through crate_content_digest.

source
RustCall._plain_crate_build_env — Method
_plain_crate_build_env(record::CrateBuildRecord) -> Vector{Pair{String, String}}

The environment part of a plain crate's artifact identity (compute_crate_hash, crate_library_name), read from record rather than from ENV: the same values _plain_crate_build_env() reads, under the same names and in the same order, so the cache key, the registry name and the build all come from one snapshot (#474 review).

source
RustCall._pyo3_build_interpreter — Method
_pyo3_build_interpreter() -> (interpreter::String, fingerprint::String)

The interpreter pyo3's build script selects when a crate that depends on pyo3 is built as it stands (the plain path, no wrapper), and what that interpreter reports about itself (_python_interpreter_fingerprint): ("", "") when pyo3's own configuration (PYO3_CROSS_LIB_DIR, the lib_dir of a PYO3_CONFIG_FILE) decides and no interpreter is consulted; else PYO3_PYTHON as given; else the sys.executable of the first python3 / python on PATH. The same order pyo3 uses — RustCall's own selectors (RUSTCALL_PYTHON_LIBDIR, CondaPkg) play no part in a build RustCall does not wrap. Part of a plain build's key and of its module's load-time record, so a PATH that finds another Python, or a shim retargeted under one name, is a different artifact and a reported change rather than a library configured for the previous ABI (#339 review). One short subprocess; "" for both when no interpreter can be run.

source
RustCall._python_config_consulted — Method
_python_config_consulted() -> Bool

Whether python_link_source() actually asks python3-config / python-config for the link directory: the implicit case (_python_link_is_implicit), minus the one step it takes before either command — on macOS a framework build of the interpreter answers with its framework prefix, and neither command is run. For such a Python the commands are not inputs: recording them warned about a changed python3-config on PATH, and tracking its file rebuilt the package, while the wrapper's link directory and identity had not moved (#339 review). Mirrors the python3 / python loop of python_link_source() step for step, and is false when no interpreter is found at all — then nothing is consulted.

source
RustCall._python_config_selections — Method
_python_config_selections() -> Vector{Pair{String, String}}

The python3-config and python-config that python_link_source() would run for the implicit link directory — the first of each on PATH, "" when there is none — in the order _python_config_libdir() tries them. Both are recorded and compared for a PyO3 wrapper module, and both files tracked, because PATH resolving either to another installation changes the rpath the wrapper is linked with while the interpreter, and everything else recorded, stays the same. Recording the fallback even when the first command answers is deliberate: which one answers is only known by running them, and a load must not (#339 review).

source
RustCall._python_link_is_implicit — Method
_python_link_is_implicit() -> Bool

Whether python_link_source() would reach its last step — the interpreter and python3-config / python-config found on PATH — rather than be decided by pyo3's own configuration, PYO3_PYTHON, RUSTCALL_PYTHON_LIBDIR or CondaPkg. Only then are the config commands inputs of the wrapper (#339 review).

source
RustCall._python_resolved — Method
_python_resolved(command) -> String

The sys.executable that command reports, or command itself when it cannot be run; "" for "". A bare python3 or a shim is one path on PATH and another underneath, and only the interpreter can say which (#339 review).

source
RustCall._python_selection — Method
_python_selection() -> String

Which interpreter python_link_source() would pin, decided the way it decides it: PYO3_PYTHON when set, else CondaPkg's when that package is loaded, else the sys.executable the first python3 / python on PATH reports (_python_executable_on_path). "" when there is none.

Recorded for a PyO3 wrapper module so __init__ can tell that the selection moved — PYO3_PYTHON unset and PATH now finding a different interpreter — which tracking the selected interpreter's files cannot see, because the old one is still there, unchanged (#339 review). The implicit case asks the interpreter rather than trusting Sys.which: a pyenv or asdf shim keeps one path on PATH while its project selection moves the real interpreter, and only sys.executable says which one that is. One short subprocess per load of a PyO3 wrapper module; a plain module never runs it.

source
RustCall._record_build_subprocess_env — Method
_record_build_subprocess_env(record::CrateBuildRecord, snapshot) -> Dict{String, String}

The environment every Cargo subprocess of a build described by record runs under — the cfg probe and the build of @rust_crate, write_bindings_to_file and a hot reload — derived from the record over snapshot, the build's one snapshot of ENV, so the build is the one the record describes even if another task changes ENV meanwhile (#474 review, #481):

  • every variable artifact_build_env_captured accepts is removed from the snapshot and the record's own values are put back (RUSTFLAGS, CARGO_PROFILE_*, RUSTUP_TOOLCHAIN, PYO3_*, a build script's CC, ...);
  • the interpreter pyo3's build script would pick — recorded as <pyo3 build interpreter>, found on PATH when PYO3_PYTHON is unset — is pinned in PYO3_PYTHON, so a PATH changed after the record was taken cannot select another Python for the build;
  • the Cargo configuration CARGO_HOME selects is checked against the record's digest on this environment, and a different one is refused.

The rest of the snapshot (PATH, CARGO_HOME, ...) is what the build needs to run. Other <...> entries of record.build_env are digests, not variables.

source
RustCall._recorded_build_env — Method
_recorded_build_env(snapshot; python = false, link_source = nothing) -> Vector{Pair{String, String}}

The environment a generated module records and compares at load time: the artifact_build_env allowlist, plus RustCall's own selectors that decide the artifact without being in that allowlist — RUSTCALL_PYTHON_LIBDIR, which python_link_source() gives precedence and pyo3_link_rustflags() folds into a wrapper's identity and rpath (#339 review). One function for both sides, so what is recorded and what is compared cannot drift.

Read from snapshot — variables, PATH lookups and every interpreter it runs — so a record and the build it describes see one environment (#481). The form without it takes a snapshot of ENV now.

link_source, when given, is the (libdir, interpreter, fingerprint) a PyO3 wrapper's plan was made with — the values its artifact key was computed from — and the record takes the link directory, the selection and the fingerprint from it rather than asking the interpreter again. A second answer is a second moment: an interpreter replaced in place between the two recorded a Python the library was not built for, and the load-time check then accepted the wrong wrapper (#485 review). Comparing (_build_env_changes) passes none, so the current interpreter is asked, which is the point of the check.

source
RustCall._verify_build_interpreter — Method
_verify_build_interpreter(snapshot, interpreter, fingerprint, what)
_verify_build_interpreter(record::CrateBuildRecord, snapshot)

Refuse a build whose Python interpreter was replaced in place while it ran (#481). A build that configures pyo3 for an interpreter is keyed and recorded by that interpreter's path and by what it reported about itself (_python_interpreter_fingerprint), asked before the build. The path is pinned in PYO3_PYTHON, so PATH cannot select another one — but the file behind the path can change (an upgrade, a retargeted shim), and the build would then be configured for a Python its key and record do not name. So the interpreter is asked again, under the same snapshot, once the build is done and before the library is cached or published, and a different answer is a RustError.

Nothing is checked when interpreter or fingerprint is "" — no interpreter was consulted, or it could not be run when the build was planned. The record form reads <pyo3 build interpreter> / <pyo3 build fingerprint>: the interpreter a plain build's pyo3 configures itself for.

source
RustCall._warn_if_build_env_changed — Function
_warn_if_build_env_changed(recorded, crate_path, lib_name; strict = false,
                           origin = :rust_crate)

Check whether the environment that decides this crate's artifact is the one it was built under. The generated @rust_crate module uses strict = true and refuses to load a precompiled image whose non-file inputs changed; the default is retained for diagnostic callers and emits the historical warning.

origin says where the module came from, and so which remedy the message names (_build_env_changed_message, #531): :rust_crate for the module @rust_crate builds, :bindings_file for a file write_bindings_to_file wrote. The in-memory module's __init__ names its origin; a written file makes the origin-less record call, which is read as :bindings_file (_crate_init_prologue).

Julia invalidates a precompile image from files, and Base.include_dependency is the only lever a generated module has. Part of the artifact identity is not a file: RUSTFLAGS, PYO3_PYTHON, a PYO3_CONFIG_FILE pointing somewhere else, and the rest of the allowlist artifact_build_env captures. Change one of those and every file the image tracks is still byte-for-byte what it was, so Julia keeps the image and the module loads a library built for the other environment — silently, and with a Python preload plan to match (#339 review).

Nothing here can invalidate the image; what it can do is refuse to be silent. The module records the values it was generated under and compares them at load time, which is cheap — the allowlist is read from one snapshot of ENV taken here, no probe, no build. The fix it names is the one that works for the module's origin: re-precompiling a package rebuilds a @rust_crate module under the current environment, but a written file carries its record in its own source, so it must be written again.

source
RustCall.crate_build_options — Method
crate_build_options(; release, features, default_features, kind) -> NamedTuple

The build a generated @rust_crate module was made from, as the module records it in its CrateBuildRecord (_BUILD_RECORD): the profile, the feature selection, and kind — how the library was produced (:direct, the crate built as its own cdylib; :wrapper, a generated wrapper crate around an rlib; :pyo3_wrapper, the PyO3 wrapper of #275). Hot reload rebuilds from it (enable_hot_reload_for_crate), so a reload publishes a build with the same #[cfg]s under the module's registry name rather than a release build with default features (#461 review).

source
RustCall.crate_build_record — Method
crate_build_record(crate_path, lib_name; build_options, python = false,
                   snapshot, link_source = nothing) -> CrateBuildRecord

The record of a build of crate_path made under snapshot: the given build options, plus the build environment, Cargo configuration and toolchain as the snapshot has them. What both crate emitters record (one call, one value), and what the path form of enable_hot_reload_for_crate constructs for a library it has no module of. snapshot is required: a record read from ENV at its own moment described a build made under another one (#481). link_source is a PyO3 wrapper plan's link source (_recorded_build_env); the wrapper path records through pyo3_wrapper_build_record.

source
RustCall._crate_init_prologue — Method
_crate_init_prologue(origin::Symbol)

What a generated crate module's __init__ does before it loads its library, in order, shared by both emitters: the in-memory module splices these expressions (origin = :rust_crate) and emit_crate_module_code prints them (:bindings_file), so a written file cannot drift from @rust_crate (#474 review). Only the in-memory check names its origin: a written file is loaded by every RustCall of its format line, so it makes only calls the oldest of them accepts — the origin-less one, which the check reads as a written file's (#531). First the strict build-environment check against _BUILD_RECORD — a precompiled module refuses to load a library built under another RUSTFLAGS, PYO3_PYTHON, Cargo configuration or toolchain (#339, #355) — then the mirror registration, which must precede the load (#277).

source
RustCall.emit_crate_module — Method
emit_crate_module(info::CrateInfo, lib_path::String; module_name::Union{String, Nothing}=nothing) -> Expr

Generate a Julia module expression containing bindings for the crate.

Arguments

  • info::CrateInfo: Crate information from scan_crate
  • lib_path::String: Path to the compiled shared library

Keyword Arguments

  • module_name::Union{String, Nothing}: Name for the module (default: crate name with first letter capitalized)

Returns

  • Expr: A module expression that can be evaluated
source
RustCall._CRATE_MODULE_HELPERS — Constant
_CRATE_MODULE_HELPERS

The names a generated crate module defines once, at its root, and every submodule imports from its parent: the library record and the snapshot constructors (_call_target, _vec_target, _ctor_target, _struct_generation), the symbol cache and the panic guard. One definition per module tree, so a reload swaps the image for every submodule at once.

source
RustCall._CRATE_MODULE_ROOT_CONSTANTS — Constant
_CRATE_MODULE_ROOT_CONSTANTS

The other names a generated crate module binds at its root — the library path, the build record, the preload list, the pin flag, the crate's tracked inputs, the symbol cache and __init__ — which a Rust item or module may not take. test/test_hot_reload_record.jl collects every root binding either emitter actually defines and asserts it is reserved here or in _CRATE_MODULE_HELPERS, so a constant added to an emitter without reserving its name fails (#463).

source
RustCall.ModuleNode — Type
ModuleNode

One module of a crate's binding layout: the items whose module_path is path, and the modules below it. The root has an empty path.

The generated Julia module mirrors the Rust module tree: an item at the crate root is bound where it always was, an item in mod a is bound in a submodule a (bindings.a.run(), bindings.a.C), so two runs or two struct C in different modules — which the symbol scheme keeps apart in the library — are kept apart in Julia as well. A module that only contains other modules is still emitted, so the path in Julia is the path in Rust.

source
RustCall._check_module_names — Method
_check_module_names(tree::ModuleNode)

Refuse a layout Julia cannot define. Rust keeps values, types and modules in separate namespaces, so a crate may have both #[julia] fn a() and #[julia] mod a { ... }; Julia has one namespace per module, and the generated parent would define function a and then module a — a constant-redefinition error that takes the whole bindings module down (#300 review). Every child module name is therefore checked against everything its parent binds: free functions, struct types, every method name (static or instance — both become functions of the parent), field accessors (get_<f>, set_<f>!), the helpers every generated module defines (_call_target, _LIB_GEN, ...) and the eval / include Julia defines in every module (_JULIA_MODULE_OWN_NAMES). Within one node a struct's type name must not repeat a function-like binding either (fn C + struct C).

Nothing else is reserved: the generated code reaches Base, Core and RustCall through GlobalRefs or rustcall′ aliases no Rust name can spell (#528), so an item named Base, RustCall, String or getfield shadows nothing it uses. Module segments must also spell a Julia identifier (_julia_module_name). The error names both sides and the fix.

source
RustCall._crate_wrapper_exprs — Method
_crate_wrapper_exprs(tree::ModuleNode) -> (func_defs, struct_defs, submodules)

The wrappers of a crate as @rust_crate binds them: the root's function wrappers, its struct definitions (with the root's static-method collisions, #323), and one module expression per Rust module below (#300). emit_crate_module splices them into the generated module; boundary_report runs them in collecting mode (#454), so the surface the report examines is the surface the module defines.

source
RustCall._function_declarations — Method
_function_declarations(node::ModuleNode; accessors) -> Vector{String}

Every function name the emitters define in node's module that is not a type or a submodule (free functions, static and instance methods, and with accessors the expression emitter's get_<f> / set_<f>!), read off julia_definitions. Each is declared function <name> end before any method, so it is a new function of this module whatever it is called: a method defined under a name the module only sees through using Base — fn Int32, fn String — would otherwise extend Base's constructor (#528).

source
RustCall._julia_module_name — Method
_julia_module_name(segment::AbstractString) -> String

The Julia name of a Rust module segment: julia_binding_name, the rule every item kind follows (#514). A raw identifier (r#type) loses its prefix — # would start a comment in the written file — and a Julia keyword gets a trailing underscore (mod r#do → do_, mod end → end_), so the submodule parses and can be reached by name. The layout checks compare these names, so mod r#do beside mod do_ is refused.

source
RustCall._module_tree — Method
_module_tree(info::CrateInfo) -> ModuleNode
_module_tree(functions, structs) -> ModuleNode

Arrange a crate's items by module_path. Children are sorted by name, so the layout — and a file written by write_bindings_to_file — is deterministic whatever order the manifest listed the items in.

source
RustCall._rename_crate_tree — Method
_rename_crate_tree(tree; strict) -> ModuleNode

tree with every parameter named against what both crate emitters make of its module's items — the expressions @rust_crate evaluates and the source text write_bindings_to_file writes, parsed (#526) — so the two agree on every name, and each is free of every name the other's definitions use.

source
RustCall._rename_tree_parameters — Method
_rename_tree_parameters(tree, emit) -> ModuleNode

tree with every module's items renamed by _rename_parameters against what emit(functions, structs) makes of that module's items (#526).

source
RustCall._submodule_code — Method
_submodule_code(node::ModuleNode; strict) -> Vector{String}

Source-text twin of _submodule_exprs for emit_crate_module_code.

source
RustCall._submodule_exprs — Method
_submodule_exprs(node::ModuleNode) -> Vector{Expr}

The module <name> ... end expressions for the children of node, each with the prelude, the helpers imported from the parent, its own items and its own children. Static-method name collisions (#323) are decided per module, since that is the scope a bare name(args...) definition lives in.

source
RustCall._target_cache_name — Method
_target_cache_name(kind, symbol) -> Symbol

The name of the const a generated call site keeps its snapshot in (#253).

Why a name at all

@rust and the #[julia] wrappers splice their CallTargetCache straight into the expansion, where it needs no name and cannot collide. A @rust_crate module has no such option: write_bindings_to_file emits the same module as source text, and a live object has no source spelling. Each call site therefore declares its cache next to the wrapper that uses it, in both emitters.

Why (kind, symbol) is unique

kind names the emitter, not the tuple shape: :fn a free function, :m a method wrapper, :free a struct's destructor, :acc a get_x / set_x! helper, :prop a getproperty / setproperty! branch. Each of those emits a given FFI symbol at most once per module — a field's getter appears in the accessor and in getproperty, which is exactly why those two are different kinds rather than one — so no two call sites ever ask for the same name, and const is never declared twice.

Why the name cannot be a user's

A generated module also binds whatever the crate exports: a function foo becomes Julia's foo. A cache spelled _TC_fn_rustcall_foo would therefore collide with a crate that exports a Rust function of exactly that name — legal Rust, and the module would then either redefine a const or define methods on a CrateTargetCache, taking the whole bindings module down (#253 review).

# is what makes that impossible rather than merely unlikely: it cannot appear in a Rust identifier, and so cannot appear in a name the crate contributes. Julia is happy to bind it — var"#TC#fn#rustcall_foo" — which is also how Base.show spells the symbol, so both emitters write the same characters.

source
RustCall._target_cache_ref — Method
_target_cache_ref(kind, symbol) -> String

How _target_cache_name(kind, symbol) is spelled in Julia source: var"#TC#fn#rustcall_add". The AST emitter splices the Symbol and never needs this; the file emitter writes text and does.

It is the same spelling Base.show gives that symbol, so the two emitters' output stays comparable character for character — which is what test/test_crate_bindings.jl checks them with.

source
RustCall.MethodPayloadPlan — Type
MethodPayloadPlan

Everything both @rust_crate method emitters need for a Result / Option return (#268): the name of the #[repr(C)] mirror, its definition, the surface types the caller sees, and the <owner>_free_rust_string an owned-string payload is released through (empty when no payload is one).

source
RustCall._check_not_freed — Method
_check_not_freed(obj, type_name::String)

Check that a wrapped Rust object has not been freed, raising rather than letting the call dereference C_NULL inside Rust.

The generated @rust_crate modules and the emitted bindings files import this name, so it stays; the implementation is check_not_freed (src/ffi/structs.jl), which the inline #[julia] structs use as well. One rule, one message, both flavours (#249, #277 Phase B4).

source
RustCall._crate_field_read — Method
_crate_field_read(info, field_name, field_type, ptr_expr, self_ptr_expr) -> Expr

How a crate-mode field getter is read: the one decision, from ffi_return_contract. A field whose manifest abi is "string" comes back as an owned <Struct>_RustCallOwnedString buffer released through the contract's free_symbol; every other field is a single C slot.

source
RustCall._crate_field_read_source — Method
_crate_field_read_source(info, field_name, field_type, ptr_var, self_ptr) -> String

Source-text counterpart of _crate_field_read for the file emitter.

source
RustCall._crate_field_write — Method
_crate_field_write(info, field_name, field_type, setter_symbol, self_ptr_expr, value_expr) -> Expr

The call a field setter makes, with the value converted to the field's surface type first. call_rust_function derives the ccall signature from the runtime type of each argument, so passing value through as it came meant set_scale!(obj, 3) on an f64 field put an Int64 in an integer register while Rust read an f64 from a floating-point one — garbage stored, or worse (#307 review). The type is the one the getter reads the field back as (ffi_return_symbol_or_throw), so the two directions agree, and the conversion raises on a value that does not fit rather than reinterpreting it.

source
RustCall._crate_field_write_source — Method
_crate_field_write_source(info, field_name, field_type, setter_symbol, self_ptr, value; strict) -> String

Source-text counterpart of _crate_field_write for the file emitter.

source
RustCall._generate_option_function_wrapper — Function
_generate_option_function_wrapper(func, option_info, arg_syms, converted_args) -> Expr

Generate a Julia wrapper for a function that returns Option<T>. The wrapper will return RustOption{T}.

source
RustCall._generate_property_accessors — Method
_generate_property_accessors(info::RustStructInfo) -> Union{Expr, Nothing}

Generate Base.getproperty and Base.setproperty! methods for natural field access. This allows obj.field and obj.field = value syntax.

source
RustCall._generate_py_result_function_wrapper — Function
_generate_py_result_function_wrapper(func, arg_syms, bindings, preserved, converted_args) -> Expr

Julia wrapper for a scanned #[pyfunction] returning PyResult<T> (#275 Phase 2). The result is a RustResult{T, String} whose error value is the fixed PYO3_OPAQUE_ERROR: the wrapper reports only that some Python-side error occurred, because rendering a PyErr without an interpreter panics inside pyo3 and the panic crossing extern "C" would abort the process.

source
RustCall._generate_py_result_method_wrapper — Method
_generate_py_result_method_wrapper(info, method, ...) -> Expr

Julia wrapper for a scanned #[pymethods] method returning PyResult<T> (#275 Phase 2), the method twin of _generate_py_result_function_wrapper. The C struct is CResult_<Struct>_<method>, matching the name the wrapper generator gives it.

source
RustCall._generate_result_function_wrapper — Function
_generate_result_function_wrapper(func, result_info, arg_syms, converted_args) -> Expr

Generate a Julia wrapper for a function that returns Result<T, E>. The wrapper will return RustResult{T, E}.

source
RustCall._generate_string_function_wrapper — Method
_generate_string_function_wrapper(func, arg_syms) -> Expr

Wrapper for a #[julia] function with String / &str arguments or return (#242): arguments are passed as (ptr, len) pairs under GC.@preserve, a String return is copied out of <fn>_RustCallOwnedString and released with <fn>_free_rust_string, a &str return is copied out of the borrowed view.

source
RustCall._method_payload_plan — Method
_method_payload_plan(info, method, helper_owner) -> MethodPayloadPlan

The CResult_<Struct>_<method> / COption_<Struct>_<method> mirror of one method, shared by the in-memory @rust_crate emitter and the source-text one so the two cannot describe the same aggregate differently.

helper_owner is what the wrapper's owned-string buffer is named after — the struct for a method wrapped next to its struct, <Struct>_<method> for one whose wrapper declares its own buffers — and is the only thing that differs between the flavours. The caller takes it from the manifest (_method_string_owner, #342).

source
RustCall._py_result_types — Method
_py_result_types(ok_type, ok_abi, context; strict) -> (surface, slot, is_unit)

How a lowered PyResult<T> is read on the Julia side (#275 Phase 2).

The wrapper returns CResult_<owner> { is_ok: u8, ok_value: <slot>, err_value: i32 }. slot is the C field type, surface is what the caller sees, and is_unit says the Ok payload is a placeholder: a PyResult<()> still has to report success or failure, so the wrapper writes a u8 there and Julia hands back nothing.

The error side is not a type at all — it is always PYO3_OPAQUE_ERROR, because the generated wrapper drops the PyErr without ever rendering it.

source
RustCall._static_method_collisions — Method
_static_method_collisions(info::CrateInfo) -> Set{String}

The names a static (non-constructor) #[julia] method shares with a free function or with another struct's static method in the same crate.

A static method is bound as name(::Type{Struct}, args...) (#323); it also gets the bare name(args...) form for convenience, but only when nothing else in the generated module would define name(args...) too — two such definitions overwrite each other (silently under @rust_crate, a hard error when a written module is precompiled). Free functions always keep their bare name; the static method yields.

source
RustCall.BINDINGS_FORMAT_VERSION — Constant
BINDINGS_FORMAT_VERSION

Format marker carried by every file write_bindings_to_file emits (# Bindings format: <MAJOR.MINOR>), and the value the file's const _BINDINGS_FORMAT = RustCall.check_bindings_format("<MAJOR.MINOR>") hands back to the RustCall that loads it.

Since v0.7 (#489) it is the MAJOR.MINOR of this release, read from Project.toml when the package is loaded — RELEASE_FORMAT_IDENTIFIER, the same value as MANIFEST_SCHEMA_VERSION — never a number of its own. A file is compatible with the RustCall that loads it when the two name the same MAJOR.MINOR: a patch release never changes the format, so a file written by v0.7.0 loads under v0.7.3; a different minor or major is refused, at include and again in __init__, with a message saying to regenerate the file with RustCall.write_bindings_to_file (check_bindings_format). A bindings-format change may therefore ship only in a minor or major release.

Through v0.6.x the format was an integer bumped on every incompatible edit, and those files are not readable any more: they define no _BINDINGS_FORMAT, and register_handle_mirror!, which every such __init__ calls, refuses the module with the same message. What each integer introduced:

  • 2 (#277 Phase B5): the file loads its library through RustCall.load_artifact! rather than Libdl.dlopen, so the handle is registered and unload_library can see it, and its struct finalizers capture a destructor pointer and the library's liveness flag instead of resolving the destructor when they run.

  • 3 (#246): string arguments are built with RustCall.ffi_string_argument, which the file imports, so invalid UTF-8 raises instead of being substituted. That name does not exist in an older RustCall, so a file emitted here does not load against one — the direction the marker is really for.

  • 4 (#245): the emitted CResult_<fn> / COption_<fn> mirrors subtype RustCall.FFIByValue, which the file imports. That name does not exist in an older RustCall, so a file emitted here does not load against one — the direction the marker is really for.

  • 5 (#268): a method returning Result<T, E> / Option<T> emits a CResult_<Struct>_<method> / COption_<Struct>_<method> mirror and decodes it with RustCall._result_payload, which the file imports and which does not exist in an older RustCall. The same import carries the release of an owned String payload, so a file emitted here must not be loaded against a RustCall that would leak it.

  • 6 (#309): __init__ opens a private generation copy of the library (RustCall.loadable_library_copy, #289) rather than mapping _LIB_PATH — Cargo's output, or the copy write_bindings_to_file made — in place. A mapped image cannot be overwritten on Windows, so a module emitted before this made the crate unbuildable (and the file unregenerable) for the rest of the session. The name does not exist in a RustCall older than #289.

  • 7 (#300): every symbol the file names is module-qualified (a__C_free, rustcall_a__run), and items inside Rust modules live in Julia submodules (bindings.a.run). A file emitted before this names symbols a library built with the current proc-macro no longer exports for any item inside a module.

  • 8 (#303): generated calls support defaulted PyO3 arities and Python-owned class handles.

  • 9 (#303): generated modules pin wrapper images containing Python-owned handles and give those objects a process-lifetime finalizer flag.

  • 10 (#371): the pin/finalizer decision comes from the wrapper manifest's authoritative python_owned_handle field, so filtering the method that selected that handle cannot silently remove the lifetime policy.

  • 11 (#253): every call site keeps the snapshot it resolved in a RustCall.CrateTargetCache of its own, declared beside the wrapper, and the target helpers take that cache as their first argument. The name does not exist in an older RustCall, so a file emitted here does not load against one — the direction the marker is really for.

  • 12 (#460): a callback argument's pointer is @cfunction(RustCall.CallbackSlot{k, R}(), ...), a slot that knows its return type and so hands Rust a zero of it — never raises through Rust — when invoked with no call in progress. The name does not exist in an older RustCall. Owned-buffer returns are guarded with the four-argument _guard_panic(value, channel, name, free_ptr), which calls a RustCall.guard_rust_panic_ptr method an older RustCall does not have, so a buffer returned by a call whose callback threw is released instead of leaked.

  • 13 (#474): the file records every input of its build — crate, registry name, profile, features, kind, build environment, Cargo configuration, toolchain — as one RustCall.CrateBuildRecord (_BUILD_RECORD), which is what a hot reload rebuilds from, and reads _LIB_NAME from it. The name does not exist in an older RustCall. Its __init__ also checks the recorded build environment before loading, as the in-memory module does.

source
RustCall._cache_built_library — Method
_cache_built_library(cache_key, built, cache_enabled) -> String

The path a generated module should name for a library that was just built: the cache copy when caching is on, and built itself when it is off or the cache could not be written.

Caching is what makes the path durable. built is either Cargo's output under crate_target_directory(crate) — rewritten by the next build of the crate — or a file inside a wrapper project that is about to be deleted; the cache copy is neither, which is what a module compiled into a package's precompile image needs when its __init__ runs in a later session (#339).

Returning built unchanged is the caller's signal that nothing was copied, so a caller whose built is about to disappear can keep a copy of its own.

source
RustCall._plain_crate_build_env — Method
_plain_crate_build_env() -> Vector{Pair{String, String}}

The environment a plain @rust_crate build (no PyO3 wrapper) is keyed by: artifact_build_env() — the #282 allowlist, PYO3_* included by prefix — plus the contents of PYO3_CONFIG_FILE when it is set. The allowlist records that variable's value, which is a path; a crate that depends on pyo3 and takes this path (a cdylib exposing #[julia] items, say) reads the file itself at build time, so an edit to it — another Python version, ABI or library directory — is a different binary under the same path. The wrapper path already hashes the contents (_pyo3_wrapper_build_env); without this the plain key did not, and get_cargo_cached_library answered the edited configuration with the old library (#339 review).

Neither depends on the dependency graph, deliberately. Cargo hands every ambient variable to every build script, and a crate's own build.rs may read PYO3_PYTHON, or open the file PYO3_CONFIG_FILE names, without depending on pyo3 — which crates are in the graph proves nothing about what a script reads. So the value is an input of every build (the #282 contract) and so are the contents of the file it names, as .cargo/config.toml's are: the price is a spare rebuild when Python is configured for another package while this variable is set and its file edited, and the alternative — a gate on pyo3 being in the graph — was a stale library for the crate that read the file anyway (#339 review; an earlier round of this PR tried the gate and reverted it).

source
RustCall._plain_scan_info — Method
_plain_scan_info(crate_path, info, features, default_features, release) -> CrateInfo

The scan the plain (#[julia]) path emits bindings from: info rescanned under the configuration the crate is built with — rustc --print cfg of the crate as its own Cargo root, under the requested profile and feature flags (_crate_build_cfg_text) — so every #[cfg] is decided the way the build decides it.

The lenient scan lists every feature variant of an item; the build has exactly one of them. Emitting the lenient list produced a module that named symbols the library does not export (a #[cfg(feature = "x")] #[julia] fn with x off), or the wrong one of two mutually exclusive signatures, and the mismatch surfaced as a dlsym failure on the first call. Hot reload has always rescanned this way after a rebuild (_scan_crate_signatures); the first load now does too, and the feature set a caller asks for (features, default_features) is what the probe runs under, as it is what the build runs under (#307 review; #277 Phase B).

The probe has the shape of the build. A crate with a cdylib target is built as the Cargo root (build_crate_directly), so it is probed as one and its own [profile.*] applies. Any other crate is built as the dependency of a generated _julia_wrapper root, whose profile — RustCall's, panic = "unwind" pinned — replaces the crate's own; such a crate is probed as a wrapper's dependency (_wrapper_probe_cfg_text), so a #[cfg(debug_assertions)] item under a crate-level debug-assertions = true is scanned the way the build compiles it: out (#307 review).

info is returned unchanged when Cargo will not answer (no cargo, an unresolvable crate); the build then fails on its own terms.

source
RustCall._uncached_library_home — Method
_uncached_library_home(built) -> String

A copy of built in a directory that outlives the process that made it, for a build that is not entered into the cache (cache = false, or a cache write that failed).

Not mktempdir(): that cleans up at process exit, and the process that generates a module is not always the one that loads it. A package precompiled with cache = false records this path as its _LIB_PATH; the precompile worker then exits, the directory goes with it, and the session that triggered the precompilation loads an image whose library is already gone (#339 review). The copy lives under the Cargo cache directory instead, under a name the cache lookup never returns, so RustCall.clear_cache() is what removes it.

source
RustCall.bindings_format_compatible — Method
bindings_format_compatible(marker) -> Bool

Whether a bindings file marked marker is readable by this RustCall: the marker parses as a VersionNumber whose MAJOR.MINOR equals BINDINGS_FORMAT_VERSION's (a patch component, if any, may differ). An integer — the scheme of v0.6.x and earlier — nothing (no marker) or anything that is not a version is not.

source
RustCall.build_crate_directly — Method
build_crate_directly(info::CrateInfo, release::Bool) -> String

Build the crate directly using cargo and return the path to the library.

source
RustCall.check_bindings_format — Method
check_bindings_format(marker) -> String

Return marker when a bindings file carrying it is readable by this RustCall (bindings_format_compatible), and otherwise raise a RustError saying to regenerate the file with write_bindings_to_file. Every generated crate module calls it at its top level (const _BINDINGS_FORMAT = ...), so an incompatible file is refused when it is included, before anything else in it runs (#489).

source
RustCall.compute_crate_hash — Method
compute_crate_hash(info::CrateInfo) -> String

Identity of an external crate build: artifact_key of an ArtifactId, so the @rust_crate path answers "which artifact is this?" with the same function as every other path (#278).

What it covers, and what the previous formula missed:

  • the whole crate directory, through crate_content_digest, not only the .rs files the scan happened to list — so Cargo.toml, Cargo.lock, build.rs and any include_str!ed data are inputs;
  • local path dependencies, by content, through artifact_path_dependency_digest, so editing a sibling crate rebuilds;
  • the effective Cargo configuration of the crate directory (.cargo/config.toml and the chain above it, plus the Cargo home file);
  • the toolchain and the compiler that runs, defaulted by ArtifactId;
  • the release profile, and the crate's name and version as before.

Absolute paths are deliberately absent: an identical crate checked out elsewhere keys the same, so a cache hit survives a move.

The name, the signature and the return type (a hex String) are unchanged, and so is the format of the file write_bindings_to_file emits; only the value changes, which means the first build after upgrading rebuilds.

source
RustCall.crate_library_name — Method
crate_library_name(info::CrateInfo; release = true) -> String

The RUST_LIBRARIES key a @rust_crate library is registered under: rust_crate_<crate name>_<short id of the crate identity for that profile>.

The profile is part of the name, exactly as it is part of the cache key (compute_crate_hash(info; release)). A debug and a release build of one crate are two different binaries, and giving them one registry name made them clobber each other: the second @rust_crate replaced the first's entry, retired its liveness flag out from under objects that were still alive, and pointed its module mirror at the other profile's image.

@rust_crate used to keep its handle only in a module-local Ref, so unload_library, unload_all_libraries and every registry the rest of RustCall keeps were blind to it (#250). Registering it means the same transaction that publishes the handle also publishes the liveness flag its objects capture, and unloading it retires them (#277 Phase B5).

Keyed by the crate identity so two crates — or one crate rebuilt under a different toolchain — do not collide on one entry.

source
RustCall.generate_bindings — Method
generate_bindings(crate_path::String; kwargs...) -> Expr

Generate Julia bindings for an external Rust crate.

This is the main entry point for the Maturin-like feature. It scans the crate, creates a wrapper crate if needed, builds it, and generates Julia bindings.

Arguments

  • crate_path::String: Path to the Rust crate root directory

Keyword Arguments

  • output_module_name::Union{String, Nothing}: Name for the generated module
  • build_release::Bool: Build in release mode (default: true)
  • cache_enabled::Bool: Enable caching (default: true)

Returns

  • Expr: A module expression containing all bindings

Example

bindings = generate_bindings("/path/to/my_crate")
eval(bindings)
# The generated bindings are now available
MyCrate.add(Int32(1), Int32(2))
source
RustCall.get_function_pointer_from_lib — Method
get_function_pointer_from_lib(lib_handle::Ptr{Cvoid}, func_name::String) -> Ptr{Cvoid}

Get a function pointer from a loaded library.

No generated wrapper calls it — they resolve through their module's generation snapshot. It stays because the import RustCall: ... prelude of every file an older RustCall wrote with write_bindings_to_file names it, and such a file of this MAJOR.MINOR must keep loading (BINDINGS_FORMAT_VERSION).

source
RustCall.CrateBindings — Type
CrateBindings

Runtime wrapper returned by @rust_crate and load_crate_bindings.

Property access preserves non-function exports such as types and constants, while exported functions are routed through a proxy so calls remain world-age-safe after dynamic loading.

source
RustCall._instantiate_runtime_bindings — Method
_instantiate_runtime_bindings(bindings_expr; target_module, visible) -> Module

Evaluate the generated module expression and return the module.

Where it is evaluated decides whether the caller can be precompiled (#339):

  • target_module === nothing — the run-time API, load_crate_bindings called from a function with no expanding module: a fresh anonymous Module under Main, as before. Nothing rooted in Main can be part of a package's precompile image, and nothing that calls this way is being precompiled.
  • target_module given (the @rust_crate macro passes __module__): visible = true defines the module directly as target_module.<name> — the submodule= form, for using .Name: .... Otherwise, while the caller is being precompiled (Base.generating_output()), it goes into a hidden child namespace target_module.var"##RustCallCrateRuntime#N", unique per call, so it belongs to the module tree Julia is serializing and nothing the caller did not name appears in its namespace (the #222 contract). Outside precompilation the anonymous Main-rooted module is used exactly as before: a child module defined in the caller can never be removed, and a run-time @rust_crate may be evaluated any number of times.

Only submodule= makes it visible, never name=, and that separation is not cosmetic: const B = @rust_crate path name="B" is a documented form, and defining a module B in the caller and then binding the returned value to the same constant produced a package whose precompile image segfaults on load (#339 review). name= therefore keeps naming the module without defining anything the caller did not ask for.

source
RustCall.load_crate_bindings — Method
load_crate_bindings(crate_path::String; output_module_name=nothing, submodule_name=nothing, build_release=true, cache_enabled=true, target_module=nothing) -> CrateBindings

Generate, load, and return explicit bindings for a Rust crate.

Use the returned CrateBindings value directly:

const MyCrate = load_crate_bindings("/path/to/my_crate")
MyCrate.add(Int32(1), Int32(2))
p = MyCrate.Point(3.0, 4.0)
p isa MyCrate.Point

target_module is where the generated module is defined. The @rust_crate macro passes the module that expands it, which is what lets a package that uses the macro at top level be precompiled (#339); called without it, the module lives in an anonymous namespace under Main and the caller cannot be precompiled.

output_module_name names the generated module; it defines nothing in target_module, so the bindings are reached through the returned value. submodule_name is what defines it there — target_module.Name, so using .Name: f works — and it also names it, so the two are not given together.

source
RustCall.@rust_crate — Macro
@rust_crate(path)
@rust_crate(path, options...)

Generate and load bindings for an external Rust crate.

Arguments

  • path: Path to the Rust crate (string literal)

Options

  • name="ModuleName": name the generated module. It defines nothing in the calling module; the bindings are reached through the returned value.
  • submodule="ModuleName": define the generated module under that name in the calling module, so that using .ModuleName: f, T works — the shape a package uses. Do not assign the result to the same name.
  • release=true/false: Build in release mode (default: true)
  • cache=true/false: Enable caching (default: true)
  • pyo3_host=false/true: bind a PyO3 crate through a live Python interpreter instead of the generated C-ABI wrapper (#424). The crate is built as the Python extension it already is and its imported module is called, so a private #[pyfunction] (E0603 to the wrapper path), a Python<'_> signature, numpy arrays and Python callables are all reachable. Requires PythonCall (using PythonCall); a PyResult{T} becomes RustResult{T, String} carrying the interpreter's own message.

Where the module lives

The generated module is evaluated inside the module that expands the macro, so a package that uses @rust_crate at top level can be precompiled (#339): the crate is built and the bindings generated when the package is precompiled, and the module's __init__ opens the library — RustCall's cache copy — in the session that loads the package. If that copy has been rebuilt or removed (RustCall.clear_cache()), the package's precompile cache is stale and Julia re-precompiles it, building the crate again.

Without submodule= the module has a hidden, per-call name inside the caller, so repeated calls never collide and nothing the caller did not name appears in its namespace. With submodule="X", a second @rust_crate ... submodule="X" in the same module replaces X (Julia warns replacing module X); bindings obtained earlier keep the module they hold. submodule="X" defines X, so do not also write const X = @rust_crate ... submodule="X" — binding the returned value over the module it just defined is what name= deliberately avoids.

Example

# Basic usage
const MyCrate = @rust_crate "/path/to/my_crate"

# With options
const MyBindings = @rust_crate "/path/to/my_crate" name="MyBindings" release=true

# After loading, use the returned bindings value directly
MyCrate.add(Int32(1), Int32(2))
p = MyCrate.Point(3.0, 4.0)
MyCrate.distance(p)

# In a package: define the module here and re-export from it
module MyPkg
using RustCall
@rust_crate joinpath(@__DIR__, "..", "deps", "my_crate") submodule="Bindings"
using .Bindings: add, Point
export add, Point
end
source
RustCall.write_bindings_to_file — Method
write_bindings_to_file(crate_path::String, output_path::String; kwargs...) -> String

Generate Julia bindings for a Rust crate and write them to a file.

This function is designed for package development workflow where bindings should be generated once and then included in the package for precompilation.

Arguments

  • crate_path::String: Path to the Rust crate root directory
  • output_path::String: Path to write the generated Julia code

Keyword Arguments

  • output_module_name::Union{String, Nothing}: Name for the generated module
  • build_release::Bool: Build in release mode (default: true)
  • relative_lib_path::Union{String, Nothing}: Path to library relative to the generated file
  • strict::Symbol: what to do when the FFI contract cannot describe a return type — :error (raise, naming the signature), :warn (warn once and emit Any) or :none (emit Any silently). Defaults to RustCall.FFI_STRICT[]. A crate that used to emit Any for an unsupported type keeps building with :warn; see docs/src/crate_bindings.md. If not provided, uses the absolute path to the compiled library.

Returns

  • String: Path to the generated Julia file

Workflow for Package Development

  1. During development, call write_bindings_to_file to generate bindings:

    using RustCall
    write_bindings_to_file(
        "deps/my_rust_crate",
        "src/generated/MyRustBindings.jl",
        relative_lib_path = "../deps/lib"
    )
  2. Include the generated file in your package:

    # In src/MyPackage.jl
    include("generated/MyRustBindings.jl")
  3. The generated module will be precompiled with your package.

Example

using RustCall

# Generate bindings to a file
write_bindings_to_file(
    "/path/to/my_crate",
    "src/MyCrateBindings.jl",
    output_module_name = "MyCrate"
)

# The file can now be included in your package
source
RustCall._emit_in_callback_frame — Method
_emit_in_callback_frame(frame_str, code) -> String

Source-text twin of _in_callback_frame (#296): code, or code inside a try … finally that pops the CallbackFrame named by frame_str.

source
RustCall._emit_method_code — Method
_emit_method_code(struct_info::RustStructInfo, method::RustMethod) -> String

Generate Julia code for a method wrapper as a string.

source
RustCall._emit_preserved — Method
_emit_preserved(preserve_str, call) -> String

GC.@preserve <objects>, <call> as source text (through the file's rustcall′Base alias, #528), or just <call> when there is nothing to preserve.

GC.@preserve takes at least one object followed by the expression, so the empty case has to omit the macro entirely rather than emit GC.@preserve(, call). The parenthesized form is used because the result is nested inside _guard_panic(...), and it needs the objects comma-separated where the statement form separates them by spaces.

source
RustCall._emit_string_arg_plan — Method
_emit_string_arg_plan(func_or_method) -> (bindings_str, preserve_str, converted_args_str, frame_str)

Source-text counterpart of _string_arg_plan for the file emitter (free functions and struct methods alike).

source
RustCall._quote_preserved — Method
_quote_preserved(preserved, call) -> Expr

GC.@preserve <objects> <call>, or just call when preserved is empty. The expression twin of _emit_preserved: GC.@preserve needs at least one object, so an empty list must not produce the macro call at all.

source
RustCall.emit_crate_module_code — Method
emit_crate_module_code(info::CrateInfo, lib_path::String; kwargs...) -> String

Generate Julia module code as a string, suitable for writing to a file.

Arguments

  • info::CrateInfo: Crate information from scan_crate
  • lib_path::String: Path to the compiled shared library (or relative path)

Keyword Arguments

  • module_name::Union{String, Nothing}: Name for the module
  • use_relative_path::Bool: If true, treat lib_path as relative to @DIR
  • strict::Symbol: how an unsupported return type is handled, see FFI_STRICT. Threaded through every emitter rather than set globally, so concurrent calls do not interfere.
  • preload::Vector{String}: libraries the image imports by name that the loader would not find on its own (a PyO3 wrapper's Python DLL on Windows), opened before it by load_artifact!. Emitted only when non-empty, so a file that needs none reads under a RustCall without the option.

Returns

  • String: Julia source code for the module
source

One environment per build (src/artifacts/build_env_snapshot.jl)

Every crate build — @rust_crate, write_bindings_to_file, the PyO3 wrapper and host paths, a hot reload — reads the environment through one RustCall.BuildEnvSnapshot taken at its start (#481).

RustCall.BuildEnvSnapshot — Type
BuildEnvSnapshot

One copy of the process environment, taken once at the start of a crate build: @rust_crate (the direct crate, the generated wrapper crate, the PyO3 wrapper crate), write_bindings_to_file, the PyO3 host path (build_pyo3_extension) and a hot reload. Everything the build derives from the environment is read from it after that, and nothing on the path reads ENV again:

  • the artifact key (compute_crate_hash, _pyo3_wrapper_build_env, _pyo3_host_build_env) and the registry name;
  • the module's CrateBuildRecord (crate_build_record) and the checks against a record (_build_record_mismatch, _build_env_changes);
  • every subprocess: the Cargo probes and builds run under snapshot_env(snapshot) (or the record's environment derived from it), and every Python interpreter the build asks about is started under it too (snapshot_cmd), so a PATH changed by another task selects no other python3. A program looked up on PATH is looked up on the snapshot's (snapshot_which).

Before #481 each of those read ENV at its own moment, so a task changing RUSTFLAGS, PYO3_PYTHON or PATH in between could produce a library built under one environment, keyed and recorded under another, and checked against a third.

Immutable in effect: the table is copied in at construction, never mutated, and handed out only as a fresh copy (snapshot_env), so a callee that edits the environment it was given cannot change what the next reader sees. test/test_build_env_snapshot.jl asserts at the source level that no function on a build path reads ENV directly, and per entry point that an environment changed right after the snapshot reaches neither the library, nor the record, nor the checks.

source
RustCall.BuildEnvSnapshot — Method
BuildEnvSnapshot() -> BuildEnvSnapshot

The snapshot of ENV now. Called once, at the start of a build entry point; The test seam runs right after it (_build_env_seam(:snapshot)).

source
RustCall.snapshot_cmd — Method
snapshot_cmd(s::BuildEnvSnapshot, cmd::Cmd) -> Cmd

cmd run under the snapshot's environment rather than the process's. A bare program name is looked up on the snapshot's PATH — libuv resolves it from the child's environment — so the interpreter or tool that runs is the one the snapshot selects.

source
RustCall.snapshot_env — Method
snapshot_env(s::BuildEnvSnapshot) -> Dict{String, String}

A fresh copy of the snapshot's variables, for a subprocess environment (setenv) or a helper that takes an environment table. Each call returns a new Dict, so editing it (pinning PYO3_PYTHON, CARGO_TARGET_DIR) is local to that caller.

source
RustCall.snapshot_which — Method
snapshot_which(s::BuildEnvSnapshot, name) -> String

Sys.which(name) on the snapshot's PATH rather than the process's, spelled the same way (Sys.which's own search, step for step); "" when nothing is found.

source