19.2 Borrowing and Lifetimes
19.2.1 Motivation
In GNU R, borrowed access to heap objects requires manual registration. The PROTECT macro pushes a pointer onto a stack of GC roots, and the function calls UNPROTECT to pop it before returning. Forgetting PROTECT creates a use-after-free bug that may not crash until much later. Forgetting UNPROTECT leaves the stack unbalanced. R’s tree-walking evaluator prints a “stack imbalance” message when a builtin it called returns with the stack changed, but byte-compiled code is not checked, so the leak can pass without a message.
Rust handles the same problem for references with lifetimes. A reference carries a lifetime in its type, and the compiler checks, before the program runs, that the reference cannot outlive the value it points to. A dangling reference cannot exist in safe Rust code. That is the job PROTECT does by hand, with one limit this page comes back to: lifetimes cover Rust references, not the integer handles an interpreter like rrs uses for R objects.
19.2.2 The problem: temporary access and lifetime
Every reference points to a value. That value lives for a bounded time. If the reference outlives the value, dereferencing it is undefined behavior. In garbage-collected languages, the GC solves this by keeping values alive as long as any reference exists. In C, the programmer solves it by hand, with PROTECT in code that uses R’s API, or with other conventions.
Rust makes the lifetime part of the reference’s type, written &'a T when it is spelled out. If a function tries to return a reference to a local variable, the compiler rejects it.
19.2.3 Mental model: scopes and lifetimes
A value lives within a scope. A reference to that value cannot escape the scope. Here is a simple example:
fn make_number() -> i32 {
let x = 42;
x // x is returned, ownership moves out
}
fn borrow_number() -> &i32 {
let x = 42;
&x // ERROR E0106: missing lifetime specifier
}The first function returns the value itself, so ownership moves out. The second tries to return a reference to x, which dies when the function returns. rustc stops at the signature with E0106: the returned reference has no input to borrow from. Written with an explicit lifetime, as fn borrow_number<'a>() -> &'a i32, the same body fails with E0515, “cannot return reference to local variable x”.
19.2.4 Mechanism: lifetimes in function signatures
Every reference in a function signature has a lifetime, even when none is written. Here one is written out:
fn get_length<'a>(s: &'a str) -> usize {
s.len()
}The 'a is a lifetime parameter. It names how long the borrow of s lasts. The return type is a usize, an owned value with no lifetime, so here 'a constrains nothing and the compiler would accept the signature without it.
In most code the compiler fills lifetimes in. A function that takes several references and returns one has to say which input the result borrows from:
fn merge<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() > s2.len() { s1 } else { s2 }
}Both inputs have the same lifetime 'a. The output also has lifetime 'a. This signature says: “The returned reference is valid as long as both inputs are valid”.
Rust has two kinds of references. A &T is a shared reference. Many can exist at the same time, but none can mutate the value. An &mut T is a mutable reference. Only one can exist at a time, and it can mutate the value. Shared and mutable borrows never coexist.
let mut v = vec![1, 2, 3];
let r = &v; // shared borrow
// v.push(4); // ERROR E0502: v is borrowed as immutable
println!("{:?}", r); // last use of r: the borrow ends here
v.push(4); // OK: no borrow is live19.2.5 Relevance to my work
In GNU R, the PROTECT macro tells the GC: “Keep this value alive. I am using it right now”. The PROTECT stack is a manual registry of active references. The programmer is responsible for maintaining it.
Rust lifetimes do the same job for Rust references, automatically. A reference carries proof that the value is alive, and the compiler checks the proof once, at compile time, with no stack to manage and no UNPROTECT to forget. The PROTECT stack, by contrast, grows and shrinks at run time, a collection can start at any allocation, and an entry left on the stack keeps its object alive longer than intended.
Every SEXP in GNU R embeds GC bookkeeping, and even a read can write to an object: reading the data of an ALTREP compact sequence allocates and stores the expanded vector, and the collector sets mark bits on every object it reaches. C code must protect each SEXP it holds across a call that may allocate, unless the caller or an already protected object keeps it alive, or risk use-after-free.
rrs uses handles (u32 indices into the heap vector) instead of raw pointers. A handle is not a Rust reference and carries no lifetime, so the borrow checker cannot tell whether the object behind it is still alive. rrs answers that the way GNU R does: its collector treats a protect stack and a precious list as roots, and the evaluator protects what it holds across allocations. What the borrow checker does prove is narrower. The evaluator, Ev<'a>, holds one &'a mut Interp, so nothing else can touch the interpreter while it runs.
Rust’s rule that at most one mutable reference exists at a time is close to copy-on-modify. R lets a value be shared without copying, and copies it at the first modification while it is still shared. Rust rejects the shared mutation at compile time, so there is nothing to copy.
19.2.6 Other systems
C and GNU R rely on convention. Developers balance PROTECT and UNPROTECT by reading the code, and static checkers such as rchk find some mistakes, but the C language itself offers no help.
Other systems use different approaches. Python counts references and frees when the count reaches zero, with a cycle collector on top. Java uses a tracing GC. Neither approach lets you prove at compile time that a reference is safe.
19.2.7 Lifetimes in action: structs, annotations, and errors
A struct that holds a reference must declare a lifetime for that reference. The struct itself is tied to that lifetime.
struct Parser<'a> {
input: &'a str,
}
impl<'a> Parser<'a> {
fn parse(&mut self) -> Option<&'a str> {
let input = self.input.trim_start();
let end = input.find(' ').unwrap_or(input.len());
let (word, rest) = input.split_at(end);
self.input = rest;
if word.is_empty() { None } else { Some(word) }
}
}The Parser struct holds a reference to a string with lifetime 'a, so the compiler will not let the string be freed while a Parser that points into it is still in use. parse returns slices with the same 'a, not the shorter lifetime of &mut self, so a word it returns stays usable after the Parser is gone, as long as the string lives. rrs uses the same shape for its evaluator: Ev<'a> holds &'a mut Interp, one exclusive borrow of the whole interpreter, and the compiler will not let the interpreter be dropped or used by anything else while an Ev is live.
In most Rust code, lifetimes are inferred. Three elision rules fill them in for most signatures, so annotations are needed mainly when a function returns a reference and the rules cannot tell which input it borrows from, or when it has to tie the lifetimes of its inputs to each other. A lifetime is a compile-time proof obligation with no run-time cost. It records which reference outlives which.
Lifetime errors from the compiler can be confusing at first. A common mistake is naming a lifetime for the output without tying the inputs to it:
fn find_longest<'a>(
s1: &str,
s2: &str
) -> &'a str {
if s1.len() > s2.len() { s1 } else { s2 }
}The function promises a reference that lives for 'a, but s1 and s2 have their own unnamed lifetimes, unrelated to 'a, so rustc rejects it with E0621, “explicit lifetime required in the type of s1” (and the same for s2). The fix is to give both inputs the lifetime 'a, as merge does, or to return owned data such as a String. Returning a reference to a local variable, shown at the top of this page, has the same owned-data fix.
19.2.8 Comparison with garbage collection
A tracing garbage collector solves the lifetime problem by keeping all reachable objects alive. The GC runs periodically and marks all objects reachable from GC roots. Everything not marked is freed.
Rust solves it for references at compile time. A reference carries proof that the value is alive, and nothing is marked or traced at run time.
The trade-off is effort at design time: the programmer has to arrange the code so that the compiler can prove each borrow valid. The payoff is that a plain reference costs nothing at run time.
An interpreter for a garbage-collected language still needs a collector for the objects it manages, as rrs shows. Lifetimes check the Rust structures around that collector, not the R objects inside it.
Further reading
- The Rust Book, Chapter 10.3: “Validating References with Lifetimes”. https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html
- The Rust Reference: “Lifetime bounds”. https://doc.rust-lang.org/reference/trait-bounds.html#lifetime-bounds
- The Rustonomicon: “Lifetimes”. https://doc.rust-lang.org/nomicon/lifetimes.html
Where this appears
- r-in-rust (rrs) Lifetimes check Rust references. rrs still keeps a protect stack for R objects, because its handles carry no lifetime.