depends-rs
depends-rs lets you express Rust borrow relationships declaratively by mapping data dependencies instead of manually wiring lifetime generics.
depends-rs replaces manual lifetime wiring with clear data-flow contracts. The procedural macros generate ordinary Rust lifetime parameters and where clauses, while rustc continues to rigorously check every borrow, function body, and outlives rule.
depends-rs can be seen as a spiritual successor to Cyan.
Quick Start
use ;
The generated Rust code expands to:
This function returns a struct holding two independent borrows:
return.leftis tied to the lifetime ofleft.return.rightis tied to the lifetime ofright.- Both inputs must remain valid while the returned
Pairis in use, but each input borrow can be released independently.
Core Mental Model
depends-rs separates borrow architecture into two declarative steps:
- Lifetime Shapes (
#[lifetimes]): Attached tostruct,enum, orimplitems. It inspects your data layout and automatically introduces independent lifetime parameters for reference fields, naming them after the fields (e.g.'head,'tail,'parts_head). - Lifetime Contracts (
#[depends]): Attached to functions and methods. Instead of manually inventing generic lifetime variables, you declare how outputs depend on inputs through intuitive path expressions (e.g.return.field = input.fieldorout.data <= cfg.name).
Syntax Cheat Sheet
Contract Operators
| Operator | Target | Source | Semantic | Generated Rust |
|---|---|---|---|---|
= |
Leaf or Aggregate | Leaf | Exact assignment / Broadcast: Binds target leaf to source lifetime. If target is an aggregate, broadcasts to all unmatched leaves. | Shared lifetime parameter ('src) |
<= |
Leaf | Leaf | Outlives constraint: Enforces that target must live no longer than source (target is bounded by source). | where 'source: 'target |
~= |
Aggregate | Aggregate | Structural mapping: Recursively matches and binds all lifetime leaves between two matching aggregate shapes 1-to-1. | Matching shared lifetime parameters |
~<= |
Aggregate | Aggregate | Structural outlives: Recursively applies outlives constraints to all corresponding leaves between two matching aggregates. | where 'source_i: 'target_i |
[!TIP] Outlives Intuition: Rust writes
'source: 'targetto mean "source outlives target" (source lives at least as long as target). Independs-rs,Target <= Sourcemeans "Target's lifetime is bounded within Source's lifetime" (Target $\le$ Source).
Path Expressions
| Syntax | Example | Description |
|---|---|---|
return |
return = text |
The return value root |
| Parameter name | text, cfg |
An input parameter root |
| Named field | cfg.name, return.parts.tail |
Struct field navigation |
| Tuple index | tuple.0, tuple.1 |
Tuple element index |
| Enum variant | return.Right.value, return.Pair.1 |
Enum variant field or tuple element |
| Container index | entries.0, entries.1 |
Multi-argument generic container type arguments (e.g. HashMap<K, V>) |
| Method receiver | self.data |
Field stored inside &self or self |
| Nested reference | input.deref |
Inner reference in nested references like &mut &mut T |
| Explicit lifetime | 'a, 'static |
Declared function lifetime or 'static |
Defining Borrowed Types with #[lifetimes]
Structs and Nested Types
#[lifetimes] generates independent lifetime parameters for each reference field. Field names determine parameter names. When types are nested, paths are concatenated to retain full lifetime granularity:
use lifetimes;
// Expands to: struct Split<'head, 'tail> { head: &'head str, tail: &'tail str }
// Expands to: struct Outer<'parts_head, 'parts_tail, 'label> { ... }
Because lifetimes remain distinct, a function can return parts.head from one source, parts.tail from another, and label from a third.
Tuples and Enums
Paths follow the structural shape of your type definitions. Tuple elements use numeric indices (.0, .1), while enum variants use their variant names:
use ;
;
// Expands to: struct Tuple<'prefix, T>(&'prefix str, T);
Generics and Standard Containers
-
Generic fields: Dependency paths follow field names rather than generic parameter positions:
use ; // To target `data` inside `value: View`: use `return.value.data` -
Containers (
Vec, arrays, slices): Collections of references share a single lifetime parameter per field:use lifetimes; -
Multi-argument containers: For containers with multiple type arguments (such as
HashMap<K, V>), paths use numeric indices (.0for key,.1for value) on the field (e.g.entries.0,entries.1).
Impl Blocks and Methods
When implementing methods on types decorated with #[lifetimes], attach #[lifetimes] to the impl block to automatically reconstruct the type's lifetime parameters:
use lifetimes;
// Expands to: impl<'data> View<'data> { ... }
Disentangling &self from Stored Fields
In ordinary Rust, fn data(&self) -> &str triggers lifetime elision, binding the return lifetime to the temporary &self borrow. Callers cannot release or mutate View while holding that return reference.
With #[depends], you can bind the return value directly to the stored lifetime in self.data, completely independent of the receiver borrow:
use ;
The enclosing self shape also applies to every bare Self occurrence. For example, an argument other: &Self exposes other.data, and a Self return type exposes return.data to dependency contracts.
Declaring Contracts with #[depends]
Exact Field Mappings and Broadcasts (=)
The basic building block maps an input borrow to a returned field:
use ;
// Lowered to: fn make<'text>(text: &'text str) -> View<'text>
When the target is an aggregate, = acts as a broadcast relation, assigning the source lifetime to all matching leaves. More specific relations override broader ones:
use ;
Extracting Inner Fields from Inputs
When an input parameter is a borrowed struct, you can depend on either:
- The temporary borrow of the wrapper itself (
cfg), or - An inner borrowed field stored inside the wrapper (
cfg.name):
use ;
Because the return value borrows 'name rather than 'config, callers can drop or release cfg while keeping the returned string reference valid.
In-Place Updates and Outlives Constraints (<=)
When modifying an existing borrowed value through a mutable reference (&mut View), ordinary assignment (=) is invalid because a function cannot rebind the caller's pre-existing lifetime slot.
Instead, use <= to express an outlives constraint ('source: 'target): the incoming data must live at least as long as the slot being modified (Target <= Source):
use ;
The constraint 'name: 'data ensures safety without forcing out to change its lifetime parameter.
Structural Operations (~= and ~<=)
When working with aggregate values by value or batch-updating aggregates, structural operators compare and map shapes automatically.
Structural Mappings (~=)
~= maps matching lifetime leaves 1-to-1 between two aggregate values. A by-value aggregate cannot be used as the source of =; use ~= instead:
use ;
The ~= relation maps return.name to old.name and return.config to old.config. The more specific = relation overrides the mapping for return.cache. The macro reports the first missing relative path if aggregate shapes do not match.
Structural Outlives (~<=)
~<= applies an outlives constraint across all matching leaves in two aggregate paths. Each source lifetime must outlive the corresponding target lifetime:
use ;
The relative paths below out and cfg must have the same shape. Use <= for single leaf constraints and ~<= when the whole aggregate must be checked.
Nested Mutable References (.deref)
Nested references have separate dependency paths. For input: &mut &mut i32, the outer borrow is named input, while the inner mutable reference is addressed as input.deref. When returning the inner reborrow, use input.deref <= input to specify that the outer borrow outlives the reborrow:
use depends;
Explicit Lifetime Sources and Targets
A declared function lifetime or 'static can be used as the source or target of a relation:
use ;
A declared lifetime can also be the target of an outlives relation when interfacing with an external type that already contains an explicit lifetime parameter:
use depends;
The generated signature adds 'text: 'a and preserves the external type's written lifetime argument.
Async Functions
Contracts work seamlessly on async fn. The generated lifetime belongs to the function signature, ensuring the returned future resolves to a borrowed value valid for the contract's duration:
use ;
async
async
async
The input must stay alive until the future completes and the returned borrowed value is no longer used.
Trait Methods
When a trait method returns a borrowed type, attach #[depends] to the method declaration. The same contract syntax works for signatures, default implementations, and async fn:
use ;
// Implementations can use the same contract.
;
The trait itself does not need #[lifetimes]. Rustc verifies that every implementation conforms to the expanded signature.
Consuming Transitions
If an in-place mutation cannot satisfy an existing lifetime slot (or you need to transition into a new lifetime), consume the old value by value and return a fresh one:
use ;
The caller drops ownership of the old view and receives a new view tied to text.
Working with Opaque and External Types
depends-rs expands lifetime shapes by querying compile-time metadata generated by #[lifetimes]. For external types or unannotated local types, the macro cannot inspect their fields and treats them as opaque boundaries.
Manual Opacity: opaque(...)
Use opaque(...) on #[lifetimes] or #[depends] to mark an unannotated type as a boundary. Pass the type path without generic arguments:
use lifetimes;
;
// Expands to: struct Holder<'text> { value: ExternalType, text: &'text str }
Here, return.value.field cannot refer to a field inside ExternalType. To expose its fields, annotate the type's definition with #[lifetimes] and remove the opaque(...) entry.
Automatically Recognized Types (Built-in Opacity)
Lifetime-shape lookup is skipped automatically for standard and primitive types, treating them as built-in boundaries. The complete list of special-cased types is:
- Primitive types:
str,bool,char,i8,i16,i32,i64,i128,isize,u8,u16,u32,u64,u128,usize,f32, andf64. - Standard library paths:
Any path whose first segment is
std,core, oralloc. - Unqualified standard types:
The unqualified names
String,Vec,Option,Result,Box,Cow,Rc,Arc,Cell,RefCell,UnsafeCell,Pin,PhantomData,MaybeUninit,HashMap,HashSet,BTreeMap,BTreeSet,VecDeque,LinkedList,BinaryHeap,Mutex,RwLock,Path,PathBuf,OsStr,OsString,CStr, andCString. - Type parameters & associated types:
Type parameters and paths starting with a type parameter or
Self, such asT,T::Item, andSelf::Item. - Explicit lifetime arguments:
Any path written with explicit lifetime arguments, such as
View<'a>,View<'static>, orView<'_>, even if the type has#[lifetimes]metadata.
[!NOTE] Path Resolution: These checks use the written syntax path without resolving type aliases or imports. A renamed standard-library type may need an explicit
opaque(...)entry, while a custom local type namedVecwill match the built-in list.
Type Arguments on Opaque Containers
Opacity stops inspection of a type's internal struct fields, but it does not stop recursive inspection of enclosing references and generic type arguments on the final segment:
- For
rows: Vec<&str>, it generates a lifetime parameter for&straccessible atrows. - For
rows: Vec<View>, an annotatedViewexposesrows.data. - Single type argument: Uses the enclosing field path (e.g.
rows). - Multiple type arguments: Uses numeric indices corresponding to the type argument order:
- For
entries: HashMap<&str, &str>, the key lifetime is addressed asentries.0, and the value lifetime is addressed asentries.1.
- For
External Types with Explicit Lifetimes
If an external type declares its own lifetimes, wire them using ordinary Rust lifetime syntax:
use depends;
Because ExternalView<'a> contains an explicit lifetime argument, metadata lookup is skipped automatically, so opaque(ExternalView) is unnecessary.
Cross-Module & Crate Integration
depends-rs relies on macro-generated metadata tokens attached to annotated items. Standard Rust visibility, aliases, glob imports, and cross-crate re-exports work out of the box:
use depends;
// `model` can also be a dependency crate.
use View as PublicView;
If depends-rs is renamed in your Cargo.toml, pass crate_path:
extern crate depends_rs as my_depends;
use ;
How Rustc Enforces Soundness
depends-rs does not bypass Rust's borrow checker or introduce unsafe code:
- No body inspection: The macros only rewrite function signatures and item declarations.
- Pure compiler checking:
rustcvalidates the function body, verifies that returned values match declared contracts, and ensures all outlives constraints hold. - Non-goals:
depends-rsintentionally avoids runtime checks, hidden typestates, Higher-Rank Trait Bounds (HRTB), Generic Associated Type (GAT) rewriting, compiler-internal type introspection, or inspecting unannotated external types.
Verification
To run tests, checks, and formatting:
cargo test --workspace --offline
cargo check --workspace --offline
cargo clippy --workspace --offline --all-targets -- -D warnings
./tests/compile_fail.sh
cargo fmt --all -- --check
License
Licensed under the Mozilla Public License 2.0. See LICENSE.