flowchart TD
interp["interpreter (owner)"] --> heap[("heap:<br/>Vec of values")]
interp --> syms["symbol table"]
heap --> v1["value: list"]
heap --> v2["value: closure"]
eval["evaluator"] -.->|borrows| heap
eval -.->|borrows| syms
19.1 Ownership
19.1.1 Motivation
Memory safety is one of the hardest problems a runtime engineer faces. In GNU R, the garbage collector owns all objects in the heap. C code borrows them as raw pointers and must register roots with PROTECT to stay safe. A forgotten PROTECT or an unrooted allocation is a silent use-after-free bug. The burden falls entirely on the programmer.
Rust moves this burden to the compiler. A static analysis proves each value has one owner. All borrows must obey a single rule: sharing and mutation cannot coexist. R’s copy-on-modify rests on a related idea, as the section on aliasing below shows. Once you understand ownership, you can reason about the lifetime of a Rust value without reading a garbage collector.
19.1.2 The problem: ownership of an R value
Every object needs a rule for how long it stays alive and when it can be freed. In a garbage-collected system, the GC decides automatically, at a cost: it has to trace live objects to find the dead ones, every object carries bookkeeping fields, and a collection pauses the program at a moment the program does not choose.
Rust takes the opposite approach. Every value has an owner, the variable or field that holds it, and the owner is responsible for cleanup. When the owner goes out of scope, the value is dropped. The compiler verifies that all accesses through borrows obey the rules. Nothing traces the heap at run time, so plain Rust values have no collection pauses.
For a runtime engineer, this forces a choice at design time about who owns each piece of state: the function that created it, a struct that holds it, or several places at once when it has to outlive its parent. In GNU R, the answer is always the GC.
19.1.3 The rule set
Rust ownership is built on four facts.
First: every value has exactly one owner. When you create a value, a variable or struct field becomes its owner. No two owners compete to free the same object.
Second: the owner decides when the value dies. When the owner goes out of scope, Rust automatically calls a drop function on the value. For heap objects, drop deallocates memory. For RAII types (resource acquisition is initialization), drop releases whatever resource the type acquired. Because there is one owner, there is one drop, at a point the source code shows.
Third: assignment moves ownership. If you write let y = x and the type is not Copy, ownership transfers from x to y and the name x can no longer be used. Types that are Copy, such as i32 and f64, are copied bit for bit instead, since they own nothing that needs dropping. The move rule stops two owners from both dropping the same value.
Fourth: borrows allow temporary access without taking ownership. A &T borrow is shared and immutable. Many readers can hold &T at the same time. An &mut T borrow is exclusive and mutable. Only one mutable borrow exists at a time. Shared and mutable borrows never coexist on the same value. The compiler enforces this at compile time.
The compiler rejects any safe Rust program that breaks these rules.
19.1.4 Mental model: the shape of data
Think of ownership as a tree. The root is a variable in a function’s scope. Its children are the fields and heap allocations it reaches. Each node has one parent: its owner. When the root goes out of scope, the whole tree is freed, depth first.
Here is what that looks like for a simple interpreter:
An interpreter owns its heap and symbol table as plain struct fields. The evaluator borrows both temporarily while it runs.
The interpreter struct is the root. It owns a heap (a Vec of values) and a symbol table. When the interpreter goes out of scope, the heap, its values and the symbol table are freed with it. The evaluator borrows the heap and symbol table but does not own them. Its borrows are temporary. They end before the interpreter is freed.
With one thread owning each interpreter, the heap lives and dies with its interpreter, and no other interpreter holds a reference into it, so collecting one heap needs no coordination with any other.
19.1.5 Mechanism: the borrow checker
Rust’s borrow checker runs at compile time. It enforces two rules on borrows.
Shared references are read-only. If you hold &T, you can read from T. You cannot mutate it, unless T is one of the interior mutability types covered in Arc, Mutex, and Interior Mutability. If one borrow is mutable (&mut T), no other borrow can exist (shared or mutable). The value is locked down until that exclusive borrow ends.
Borrows cannot outlive their owner. If a value goes out of scope, all borrows to it are invalid. The compiler tracks scopes and lifetimes. If a function tries to return a reference to a local variable, the compiler rejects it.
Here is Rust code that demonstrates both rules:
let mut x = 42;
let r1 = &x; // shared borrow
let r2 = &x; // another shared borrow, fine
// let r3 = &mut x; // ERROR E0502: cannot borrow x as mutable
// while r1 and r2 are live
println!("{} {}", r1, r2); // r1 and r2 end here
let r3 = &mut x; // OK now: r1 and r2 are no longer live
*r3 = 100;The comments describe what the borrow checker sees. A borrow ends at its last use, not at the end of its block (the compiler calls this non-lexical lifetimes, or NLL), so once the println! has used r1 and r2, the mutable borrow is allowed. None of this is checked at run time.
19.1.6 Aliasing XOR mutation: why this connects to R
R’s copy-on-modify stops sharing and mutation from meeting at run time. When code modifies a vector that more than one name refers to, R copies it first, so the other names never see the change. The price is the copy.
Rust enforces the same separation in the types. You can share a value (with &T), but you cannot mutate it. Or you can mutate it (with &mut T), but only from one place at a time. Outside the interior mutability types (Cell, RefCell, Mutex and the atomics), safe Rust cannot mutate a value while it is aliased (reachable through more than one name or reference). The compiler rejects the attempt.
This rule is called “aliasing XOR mutation”. R gets it at run time by copying, and Rust gets it at compile time by refusing the program. See r-objects for how copy-on-modify shapes the internal structure of R values.
In a Rust interpreter, the compile-time check covers the interpreter’s own data structures. It does not cover aliasing between R values. In rrs, R objects refer to each other through integer handles, which the borrow checker does not see, so copy-on-modify still needs a reference counter on each object, maintained at run time as in GNU R.
19.1.8 Thread safety and data races
A data race needs two threads touching the same memory with no synchronization, at least one of them writing. Rust rules it out with two marker traits, Send and Sync, that make thread safety a property of types. A type is Send if its values can safely move across thread boundaries. A type is Sync if its values can be safely shared across threads. The compiler implements these traits automatically for structs and enums based on their fields. See Send and Sync for the full picture, and Mutexes for how a lock makes shared mutation safe at run time.
19.1.9 Ownership models: C versus Rust
GNU R uses a simple model: every R object lives on the heap. The GC owns all heap objects. C code calls into R through the API and receives SEXP values, which are pointers to SEXPREC structures. Because the GC can run at any allocation, a SEXP pointer can become invalid after the code that holds it allocates memory. To stay safe, C code must register pointers as GC roots. The PROTECT macro adds a pointer to a runtime stack of protected roots. During GC, the GC traces from these roots. Before the function returns, it calls UNPROTECT to pop them.
GNU R uses a manual GC root registry. C code must PROTECT each SEXP it holds across any call that may allocate, unless the caller or an already protected object keeps it alive, and “Writing R Extensions” advises assuming that every API call may. After allocation, the code must PROTECT the result before the next allocation. A forgotten PROTECT is a silent use-after-free bug that often surfaces only under memory pressure, making it difficult to reproduce.
This approach works but places a high cognitive burden on the programmer. Writing correct R extensions requires deep knowledge of when allocation happens. The PROTECT/UNPROTECT dance is mechanical and error-prone. Here is how Rust differs:
In C, only the PROTECT discipline stands between a pointer and freed memory. In rrs, Rust ownership covers the interpreter and its heap, and objects are reached by index, so a rooting bug reads the wrong object instead of freed memory.
19.1.10 Relevance to my work: how rrs applies ownership
The r-in-rust interpreter uses Rust ownership for the interpreter itself, and keeps R’s own rooting discipline for R objects.
Each interpreter is a struct, Interp, that owns its heap, symbol table and string cache as plain fields. The heap is a Vec of heap objects. Dropping the Interp frees all of them together, with no collection needed.
Objects are not accessed by raw pointers. Instead, they are referenced by handles: indices into the heap vector. A handle is a u32 in a small Copy type, cheap to copy and with no pointer identity. Because a handle is not a Rust reference, the borrow checker does not track it, and two things follow. Inside one interpreter, R objects stay alive the way they do in GNU R: a mark-sweep collector traces from roots, and the roots include a protect stack that the evaluator pushes and pops much as C code uses PROTECT. A handle to an object the collector has freed indexes a slot that may now hold a different object. Across interpreters, nothing at the type level stops a handle from one heap being used in another; a test-time verifier catches it only when the stray handle lands on a freed slot.
rrs forbids unsafe_code in every crate except the few that implement R’s C API, and a local gate script checks it. Each interpreter is a Rust struct that owns its heap, collector, symbol table, string cache and protect stack as plain fields. Objects are referenced by u32 handles, not raw pointers. The interpreter’s mark-sweep collector still decides when an R object dies, rooted through that protect stack and a precious list, as in GNU R.
What the design removes is the C failure mode. A missing root in rrs can make the interpreter read the wrong object or panic, but the interpreter crates cannot write unsafe, so it cannot make them read freed memory.
Further reading
- The Rust Book, Chapter 4: “Understanding Ownership”. https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
- The Rust Reference: “Moved and copied types”. https://doc.rust-lang.org/reference/expressions.html#moved-and-copied-types
- The Rustonomicon: “Ownership”. https://doc.rust-lang.org/nomicon/ownership.html