TL;DR: Borrow checking uses subtyping and generic parameters to analyze the lifetimes of references, then works backward through type matching to infer the lifetimes associated with borrow expressions. Comparing these against the scopes of the borrowed objects reveals two kinds of problems: dangling references and conflicts between mutable and shared access.
Here, a lifetime is distinct from the span of time between a value's creation and destruction. To keep the two concepts separate, this article calls the latter its scope.
What Is a Lifetime?
Lifetime analysis operates on MIR, represented as a control-flow graph (CFG), rather than on HIR, represented as an abstract syntax tree (AST). Specifically, a lifetime is a set of nodes in the MIR control-flow graph. If a lifetime contains point P, the reference is valid at P. Later, we will extend this definition to cover skolemized lifetimes: the named lifetimes in function definitions.
Lifetimes occur in MIR in two places:
- The types of variables or temporaries that hold references contain lifetimes.
- Each borrow expression has an associated lifetime.
The following pseudocode introduces three lifetimes, which we will call 'p, 'foo, and 'bar:
| |
'p is part of the type of p. It identifies the portions of the control-flow graph where p can safely be dereferenced. The lifetimes 'foo and 'bar come from borrow expressions and describe the periods during which foo and bar are borrowed.
Borrow-expression lifetimes are the foundation of borrow checking. In this example, the compiler imposes restrictions over the control flow covered by 'foo and 'bar:
fooandbarcannot be moved or dropped before their respective borrow lifetimes end.- Since
&fooand&barare shared borrows, the borrow checker prevents modifications tofooandbarduring those lifetimes. For mutable borrows, it would prevent access to the original objects during the corresponding lifetimes.
Lifetime Inference
To infer 'p, 'foo, and 'bar, the compiler converts the example into a control-flow graph. Nodes A0, B2, and C0 correspond to p = &foo, p = &bar, and print(*p), respectively:
| |
Liveness Constraints
The borrow checker first computes variable liveness. A variable is live if its current value may be used later in the program. p is assigned at A0, reassigned at B2, and used at B0 and C0. The key is that at B1, the current value &foo will not be used again along that path, so p is dead there. Also note that a variable only holds its new value after assignment: p is therefore considered dead at A0 and B2 as well. This convention is useful when solving lifetime constraints.
Lifetimes are then computed from liveness: if p is live at point P and its type contains the lifetime 'p, then 'p includes P.
This gives:
| |
Mapped back to the source code:
| |
MIR also has a DROP(variable) operation, which can extend a variable's liveness. Interestingly, liveness for this purpose does not necessarily extend every lifetime in the variable's type. Dropping &'a T or &'a mut T, for example, does nothing, so it does not matter whether 'a is still valid. We say 'a may dangle during destruction in such cases. For a type F<'a> implementing Drop, however, 'a generally must not dangle during destruction.
RFC 1327 defines which lifetimes may dangle during destruction. We therefore add another rule: even if a variable's current value may later be dropped, lifetimes in its type that are allowed to dangle do not need to include the current node merely for that drop.
Compared with lexical scopes, lifetimes are much more flexible and can even contain holes: discontinuous regions of code. This is why RFC 2094 calls them non-lexical lifetimes.
Neither 'foo nor 'bar appears directly in a variable's type, so neither has any directly live nodes.
Subtyping Constraints
In programming language theory, subtyping is a form of type polymorphism that allows a subtype to replace its supertype. Operations applicable to a supertype must also work for the corresponding subtype. Wikipedia describes the relationship as follows:
If
Subis a subtype ofSuper, the subtyping relation (written asSub<:Super) means that any term of typeSubcan safely be used in any context where a term of typeSuperis expected.
Subtyping is common in languages with inheritance, such as C# and Java. If Cat inherits from Animal, it is intuitive that a Cat can replace an Animal wherever the latter is expected, making Cat a subtype of Animal. Rust does not have inheritance; the subtyping discussed here arises from lifetimes.
The Rustonomicon explains the lifetime relationship this way:
We define
'aas a subtype of'bif and only if'aoutlives'b, written'a: 'b.
This may initially seem backward. But just as Cat has the properties and methods of Animal, 'a contains the nodes defined by 'b. A subtype extends its supertype and carries more information.
The Rustonomicon's explanation is a simplification. Subtyping for non-lexical lifetimes is location-aware: the point where the relationship is required matters. At A0, the borrow expression &foo produces a reference of type &'foo T, assigned to p of type &'p T. We must ensure that &'foo T is a subtype of &'p T. Because the new value of p is first visible at A1, however, the relationship only needs to hold at the successor of the assignment, such as A1; nodes at or before A0 are irrelevant.
This produces the following subtyping constraints:
| |
Variance rules convert them into lifetime constraints:
| |
Reborrow Constraints
Reborrowing is another source of constraints.
To define these constraints, we first introduce supporting prefixes. Starting from an expression, we strip away field projections and dereferences *, stopping when we reach the dereference of a shared reference. The expressions encountered form its supporting prefixes:
| |
Now consider a borrow of the expression exp:
| |
We compute the supporting prefixes of exp and find every dereference of the form *e. Calling the lifetime of e 'a, we add the constraint ('a: 'b) @ P, where P is the node at which the borrow takes effect.
For more examples, see Reborrow constraints.
Solving the Constraints
Once the constraints have been generated, the compiler solves them by fixed-point iteration. It initializes the lifetimes, then repeatedly visits the constraints and expands the sets until all constraints are satisfied.
A constraint ('a: 'b) @ P means that, starting at P, 'a must contain every point reachable within 'b. The compiler performs a depth-first search through 'b from P, traversing possible paths in the CFG and adding each visited valid node to 'a. A path ends when it leaves 'b. From A1 in our example, the search can reach B0 and C0, but not B3 or B4: the hole in 'p stops the if path at B1.
Solving the constraints gives:
| |
Named Lifetimes
So far, we have only discussed borrows within a function, where the compiler can infer the relevant lifetimes. Passing references across function boundaries requires explicit lifetime annotations. Apart from 'static, Rust declares generic lifetimes using syntax such as <'r>. At each function call or type instantiation, 'r is instantiated with a particular region of code.
In particular, a named lifetime such as 'r in a function definition is modeled as a set containing at least:
- Every node in the current function's CFG.
end('r): some points in the caller, or its callers, after the function returns.
We extend the lifetime constraint definition accordingly. For ('a: 'b) @ P, if 'b can reach the end of the current function's CFG from P, every end('_) contained in 'b is added to 'a. Consider:
| |
The generic lifetimes initially give:
| |
Returning x requires &'a u32 <: &'b u32, producing the constraint 'a: 'b. We must therefore add end('b) to 'a, obtaining 'a = {F, end('a), end('b)}.
The compiler then checks that whenever a generic lifetime 'a contains end('b), a where clause or implied bound establishes 'a: 'b. Otherwise, it reports an error.
Borrow checking does not analyze across function boundaries. It checks definitions and calls separately. Consider:
| |
We want Rust to reject this: the shared reference x points into data, while we attempt to borrow data mutably. The borrow checker need not understand that "points into" relationship directly. After desugaring the indexing operation, it sees a call to Index::index:
| |
The lifetime of x is inferred as {L3, L4}. From the signature of Index::index and the subtyping constraints, the lifetime of &data is also inferred as {L3, L4}. This conflicts with &mut data at L3, producing an error.
The compiler's built-in lifetime 'static means remaining valid until the program ends. Like 'a, it includes an element end('static), representing the rest of the program's execution after the current function returns.
String literals remain valid throughout execution, so references to them can have type &'static str. A common misconception is that an object referenced for 'static must have been created at compile time and must be immutable. By leaking memory, however, we can obtain an &'static mut T pointing to memory allocated at runtime:
| |
'static is a subtype of every lifetime. We can assign s to t because ('static: 'a) @ L3 always holds:
| |
Variance
Lifetime subtyping raises another question: if 'sub <: 'super, should a type constructor F<'_> also satisfy F<'sub> <: F<'super>? To answer this, we need the concept of variance.
Variance is a property of a type constructor that describes how subtyping between simpler types determines subtyping between compound types. A type constructor is a generic type written as F<T>. For example, Vec takes a type T and produces Vec<T>; & and &mut take a lifetime 'a and a type T, producing &'a T and &'a mut T. Rust has three kinds of variance. Given that Sub is a subtype of Super:
F<T>is covariant ifF<Sub>is a subtype ofF<Super>: the relationship is preserved.F<T>is contravariant ifF<Super>is a subtype ofF<Sub>: the relationship is reversed.F<T>is invariant if neither subtyping relationship holds betweenF<Sub>andF<Super>.
To balance safety and flexibility, Rust defines the following variance rules:
F<'a, T, U> | 'a | T | U |
|---|---|---|---|
&'a T | Covariant | Covariant | |
&'a mut T | Covariant | Invariant | |
*const T | Covariant | ||
*mut T | Invariant | ||
UnsafeCell<T> | Invariant | ||
[T] and [T; n] | Covariant | ||
Box<T> | Covariant | ||
PhantomData<T> | Covariant | ||
fn(T) -> U | Contravariant | Covariant | |
dyn Trait<T> + 'a | Covariant | Invariant |
Some types' variance rules can be understood by comparison with others:
Vec<T>and other containers follow the same variance rules asBox<T>.*const Tand*mut Tfollow the rules of&Tand&mut T, respectively.UnsafeCell<T>provides interior mutability, so its variance matches&mut T.Cell<T>and other types with interior mutability followUnsafeCell<T>.
Covariance of &'a T and &'a mut T over 'a is intuitive: wherever a short-lived &'short T is expected, a reference valid for the longer lifetime 'long is safe to provide. But why is &mut T invariant over T?
If it were covariant over T, writable access would allow us to store a short-lived reference in a location expected to hold a long-lived reference, causing a safety problem:
| |
assign mutably borrows ptr and redirects it to world. But ptr is declared to hold an &'static str; printing it after world is freed would be undefined behavior. To prevent this, &mut &'static str must not be a subtype of &mut &'a str.
Similarly, because &mut T permits reading T, contravariance would let us extend the apparent validity of T, also creating dangling references. &T, in contrast, only permits reading, so it can be covariant over T, but not contravariant.
Both &mut T and Box<T> provide readable and writable access to T. Why, then, can Box<T> be covariant? When subtyping occurs, ownership invalidates the old Box<T> after a move and ensures its value is not borrowed by a third party. This is an advantage of Rust's ownership system; the same design would be unsafe without those guarantees.
The following example illustrates this:
| |
After the call to assign, we have consumed boxed_ptr, the only value that retained the original 'static type information, so we cannot misuse it afterward.
The last case to tackle is function pointers.
Consider fn() -> &'a str. Calling a function of this type returns a reference valid for 'a, so it is safe to substitute a function of type fn() -> &'static str. If a caller expects the supertype &'a str, receiving the subtype &'static str is safe. Thus, fn(T) -> U should be covariant over U.
The same reasoning does not apply to arguments. A function of type fn(&'a str) accepts references valid for 'a or longer, while fn(&'static str) accepts only references valid for 'static. We can substitute the former for the latter, but not the latter for the former. Thus, fn(T) -> U should be contravariant over T.
Function arguments are the only source of contravariance in Rust, which explains why it is uncommon in practice. Encountering it requires function pointers that accept references with a particular lifetime, rather than any lifetime. The latter involves higher-ranked lifetimes, a separate mechanism discussed below.
We have now covered the standard library types. The variance of structs, enums, and unions depends on their fields. If a generic parameter appears in fields with conflicting variance requirements, it becomes invariant. For example, this struct is covariant over 'a and T, but invariant over 'b, 'c, and U:
| |
T: 'a and use<'a>
Rust can also constrain generic types using lifetimes, with the syntax T: 'a. This requires T to remain valid throughout 'a, much as &'a T describes a reference valid for 'a.
What makes T valid for 'a? If T contains references, their lifetimes must outlive 'a so they cannot dangle within it. A type without references, such as i32, Box<i32>, or String, satisfies the bound automatically: using it does not involve dangling borrowed references. In particular, T: 'static means that T cannot contain any non-'static references.
Every &'a T satisfies &'a T: 'a, and its well-formedness implies T: 'a: if T cannot be valid for 'a, neither can a reference to it. For a reference to a reference, &'a &'b T, we therefore obtain 'b: 'a. Conversely, constructing &'static Ref<'a, T> requires the corresponding outlives relationship.
The bound T: 'a can also apply to an opaque return type, impl Trait. Consider this code, which fails to compile:
| |
Without an explicit use<> bound, the opaque return type can implicitly capture generic parameters in scope. In this example, the compiler captures 'a for impl Fn(&'a str), as if adding use<'a>. The meaning of use<'a> differs from + 'a: the former captures the generic lifetime, while the latter imposes an outlives bound equivalent to T: 'a on the returned type. This distinction does not change the outcome of this particular example, but it matters when several lifetime parameters are involved:
| |
constraint fails because (a, b) does not satisfy both T: 'b and T: 'a for arbitrary 'a and 'b. capture succeeds by capturing the necessary lifetimes. The bounds on constraint demand validity over both lifetimes, effectively their union, whereas the return value of capture is usable over their intersection.
Returning to the earlier example, call the lifetime captured by phi 'f and the two borrow lifetimes 'x and 'y. Liveness makes 'f include L2, L3, and L4. Since phi is treated as impl Fn(&'f str), 'x and 'y must extend to L4, resulting in errors.
One solution is to add + 'static to the return type: impl Fn(&'a str) + 'static. The bound ensures that the hidden type does not contain non-static references tied to 'f, even if that parameter is captured. In the analysis above, 'f then appears only in the subtyping constraints ('x: 'f) @ L2 and ('y: 'f) @ L3, allowing the relevant regions to be inferred as empty.
Another solution is an explicit precise-capture bound that omits the unnecessary 'a, using use<> here, or use<T> when an in-scope type parameter T must be captured. The actual closure type does not use 'a.
A more elegant solution removes the lifetime parameter: fn say_some(name: String) -> impl Fn(&str). Here, Fn(&str) desugars to for<'a> Fn(&'a str), allowing phi to accept references with any lifetime.
Higher-Ranked Trait Bounds
A higher-ranked trait bound (HRTB), written as for<'a> Trait<'a>, means "implements Trait<'a> for every lifetime 'a." The for<'a> binder introduces an independent lifetime, decoupled from the surrounding context. Compare the meanings of the two versions of say_some:
fn say_some<'a>(name: String) -> impl Fn(&'a str): Given a lifetime'aand a valuename: String, returnphi = say_some::<'a>(name), whose type implementsFn(&'a str)for that particular input lifetime.phitherefore accepts that particular&'a str.fn say_some(name: String) -> impl for<'a> Fn(&'a str): Given a valuename: String, returnphi = say_some(name), whose type implementsFn(&'a str)for every'a.phican therefore accept references with different lifetimes.
This describes HRTBs semantically. Thinking of generic parameters as eventually being instantiated with particular "values," the effect of for<'a> is to postpone choosing 'a from the call to say_some until each call to phi.
The Fn(A) -> B notation is syntactic sugar for the underlying tuple-based Fn trait, with argument tuple (A,) and output B. Rust requires the sugared notation because the underlying form of the Fn* traits may change.
for<'a> also applies to function pointers and trait objects. Higher-ranked types have another subtyping rule: they are subtypes of types obtained by replacing their higher-ranked lifetimes:
| |
Which types satisfy a bound such as for<'a> Trait<'a>? Function types and the Fn* traits provide a useful example.
Every function definition in Rust has its own zero-sized function item type implementing Fn*. Consider a function with generic parameters <'a, T>:
| |
Its function item type and Fn implementation are roughly as follows, omitting FnMut and FnOnce:
| |
The function item type FooFnItem<T> has the generic type parameter T, but no lifetime parameter 'a. Instantiating the function item infers the "value" of T:
| |
phi has type FooFnItem<String>. From the impl, this type implements Fn(&'a String) -> &'a String for every 'a, so it can be passed to want_hrtb:
| |
In fact, for any T, the bound FooFnItem<T>: for<'a> Fn(&'a T) -> &'a T holds.
The call phi(&String::new()) desugars to phi.call(&String::new()), and the compiler chooses an independent 'a for each call. For foo, T is selected when the function item is instantiated, while 'a is selected when it is called. The former is early-bound; the latter is late-bound. Only late-bound lifetimes can become higher-ranked in this way.
Early-bound generic parameters can be supplied through turbofish syntax. Late-bound parameters cannot, because there is no corresponding slot in the function item type:
| |
When generating a function item type, the compiler handles generic parameters according to these rules:
- All generic type parameters
Tare early-bound. - Generic lifetime parameters
'aare late-bound unless:- They appear in bounds, as in
fn foo<'a: 'a>() {}orfn bar<'a, T: 'a>() {}. - They are used only in the return type, as in
fn foo<'a>() -> &'a String {}. - The function is inside an
implblock and the lifetime is declared byimpl<'a>.
- They appear in bounds, as in
For a more detailed explanation, see the Rust Compiler Development Guide.
Finally, we can extend this view of early and late binding beyond Fn*:
| |
Developments in Borrow Checking: Polonius
The borrow-checking implementation still has some limitations. Rust is developing a new borrow checker, Polonius, to address them.
The well-known cve-rs is unrelated to those limitations. It stems from a trait solver bug. In brief, when handling subtyping of higher-ranked lifetimes, the trait solver can incorrectly erase information before borrow checking runs. Without the necessary information, the borrow checker cannot detect the resulting dangling references. Addressing this requires work on the next-generation trait solver.
Polonius changes the analysis. It first creates a loan at each borrow point, recording the access path, the associated set of references, and whether the borrow is mutable or shared. Whenever an access path is read or modified, it considers loans associated with that path and its parent paths. It checks whether any associated reference is live at that point and whether the access violates the loan's mutable or shared restrictions. A live loan that is violated produces a compilation error.