Cargo projects and dependencies
Everything an inline block with a // cargo-deps: comment (or a $//!$cargoblock) goes through instead of a barerustc`: the dependency DSL and its resolution, and the temporary Cargo projects RustCall generates, builds and caches. External crates are on External crates.
Dependencies (src/build/dependencies.jl)
RustCall.DependencySpec — Type
DependencySpecRepresents a single Rust crate dependency specification.
Fields
name::String: Crate nameversion::Union{String, Nothing}: Version specification (e.g., "0.15", "1.0")features::Vector{String}: List of crate features to enablegit::Union{String, Nothing}: Git repository URL (for git dependencies)path::Union{String, Nothing}: Local path (for path dependencies)
RustCall._count_trailing_backslashes — Method
_count_trailing_backslashes(s::AbstractString) -> IntCount consecutive trailing backslash characters. Used to determine whether a quote is escaped: the quote is escaped only if preceded by an odd number of backslashes (e.g., \" is escaped, \\" is not).
RustCall.extract_cargo_block — Method
extract_cargo_block(code::String) -> Union{String, Nothing}Extract the cargo TOML block from Rust code.
Looks for patterns like:
//! ```cargo
//! [dependencies]
//! ndarray = "0.15"
//! ```Returns
- The content inside the cargo block (without //! prefixes), or
nothingif not found
RustCall.extract_cargo_deps_line — Method
extract_cargo_deps_line(code::String) -> Union{String, Nothing}Extract the cargo-deps line from Rust code.
Looks for patterns like:
// cargo-deps: ndarray="0.15", serde="1.0"Returns
- The content after "cargo-deps:", or
nothingif not found
RustCall.has_dependencies — Method
has_dependencies(code::String) -> BoolCheck if code contains any dependency specifications.
RustCall.merge_dependencies — Method
merge_dependencies(deps::Vector{DependencySpec}) -> Vector{DependencySpec}Merge dependencies with the same name, combining features.
Arguments
deps::Vector{DependencySpec}: List of dependencies (may contain duplicates)
Returns
Vector{DependencySpec}: Merged dependencies (no duplicates)
RustCall.merge_two_dependencies — Method
merge_two_dependencies(dep1::DependencySpec, dep2::DependencySpec) -> DependencySpecMerge two dependencies with the same name.
RustCall.normalize_dependency — Method
normalize_dependency(dep::DependencySpec) -> DependencySpecNormalize a dependency specification.
- Sorts features alphabetically
- Trims whitespace from strings
RustCall.parse_cargo_deps_line — Method
parse_cargo_deps_line(line::AbstractString) -> Vector{DependencySpec}Parse a cargo-deps line to extract dependencies.
Format: name="version", name2={version="1.0", features=["f1"]}
Arguments
line::AbstractString: Content after "cargo-deps:"
Returns
Vector{DependencySpec}: Parsed dependencies
RustCall.parse_cargo_toml_block — Method
parse_cargo_toml_block(block::String) -> Vector{DependencySpec}Parse a TOML-formatted cargo block to extract dependencies.
Arguments
block::String: TOML content from a cargo block
Returns
Vector{DependencySpec}: Parsed dependencies
RustCall.parse_dependencies_from_code — Method
parse_dependencies_from_code(code::String) -> Vector{DependencySpec}Parse dependencies from Rust code that contains rustscript-style dependency specifications.
Supports two formats:
Document comment format:
//! ```cargo //! [dependencies] //! ndarray = "0.15" //! serde = { version = "1.0", features = ["derive"] } //! ```Single-line comment format:
// cargo-deps: ndarray="0.15", serde="1.0"
Arguments
code::String: Rust source code potentially containing dependency specifications
Returns
Vector{DependencySpec}: List of parsed dependencies (empty if none found)
RustCall.parse_single_cargo_dep — Method
parse_single_cargo_dep(part::String) -> Union{DependencySpec, Nothing}Parse a single dependency from cargo-deps format.
Formats:
- name="version"
- name={version="1.0", features=["f1", "f2"]}
RustCall.parse_toml_dependency — Method
parse_toml_dependency(name::String, spec) -> DependencySpecParse a single dependency from TOML format.
Arguments
name::String: Crate namespec: Version string or dict with version, features, git, path
RustCall.split_cargo_deps — Method
split_cargo_deps(line::String) -> Vector{String}Split cargo-deps line by commas, respecting braces and quotes.
Dependency resolution (src/build/dependency_resolution.jl)
RustCall.resolve_version — Method
resolve_version(v1::Union{String, Nothing}, v2::Union{String, Nothing}, name::String) -> Union{String, Nothing}Resolve version conflict between two version specifications.
Strategy
- If both are nothing, return nothing
- If one is nothing, return the other
- If both are the same, return that version
- Prefer more specific version (e.g., "1.0.5" over "1.0")
- If neither is more specific, use v1 with a warning
RustCall.resolve_version_conflict — Method
resolve_version_conflict(dep1::DependencySpec, dep2::DependencySpec) -> DependencySpecResolve version conflicts between two dependency specifications.
When two dependencies with the same name have different versions:
- If one has a stricter (more specific) version, prefer that
- Otherwise, prefer the first one and emit a warning
Arguments
dep1::DependencySpec: First dependencydep2::DependencySpec: Second dependency (same name)
Returns
DependencySpec: Resolved dependency
Throws
DependencyResolutionErrorif dependencies have incompatible sources
RustCall.validate_dependencies — Method
validate_dependencies(deps::Vector{DependencySpec})Validate that all dependencies have valid specifications.
Checks
- Each dependency has a name
- Each dependency has at least one of: version, git, path
- No duplicate names (use merge_dependencies first)
Throws
DependencyResolutionErrorif validation fails
RustCall.validate_version_format — Method
validate_version_format(version::String, name::String)Validate that a version string is well-formed.
Valid formats
- "1.0"
- "1.0.5"
- "^1.0"
- "~1.0.5"
- ">=1.0, <2.0"
- "*"
RustCall.version_specificity — Method
version_specificity(version::String) -> IntCalculate a specificity score for a version string. Higher score = more specific.
Examples
- "1" -> 1
- "1.0" -> 2
- "1.0.5" -> 3
- "1.0.5-beta" -> 4
Cargo projects (src/build/cargoproject.jl)
RustCall.CARGO_BLOCK_PACKAGE_PREFIX — Constant
CARGO_BLOCK_PACKAGE_PREFIXThe prefix of the [package] name of every Cargo project RustCall generates for a // cargo-deps: block; see cargo_block_package.
RustCall.CargoProject — Type
CargoProjectRepresents a temporary Cargo project for building Rust code with dependencies.
Fields
name::String: Project/crate nameversion::String: Project version (default "0.1.0")dependencies::Vector{DependencySpec}: List of dependenciesedition::String: Rust edition (default "2021")path::String: Path to the project directory
RustCall.cargo_block_package — Method
cargo_block_package(deps) -> StringThe [package] name of the Cargo project generated for a // cargo-deps: block declaring deps: CARGO_BLOCK_PACKAGE_PREFIX followed by a short id of the dependency set's key (cargo_lockfile_id).
It is derived from the dependency set, not from the block, because the root package appears in Cargo.lock by name: a lockfile persisted for one set (lockfile_path) must fit every block that declares that set, or it could not be shared between blocks — or between machines (#256). And it is not one fixed name, because a fixed name reserves a package identity a user's own crate may hold: a block depending on a path crate named rustcall_block at the same version could not be resolved at all (Cargo refuses two packages of one name and version from different sources in a lockfile; #313 review). The project directory, not the package name, is what keeps concurrent builds apart (create_cargo_project makes a fresh temporary directory each time), and the built library is copied into the cache under the block's key.
RustCall.cleanup_cargo_project — Method
cleanup_cargo_project(project::CargoProject)Remove the temporary Cargo project directory.
Arguments
project::CargoProject: The project to clean up
RustCall.create_cargo_project — Method
create_cargo_project(name::String, dependencies::Vector{DependencySpec}; kwargs...) -> CargoProjectCreate a temporary Cargo project with the specified dependencies.
Arguments
name::String: Project name (used as crate name)dependencies::Vector{DependencySpec}: List of dependencies
Keyword Arguments
edition::String: Rust edition (default: "2021")path::Union{String, Nothing}: Project path (default: auto-generated temp directory)
Returns
CargoProject: The created project
Example
deps = [DependencySpec("ndarray", version="0.15")]
project = create_cargo_project("my_project", deps)RustCall.escape_toml_string — Method
escape_toml_string(s::AbstractString) -> StringEscape special characters in a string for safe TOML value interpolation. Prevents TOML injection by escaping backslashes, quotes, and control characters.
RustCall.format_dependency_line — Method
format_dependency_line(dep::DependencySpec) -> StringFormat a single dependency for Cargo.toml.
Examples
format_dependency_line(DependencySpec("ndarray", version="0.15"))
# => "ndarray = "0.15""
format_dependency_line(DependencySpec("serde", version="1.0", features=["derive"]))
# => "serde = { version = "1.0", features = ["derive"] }"RustCall.generate_cargo_toml — Method
generate_cargo_toml(name::String, deps::Vector{DependencySpec}, edition::String) -> StringGenerate Cargo.toml content for a project.
Arguments
name::String: Project namedeps::Vector{DependencySpec}: Dependenciesedition::String: Rust edition
Returns
String: Cargo.toml content
RustCall.get_project_lib_name — Method
get_project_lib_name(project::CargoProject) -> StringGet the library file name for the project (platform-specific).
Returns
- Library filename (e.g., "libmy_project.dylib" on macOS)
RustCall.remove_dependency_comments — Method
remove_dependency_comments(code::String) -> StringRemove dependency specification comments from Rust code.
Removes:
//!$cargo ...$blocks// cargo-deps: ...lines
Arguments
code::String: Original Rust code
Returns
String: Code without dependency comments
RustCall.write_rust_code_to_project — Method
write_rust_code_to_project(project::CargoProject, code::String)Write Rust code to the project's src/lib.rs, removing dependency comments.
Arguments
project::CargoProject: The Cargo projectcode::String: Rust source code (may contain dependency comments)
Cargo builds (src/build/cargobuild.jl)
RustCall.CRATE_TARGET_KEY_FILE — Constant
CRATE_TARGET_KEY_FILEThe file in a crate's <base> target directory holding the full artifact_key of the crate it belongs to; see crate_target_directory. It is the owner record every persistent short-named directory carries, SHORT_NAME_KEY_FILE (#504).
RustCall.TARGET_LAST_USED_STAMP — Constant
TARGET_LAST_USED_STAMPThe file in a crate_target_directory whose mtime records when RustCall last built or probed there. cleanup_old_cache ages a target directory by it: Cargo's own files are not rewritten by a no-op build, so they cannot say whether a directory is still in use.
RustCall._cargo_build_args — Method
_cargo_build_args(release, features, default_features; locked = false) -> Vector{String}The argument vector of the cargo build a project is built with: the profile, then the feature set (_cargo_feature_args), then --locked when the project's Cargo.lock is authoritative — it came from the lockfile store or was just generated for exactly this project (ensure_cargo_lockfile!) — so Cargo builds the resolved graph the identity describes or fails, never re-resolving behind the key (#256); and --offline under RUSTCALL_OFFLINE. A plain @rust_crate build made with features = ... / default_features = false passes them here, so the crate is built with the configuration that was asked for and not its default one (#307 review).
RustCall._cargo_feature_args — Method
_cargo_feature_args(features, default_features) -> Vector{String}The Cargo flags naming a feature set, in the spelling cargo build takes: --no-default-features when default_features is off, then --features a,b when features is non-empty. Empty for the default build.
RustCall._cargo_panic_env — Method
_cargo_panic_env(policy, env, release) -> Union{Nothing, Dict{String, String}}The environment to run Cargo under: env (a captured build-time snapshot, or the inherited environment when it is nothing) with CARGO_PROFILE_<PROFILE>_PANIC pinned to the policy's strategy.
nothing when the policy pins nothing (:crate_profile: the manifest is the user's, and forcing their profile from the outside would silently change how their crate is built) and there is no snapshot to replay.
The profile name follows release, not policy.cargo_profile alone: a debug build reads CARGO_PROFILE_DEV_PANIC.
RustCall._check_cargo_profile — Method
_check_cargo_profile(id::ArtifactId, release::Bool)Refuse to build when the profile recorded in id is not the one being built.
The two must agree because artifact_key(id) is the only key of the build: if they could disagree, the caller's lookup key and the artifact actually produced would describe different things — the shape of #287. Better a loud error than a cache that quietly holds the wrong binary.
RustCall._crate_target! — Function
_crate_target!(crate_path, flavour = :direct) -> Stringcrate_target_directory(crate_path, flavour), created, with the crate's last-used stamp refreshed — what every build and probe calls before it runs Cargo there. The stamp is the crate's <base> one whatever the flavour, since cleanup_old_cache ages the whole <base>.
RustCall._publish_lockfile! — Method
_publish_lockfile!(stored, target; wait = 10.0, replace = false,
root = nothing) -> StringPublish the lockfile a project just resolved (target) to the store (stored) so that exactly one resolution wins, and return the digest of the file the project ends up with.
The primitive is an exclusive create (O_CREAT | O_EXCL) of a claim file beside the entry (_claim_lockfile!), which every filesystem makes atomic — a rename guarded by an isfile check is not, and two first-time builders could pass the check together. The process that creates the claim is the publisher: it stages the content beside the entry and renames it into place (a whole file or none) unless an entry is already there, then removes the claim. Every other process is a loser: it waits up to wait seconds for the published file to appear, discards its own resolution, copies the published file into its project and returns that digest — so every racer builds the published graph (#313 review).
A claim is never expired by age. Deciding that a publisher is dead from a file's mtime against this process's clock is wrong across machines sharing the store (their clocks need not agree), and a takeover of a live claim is precisely the two-publisher race the claim exists to prevent. A claim that outlives wait with nothing published behind it therefore fails loudly, naming the file: if no other RustCall process is resolving the set, a previous one died holding the claim — delete that file (or run clear_lockfiles()) and build again. That failure is a CargoBuildError.
With replace = true the claim holder revalidates the stored file while it holds the claim. It replaces the file only when it still does not name root; otherwise it replays the now-fresh entry. A loser with a stale file waits for the entry to name root, not merely for any file to exist (#322).
RustCall._refresh_release_versions! — Method
_refresh_release_versions!(lockfile; release_names = nothing) -> SymbolRewrite, in place, the version line of every source-less [[package]] entry of lockfile that names one of RustCall's release crates the set resolves by path — release_names, or read from the manifest beside the file (_rustcall_release_names_in) — and every qualified reference "<name> <version>" to one, to the version that crate's manifest carries now. Nothing else in the file changes. Returns :unchanged, :refreshed, or :ambiguous — the file untouched — when a name has more than one source-less entry, since a same-named path package beside RustCall's crate cannot be told from it by name (its caller re-resolves the set instead). This is what lets a lockfile resolved under v0.4.0 replay --locked under v0.4.1: the set's identity does not move on a patch release (#372), so the store keeps serving the file, and the one thing in it a patch release rewrites is brought up to date.
RustCall._refresh_stored_lockfile! — Method
_refresh_stored_lockfile!(stored, release_names; wait = 10.0)Bring the lockfile the store holds at stored up to date with the current versions of the release crates in release_names (_refresh_release_versions!), in place and under the store's claim, so every reader — the identity computation and the replay alike — sees one file. A file whose refresh is ambiguous is removed instead, and the set is resolved afresh by the next ensure_cargo_lockfile!. Nothing to do for a set with no release crate, or no stored file. When another process holds the claim (a resolution or a refresh in flight) this waits up to wait seconds for it; a claim held longer than that is a CargoBuildError, as in _publish_lockfile! — the file under it cannot be trusted, and neither the identity nor a --locked build may proceed on it (#372 review).
RustCall.build_cargo_project — Method
build_cargo_project(project::CargoProject; release::Bool = true) -> StringBuild a Cargo project and return the path to the compiled library.
Arguments
project::CargoProject: The Cargo project to build
Keyword Arguments
release::Bool: Build in release mode (default: true for better performance)target_directory: theCARGO_TARGET_DIR(default: the project's owntarget/); a@rust_cratebuild passescrate_target_directory.working_directory: where Cargo runs (default: the project). Another directory is passed with--manifest-path, so Cargo's configuration is the one that directory reaches.
Returns
String: Path to the compiled shared library
Throws
CargoBuildErrorif the build fails
RustCall.build_cargo_project_cached — Method
build_cargo_project_cached(project::CargoProject, id::ArtifactId;
release = true, env = nothing) -> StringBuild a Cargo project with caching support.
If a cached library exists for this artifact, returns its path. Otherwise builds the project and caches the result.
Arguments
project::CargoProject: The Cargo project to buildid::ArtifactId: the complete identity of what is being built — source, dependency set, build environment (including the effective Cargo configuration), build profile and toolchain. The cache key isartifact_keyof exactly that record: this function never extends or re-derives it, so a Cargo block has one key for its lookup, its build and its save (#278, #287).
Keyword Arguments
release::Bool: Build in release mode (default: true)env: environment override for thecargoinvocation
Returns
String: Path to the compiled shared library (may be cached)
RustCall.cargo_offline — Function
cargo_offline() -> BoolWhether RUSTCALL_OFFLINE asks for air-gapped builds (1, true, yes; case insensitive). Every cargo invocation that could touch the network — generate-lockfile, build — then carries --offline, and Cargo fails at once, with its own message, on anything the local registry cache does not hold, rather than hanging on a download (#256). The flag changes where Cargo looks, not what it builds, so it is not part of any artifact identity.
RustCall.clear_cargo_cache — Method
clear_cargo_cache()Clear all cached Cargo-built libraries.
RustCall.clear_lockfiles — Method
clear_lockfiles()Remove every persisted Cargo.lock (lockfile_dir), so the next build of each // cargo-deps: dependency set resolves it afresh. This is the one operation that discards resolutions: clear_cache keeps them, because they are inputs of a build and not compiled output (#256). To re-resolve a single set, delete lockfile_path(deps) instead.
RustCall.crate_target_directory — Function
crate_target_directory(crate_path, flavour = :direct) -> StringThe CARGO_TARGET_DIR of every Cargo command RustCall runs for a @rust_crate crate, whichever flavour binds it (#445, #486). It is the one place that decides where a crate's build output goes; no @rust_crate path names a directory of its own.
flavour | who builds there | directory |
|---|---|---|
:direct | a cdylib crate built as its own root (build_crate_directly), its cfg probe (_crate_build_cfg_text), and a hot reload's rebuild and rescan (rebuild_crate) | <base> |
:pyo3_host | the extension module of pyo3_host = true (build_pyo3_extension) | <base>/pyo3-host |
:pyo3_wrapper | a PyO3 crate's generated wrapper and the cfg / feature probes that describe it (_build_pyo3_wrapper_project, _wrapper_probe_context); their generated projects live under it too (_wrapper_shaped_project) | <base>/pyo3-wrapper |
<base> is <Cargo cache>/targets/<short name of crate_target_id(crate_path)> (short_name_path). Never the crate's own target/: a package installed under a depot is read-only, and a CI cache that carries RustCall's cache then carries these builds as well. A hot reload rebuilds the direct build, so it shares that directory and its compiled dependencies; so does the direct build's cfg probe, so a build script sees one OUT_DIR. The PyO3 flavours get subdirectories of their own because they build the crate under another root or another link line, and two builds that write the same target/<profile>/lib<name>.* would race between Cargo exiting and RustCall copying the file out. The generated wrapper crate of a non-cdylib, non-PyO3 crate is a temporary project of its own and builds in its own target/, not here.
One <base> per crate rather than one shared by all, because Cargo writes the final library as target/<profile>/lib<name>.*, so two crates with the same package name would overwrite each other's output. Every flavour lives under the same <base>, so cleanup_old_cache ages and removes a crate's builds together, by the stamp _crate_target! refreshes.
The name is short, and verified. Windows limits a path to 260 characters (MAX_PATH; link.exe enforces it, whatever the system's long-path setting), the cache root there is already about 100 of them, and Cargo nests <profile>/build/<package>-<hash>/build_script_build-<hash>.exe below the target directory. The full 64-hex artifact_key left no room: a pyo3_host build of a crate depending on target-lexicon failed with LNK1104 at 262 characters (#486). The directory is therefore named by the key's short name (short_name_path, #504), and the full key is written inside it (CRATE_TARGET_KEY_FILE) by the first _crate_target! and compared by every later one (claim_short_name!). Isolation is still decided by the full key: two crates whose short ids collide are refused with an error rather than sharing a directory, which could have Cargo report the second as fresh and leave the first one's library in place (#447 review).
RustCall.ensure_cargo_lockfile! — Method
ensure_cargo_lockfile!(project::CargoProject; env = nothing) -> Union{String, Nothing}Give a generated project an authoritative Cargo.lock and return its content digest — nothing for a project that declares no dependencies of its own (project.dependencies empty, e.g. a @rust_crate wrapper whose manifest was written by hand), which has no entry in the lockfile store.
When the store has a lockfile for the project's dependency set (lockfile_path), it is copied in and nothing is resolved: the build that follows is --locked, so it either builds exactly the graph the file pins or fails. Otherwise cargo generate-lockfile resolves the set once — --offline under RUSTCALL_OFFLINE, failing loudly when the local registry lacks something — and the result is persisted for every later build of the same set (#256). The generated project's root package is named from the dependency set (cargo_block_package) for every block declaring it, which is what makes one lockfile fit them all.
Two processes — or two machines sharing the store — that both find it empty resolve independently, possibly from different registry snapshots. Publication is therefore no-clobber (_publish_lockfile!): the first file to land is the resolution of the set, and whoever loses discards its own, replays the published file into its project and returns that digest — so both builds are of one graph, which is the point of the store (#313 review).
Throws CargoBuildError with Cargo's own message when resolution fails.
RustCall.get_built_library_path — Method
get_built_library_path(project::CargoProject, release::Bool) -> StringGet the path to the built library for a Cargo project.
Arguments
project::CargoProject: The Cargo projectrelease::Bool: Whether release mode was used
Returns
String: Path to the shared library
Note
The path follows Cargo's target directory structure:
- Release: target/release/libname.dylib (or .so, .dll)
- Debug: target/debug/libname.dylib
RustCall.get_cargo_cache_dir — Method
get_cargo_cache_dir() -> StringGet the cache directory for Cargo-built libraries.
RustCall.get_cargo_cache_size — Method
get_cargo_cache_size() -> Int64Get the total size of the Cargo cache in bytes.
RustCall.get_cargo_cached_library — Method
get_cargo_cached_library(cache_key::String) -> Union{String, Nothing}Get a cached Cargo library by cache key.
Returns
- Path to cached library, or
nothingif not found
RustCall.hash_dependencies — Method
hash_dependencies(deps::Vector{DependencySpec}) -> StringGenerate a hash of the dependency specifications for cache keying.
Arguments
deps::Vector{DependencySpec}: Dependencies to hash
Returns
String: Hex-encoded hash of the dependencies
RustCall.lockfile_dir — Method
lockfile_dir() -> StringThe directory of the persisted Cargo.lock files (<cache dir>/lockfiles), created on demand. Lockfiles are inputs of a build, not outputs, so clear_cache / clear_cargo_cache leave them alone: delete one to re-resolve its dependency set (lockfile_path).
RustCall.lockfile_path — Method
lockfile_path(deps::Vector{DependencySpec}) -> String
lockfile_path(code::AbstractString) -> StringWhere RustCall keeps the Cargo.lock of a // cargo-deps: dependency set — named by artifact_key(cargo_lockfile_id(deps)), so the same declared set on any machine looks in the same place. The second form parses the dependency comments of a block's source (parse_dependencies_from_code).
The file is written the first time the set is resolved (cargo generate-lockfile, ensure_cargo_lockfile!) and replayed with --locked on every later build, on this machine or another one that has the file. Commit it, copy it, or delete it to resolve afresh; its content is part of every build's identity, so a changed lockfile is a rebuild and never a stale cache hit (#256).
RustCall.save_cargo_cached_library — Method
save_cargo_cached_library(cache_key::String, lib_path::String)Save a compiled library to the Cargo cache.
Arguments
cache_key::String: Cache keylib_path::String: Path to the compiled library