Introduction
Linear types are types whose values must be used exactly once, in all branches a program can take. To be “used” here means “used by some operation”, for example by passing, returning, storing, or destroying the value. This is as opposed to not being used in an operation, which in a stack language would be akin to the value being popped off the stack.1
To expand on this: linear types are types which in the substructural types framework allow for “exchange”, but not “weakening” or “contraction”. In a stack language, this allows linear values to be reordered, but not freely discarded or duplicated: each must be consumed exactly once.
Rust’s type system is affine, which means you can’t use a value after it’s been moved, preventing classes of bugs like use-after-free. Linear types are even stricter and require that a value must be used, preventing bugs like memory leaks.
In this post I will cover how to encode linear types, their interaction with various language features, and how to model these interactions in the language using effects. I’m writing this post after having had conversations about this with Jana (Hexcat). Even though I’m writing this post from my perspective, I did not arrive at the insights in this post on my own. Thank you Jana!
RAII counts as use
For a while the intuition for how to add linear types to Rust was as a form of
extra-strict
#[must_use]
which required that a type must never be dropped. This was painful because if
accepted, it would break common operations like branching and reassignment. Rust
relies heavily on destructors, and forbidding them means we’re now fighting the language.
let x = Foo {};
if cond {
consume ( x);
} // Error: x is dropped in the `else` branch My most important contribution to progressing linear types for Rust has been the insight that RAII counts as a valid “use”. Linear types in literature1 don’t stipulate by which method they should be used. They only require that values are never yeeted out of memory without being used as part of some operation. And there is no reason why Drop::drop couldn’t be that operation.
“Literature” meaning the chapter on substructural types in “Advanced Topics in Types and Programming Languages”.
let x = Foo {};
if cond {
consume ( x);
} // Ok, destructor called in the `else` branch If this isn’t intuitive, think about it this way: if we want to guarantee that we never leak any sockets or file descriptors, all we need to do is guarantee that their destructors are always called. We can try to do that by hand, but we might make mistakes and so we can’t fully guarantee it. Linear types give us the tools to make those guarantees as a part of the language.
Linearity and divergence are mutually exclusive
Say we have some trait Leak which when absent means: “this type is linear”.
We could introduce some type Foo which has linear semantics as follows:
/// When a type is `!Leak` it implements linear semantics
unsafe auto trait Leak {}
/// A type which has linear semantics
struct Foo { .. }
impl !Leak for Foo {} What we now have to do is guarantee that any instance of Foo has its
destructor run. The easiest way to break that guarantee is probably the
following:
let x = Foo {};
loop {} Here we create an instance of Foo, but its destructor will never be called. That is because loop {} loops forever and never terminates. Let’s try another program that does something very similar:
let x = Foo {};
std:: process:: exit ( 0 ); Here too we never actually run the destructors of x, because the program terminates before we have a chance to run them. Its docs specifically call out that destructors won’t be run. Now on to one last program:
let x = Foo {};
panic! ( "oh no" ); This program will run the destructors of x when compiled with panic=unwind, but it won’t when compiled with panic=abort. And since that option exists outside of the type system, we have to assume that panicking may not run destructors.1
I plan to dig into unwinding and panicking more deeply in a future post. For the purposes of this post: just assume that all functions which may panic also imply divergence. Though I suspect that we can split unwinding and divergence from panic.
What all of these examples have in common is that they return the never type (!). That is because they never actually return, instead interrupting the usual flow of the program. As a rule, linear types cannot be held across operations which evaluate to !.1
Local control flow like return, break, and continue (and by extension ?) is also typed !, but it is fine: control is handed back to an enclosing scope, which runs destructors on the way out. The problem is only operations which never hand control back.
But that’s not enough to guarantee linearity: we can emulate infinite loops via recursion too, and so we need rules for that as well. For example:
fn bar () { bar () }
let x = Foo {};
bar (); This snippet is no different than if we called loop {} at the end. The destructor will never run, despite the return type of bar being unit (()) and not never (!).
The divergence effect
In effect systems, all of these forms of divergence are captured by the divergence effect. This is often shortened to div. Under the effect rules we’re proposing, functions which carry an explicit !div marker are guaranteed to terminate (“converge”). Using the with-notation that would look as follows:
fn foo() with !div { ... } // function
let x = || with !div { ... }; // closure
let x = with !div { ... }; // block The way this works is by restricting the set of allowed operations in a !div function to only those which the compiler can prove will terminate. Just like with const, this should be deny-by-default: all operations are disallowed unless we can prove them safe. In Rust that would mean no loop {}, and no calls to functions returning never (!). But also no recursion, even through indirection:
// recursion, but with more steps
fn a () { b () }
fn b () { c () }
fn c () { a () }
a (); Indirect calls through function pointers and trait objects would also be disallowed by default, unless their types carry the !div marker too (e.g. dyn Fn() with !div).
Some amount of looping would still be possible, but only over provably bounded iterators. In today’s Rust, something like TrustedLen, restricted to a finite upper bound, could provide the length guarantee. In an effect-aware version of Rust, we would also require Iterator::next to be !div, since TrustedLen currently does not prohibit divergence:
The iterator must produce exactly the number of elements it reported or diverge before reaching the end.
The rule for linear types would be something like: “Values of types implementing !Leak may only be held in !div contexts”. Since !div contexts also prohibit diverging expressions like loop {} and calls to functions returning !, that then solves their interaction:
Foo: !Leak | fn bar() -> ! | |
|---|---|---|
with div | Disallowed | Allowed |
with !div | Allowed | Disallowed |
This means that linear values can’t be held across, say, a server’s accept loop.
Linear values can only be held within !div contexts, which themselves may be
used within a loop. But as I’ve covered
before: with effects around 80% of a
typical program does not need to carry any effects at all, 15% may want to error or
diverge, and only around 5% touches IO.
Leak is not Forget
There is also a weaker guarantee than !Leak we can provide via
!Forget. !Leak guarantees a destructor is always run, but !Forget guarantees
that when a type goes out of scope its destructor is run. The difference is that
!Forget never actually guarantees a value will go out of scope, it only explains
what will happen when it does. A different way to think of it is that
!Forget prohibits a type’s lifetime from being promoted to 'static.
To enable a futures-based version of thread::scope we likely can get away with
only requiring !Forget. Ideally we would start with Forget and only
introduce Leak later on. But since Forget: Leak, any code relaxing its
bounds to ?Forget would still imply Leak. We would need to make
sure that introducing Leak later doesn’t end up being a breaking change.
Put together, the two traits might look something like this:
/// Types whose destructor is not guaranteed to run.
///
/// This is a type compatible with diverging functions. These
/// are functions which may contain unbounded loops, recursion,
/// and calls to operations returning `!` (never).
pub unsafe auto trait Leak {}
/// Types whose lifetime can be promoted to `'static`.
///
/// Types implementing `Forget` may be passed to `mem::forget`,
/// or placed in `Rc` or `Arc` cycles created through `UnsafeCell`.
/// These types may also be held for the remainder of the
/// program via `Box::leak`, `thread::spawn`, and `static`.
pub unsafe auto trait Forget : Leak {} External termination
Something linear types cannot model is behavior which exists outside of the program’s boundaries. Linear types cannot guarantee destructors are run if, say, the kernel crashes, or the computer it runs on loses power. The way to improve program resiliency in those cases could be by fixing bugs in the kernel and using an uninterruptible power supply (UPS).1
Also particularly interesting here is durable computing.
The way I think about linear types is that they work in tandem with improvements to program execution environments. A more stable kernel and a UPS are not quite as impactful if the software we run on them constantly crashes. And vice versa: running ultra-stable software on failing hardware doesn’t create a good experience either.
Conclusion
In this post I’ve explained what linear types are, how we can encode them in
Rust using Drop, how they interact with the never type, and finally how we can
encode the divergence effect in the language to manage the interactions between
linear types and the never type. We also looked at the weaker !Forget
guarantee, which may be a good first step towards full linearity.
Non-divergence is not the only requirement for linear
types, we also need to rule out things like mem::forget, Rc cycles, and
statics. But being able to prove it certainly is an important requirement.