What is a good mental model of borrow checker?

This would probably be ideal, we already do pretty much the same for compiler errors.

Does it make sense to display this information for all points in the program, for a single variable? In particular, highlight any regions where the hovered variable is useable in this way. This is what I think I mean by "lifetime range hints" (although references may become unusable, then become usable again later, so it really should be "lifetime union-of-ranges hints").

Yes, I feel like I may have derailed this somewhat, sorry for that. However my reasoning is that a "good" model is one which is easy to visualize. This is not even strictly related to IDE tooling - can I draw my reasoning in a particular model with pen and paper using pictograms, boxes, lines, etc., without appealing to complex algebraic rules? I think that if we had a model which was naturally amenable to visual reasoning in this way, IDE tooling would naturally fall out of it.

There's two difficult parts here:

  • The mapping for B to U is 1:many - a single borrow can be used many times, so your visualization has to have some way of showing all of the ranges B to Un for all n in an unambiguous fashion.
  • Given a pair B, U, there are multiple possible As. Again, this makes doing a good visualization hard, since while errors can just point to one A and say "this is a previous invalidation point", a good visualization has to tell me about all the As that cause me to have trouble.

It'll also be true that in the error case, many (perhaps all) of the As in your situation will also be Us from the context of other triples (B, U, A). Again, for error messages, this is not a problem (you only need think about the (B, U) pairs that result in an error, and for each of those, you need only pick one A), but for the visualization case, it's a challenge.

A lot of conversation has definitely happened here, and I will confess that I am guilty of not reading the whole thread. I like to make the following general talking points:

  • I don't think it is generally useful to think of local variables as having lifetimes. It is unfortunate that the term "lifetime" tends to make people think about the scope of a variable, but scopes really aren't the important thing here. Rather, what's important are borrows and mutable borrows, and the bit about scope can mostly be handwaved by saying that dropping or deinitializing (read: moving without Copy) effectively takes a mutable borrow.
  • Borrowing a value (e.g. &expr and &mut expr) creates what is known as a loan. The goal of the borrow checker is to prevent a &mut loan from coexisting with another loan of the same thing. It does this by identifying every loan that occurs in a function body and tracing the regions through which each one is active in the control flow graph.
  • These loans are represented in the type system using lifetime annotations.
  • Values in rust can carry loans, which we express in the type system by writing T: 'a. And here is where the word "lifetime" begins to make sense, because you can also think of this as notation as expressing a "lifetime constraint." Most values have a constraint of T: 'static, meaning they can live as long as you want. But sometimes you have T: 'a, meaning it can only live for as long as the loans in 'a do not conflict with anything.

Some more resources on this:

Can you explain a bit more the interaction between Pin/Unpin and &mut exclusivity. (not that I expect a complete picture after your comment that nobody understands it yet, but a brief introduction would be much appreciated)

What took my interest in your phrasing here is that you emphasize this is the case for built-in place evaluation which suggests that these are not available for user created structures. Is that correct?

I assume here you refer to what I call partial moving (is that close to its official name? ) i.e

struct A {
    a : String,
    b : String
}  

let x = A{a: "hello".to_string(),"world".to_string()};
let z = x.a \\ here I moved out of x, which means x is not in a valid state
let w = x.b \\ but I can still use x   

I always wanted to know the story that how it works and when is it allowed, I vaguely remember that if the struct implements drop it is disabled. I would like to here more about it and its interaction with borrows and lifetimes, can you explain your point more?

The short version of it is that async allows you to hold references to locals across .await points. But those references are derived from / aliasing the Pin<&mut F> used to drive the future, causing a problem if we naïvely treat that outer reference as exclusive.

The usage pattern works out in practice, but formally justifying why, as well as how to communicate this to optimizing backends, is not clear.

Yes; or to be more specific, user defined DerefMut and IndexMut implementations. The compiler tries very hard to make it that the validity of code depends only on the signature of functions, and not their implementation; this means that when functions aren't involved, the compiler has a more complete picture and can allow more things.

That's it, really: whenever a type is used, it must be complete. If a type implements drop, the drop counts as a use. Because any[1] operation could potentially panic, a type with a drop implementation can't even temporarily be incomplete.

This doesn't interact with borrowing at all; it's just the normal fact that mutating a place conflicts with any borrows previously derived from your access method.


  1. Being pedantic, built-in place evaluation and copies/moves can't panic. In theory, Rust could allow moving out of and back into a field of a drop-having type if you do absolutely nothing in-between. It doesn't currently, though; use mem::swap or mem::replace to do so instead, which use unsafe to implement essentially that. ↩︎

Simple comparison in code: [T] slices have built-in indexing, while Vec<T> uses the Index/IndexMut traits.

fn f(x: &mut [(u32, u32)]) {
    let r1 = &mut x[0].0;
    let r2 = &mut x[0].1;
    std::mem::swap(r1, r2);
}

compiles, whereas

fn f(x: &mut Vec<(u32, u32)>) {
    let r1 = &mut x[0].0;
    let r2 = &mut x[0].1;
    std::mem::swap(r1, r2); // compilation error
}

doesn’t.

But in this case,

fn f(x: &mut Vec<(u32, u32)>) {
    let r = &mut x[0];
    let r1 = &mut r.0;
    let r2 = &mut r.1;
    std::mem::swap(r1, r2);
}

can be used instead.


Similarly for Box<T> with built-in dereferencing, vs cell::RefMut<T> using the Deref/DerefMut traits.

fn f(x: &mut Box<(u8, u8)>) {
    let r1 = &mut x.0;
    let r2 = &mut x.1;
    std::mem::swap(r1, r2);
}

vs

fn f(x: &mut std::cell::RefMut<(u8, u8)>) {
    let r1 = &mut x.0;
    let r2 = &mut x.1;
    std::mem::swap(r1, r2); // compilation error
}

but the latter can be saved using

fn f(x: &mut std::cell::RefMut<(u8, u8)>) {
    let r = &mut **x;
    let r1 = &mut r.0;
    let r2 = &mut r.1;
    std::mem::swap(r1, r2);
}

or

fn f(x: &mut std::cell::RefMut<(u8, u8)>) {
    let (ref mut r1, ref mut r2) = **x;
    std::mem::swap(r1, r2);
}

So, this is just an extension of your point that when thinking about lifetimes and borrows one should think about the desugared versions where method calls t.met() are resolved as {Type of t}::method(self) and operators t op y are resolved as <{Type of T} as {Trait related to the operator>}::Op(self, y) and the additional point that even though v[1] seems like a univocal expression, it desugars to two different things.i.e. if v is a vector it uses Index and IndexMut if v is a slice it does not go through those traits.

And surprisingly, the ones that do not use trait indirection are better integrated with borrowchecker so that borrowchecker can track disjointness of the references more easily.

I think it is surprising because the whole reason of implementing operators as traits is that it is supposed to allow you to integrate your own user defined types with the rest of the language so that they should be like primitive types, i.e. whether a type is built in or user defined should be an implementation detail not a API concern. :frowning:

(AFAIU) field expresions like a.f also have this integration and in that case it does not matter if it is a user defined struct, which is a relief. Are there other expressions that one should be aware of?

This point is excellent!

But I have two issues with your comment.

The easy one: is it best to conceptualize the issue in terms of concrete type vs type constructor, or in terms of lifetime elision. For example, when explaining fn(x:&String) -> &str we do not say this function is from a type constructor to another type constructor, but we say it is a lifetime generic function where the lifetimes are elided. So, the issue does not dispute your excellent point, but just asks if we were to add to the roadmap how should we formulate it?

The second point I do not get the point of your example,

AFAIS you think the problem in this example is that it fails to relate input parameters to the output parameter. So, the take closure is unspesific in its return type.
But after just adding some lifetime bounds to take_closure that do not constrain O but only I and the example compiles.

fn take_closure<'a, F, I: 'a, O>(f: F)
where
    F: Fn(&'a I) -> O,
{
    let _ignored = f;
}

Can you explain a bit about your example?

I would like to hear more about how can write functions generic with respect to their output whether they return reference or non-reference values, and how GAT's and other features help in that case. Can you tell more and give a few examples?

I don’t think there’s a conflict. After realizing that the notation “&String” is incomplete type information since there’s a whole to be filled where the lifetime is to be specified, the topic of lifetime elision is a separate one about whether the compiler complains about “&String” being only a type constructor missing one lifetime argument, or whether the compiler can follow some useful rules so it can fill this hole for us (in a sense allowing us to do some useful “abuse of notation”).

In situations where no elision rules modify the meaning of our syntax, the compiler complains about

type Foo = &String;

very similar to how it complains about

type Foo = Vec;

emphasizing that both are type constructors missing an argument.

For usefully describing what this type means, naturally it makes most sense to talk about its semantic meaning after type elision rules “fixed” the notation, not before. There is more than merely a type constructor as argument type here because it was implicitly re-written to for<'a> fn(x: &'a String) -> &'a str for us. A type constructor couldn’t be an argument type anyways, since a type constructor is not a type. It’s a type constructor, you can use it to construct a type by passing the required/missing arguments.


I think @quinedot's point is that lifetime elision is often so good, and the hole in a type written “&T” is so well hidden, that people learning Rust can easily ignore the fact that “&T” is not a single type, but desugars to &'a T with some generic <'a> introduced elsequere, and the consequences of this fact can have surprising effects, including a bad error message in the code example at hand. The type elision rules made F: Fn(&I) -> O into F: for<'a> Fn(&'a I) -> O, the closure became generic (specifically, in a many-input-types–to–single-return-type way) implicitly, and possibly surprisingly to inexperienced users.

The proposed solution of yours of using F: Fn(&'a I) -> O for a fixed caller-provided lifetime instead can often be a non-solution nonetheless, notably in the cases where take_closure’s implementation would try to call the given closure on a reference to a local variable. That’s the difficult to solve question if you still want to allow fairly generic return types, i.e. not restrict it to the form for<'a> Fn(&'a I) -> &'a O, but more something like “for<'a> Fn(&'a I) -> O<'a>” which would hover not be valid rust if O is a generic argument. That’s where GATs can help though.

I think there's at least three areas of discussion going on here, at least in my... meta-model? :sweat_smile: ...of the topic.

  1. What's a good mental model of the borrow checker (and how does one build it)?

  2. What are some concrete "lifetime cookbooks" or "niche knowledge areas" that can be used to demonstrate borrowing scenarios and tune one's model?

  3. How does the borrow checker itself reason about these things?

They're related, but not the same thing, IMO.


Regarding (2) cookbooks:

When I wrote up the below list, I was thinking in "cookbook" mode. Once I wrote it, I looked at it and thought "this isn't really a model of borrow rules though," so I almost just deleted it. But you seem to be getting value out of the examples, so here it is.

  • Beginner?
    • Promotion -- &0 and "hi there" are &'static i32 and &'static str
  • Intermediate?
    • Implied bounds: &'x T implies T: 'x
    • Lending iterators vs Iterator trait (collectable iterators)
    • Don't try to own data and a reference (&) to that data in the same struct ("self-referential struct")
    • Trait object lifetimes (mainly ... they exist; "learn when it bites you")
  • Advanced? (I think these are all "learn if they bite you")
    • Drop scopes -- running a destructor counts as a use
    • Temporary lifetime extension
    • Return position impl Trait (RPIT) lifetime mechanics
    • How to work around "abstracting over borrowed or owned types"
  • Niche knowledge (unlikely to encounter unless you're curious)?
    • Trait object lifetime exceptions and interactions with inferred outlive constraints
    • Exploiting implied bounds
    • Late bound vs. early bound parameters
    • Actually constructing self-referential structs in safe Rust

Regarding (3), there's this and the Polonius blog posts referred to earlier, if that is useful to you, but note that (a) they are not complete (b) the implementation has probably changed since the RFC as (c) it's changing in at least minor ways all the time.

Reading those did help tune my mental model, though personally I find them too low-level or emergent-behavior-esque to be my mental model. But YMMV.


More backlog...

@steffahn did a great job of exploring that area in illustrated detail. The key to my side-bar, which I did not go into detail on, was:

That is exactly the same case as the function call case I mentioned: The &mut you pass to a function goes away at the end of that function, too. [1] It's hidden by the replacement action in the first insert_then_get illustrated example, but there's a concrete &mut there during the function body.

So:

(2) self <--mut@* -- insert_then_get::self
(3) self <--mut@* -- immut

Is short for the uncollapsed form:

(2) self <--mut@* -- insert_then_get::self
(3) self <--mut@* -- (insert_then_get::self [dropped]) <--shared ?*-- immut

Where shared ?* means "there's no constraint on how the function does it, but (given the immut output) it must be presumed that they did some shared access at some point".

So you need a third rule:

  • Reborrows (of references) can outlive the value liveness scope (not the lifetime) of the reborrowee

(I'd argue you need the rule as this is in contrast with most exclusive-chain-of-access situations, where a link's liveness scope ending will invalidate everything beyond it; alternatively you need a rule for all of those. In either case, there are different semantics.)


  1. Even if you pass it back, I believe you actually pass back another reborrow. ↩︎

Haha, right at this very moment a new user asks a question about exactly that behavior :smiley:

(though that one could also be explained with the Copy behavior of shared references… re-borrows are more relevant for mutable references)

Yes, you're drilling into the heart of it. Let's compare:

fn take_hr_closure< F: Fn(&   I) -> O, I,     O>(f: F) { let _ignored = f; }
fn take_closure<'a, F: Fn(&'a I) -> O, I: 'a, O>(f: F) { let _ignored = f; }

The first says that F must accept any lifetime [1] and produce the same output, O, for any lifetime. It can be called with any lifetime; the caller of take_hr_closure has no say in what lifetimes it will be called with. The lifetimes have no lower bound.

Incidentally, a desugared version would be
fn take_hr_closure<F: for<'any> Fn(&'any I) -> O, I, O>(f: F)

and F is a higher-ranked type.

The second says that F must accept one specific lifetime ('a) of the caller's choosing. The lifetime does have a lower bound: it's impossible for the caller of take_closure to choose a lifetime shorter than the call to take_closure.

These are very different things! Instead of ignoring the closures... let's use them!

fn take_hr_closure< F: Fn(&   I) -> O, I: Default,      O>(f: F) {
    let i = I::default();
    f(&i);
}

fn take_closure<'a, F: Fn(&'a I) -> O, I: Default + 'a, O>(f: F) {
    let i = I::default();
    f(&i);
}

The second does not compile because of the aforementioned lower bound. The contrast is even more stark for &mut / &'a mut.

Here's a comment that drove this home for me. It's a bit dense.


Here's an example with some brief explanation at the top. It was written before GAT stabilized, but in brief this pattern:

trait Indirect<'a> {
    type Arg: 'a + FromValue<'a>;
}
// Or sometimes
trait Indirect<'a, _Lifetime_Guard = &'a Self> {
    type Arg: 'a + FromValue<'a>;
}
// Elsewhere
where T: for<'a> Indirect<'a>

are GAT simulations of

trait Indirect {
    type Arg<'a>: FromValue<'a>;
}
// Or
trait Indirect {
    type Arg<'a>: FromValue<'a> where Self: 'a;
}
// Elsewhere
where T: Indirect

I have a cleaner playground version in my drafts somewhere.


  1. that is well-formed, i.e., cannot be outside of I's validity ↩︎

Let me try to narrow it down using another analogy:

What is a model of planetery motion? Here are two

Some the questions you can ask about these models (with grossly simplified answers)

  1. What is a good model of the planetery motion
    The heliocentric model.
    Why? because it can explain the retrograde motion of the planets it can explain the phases of Venus etc. etc.
  2. How does one develop a model?
    Get expreienced in to topic, follow the scientific method experiement, form hypotheses and test them. The usual stuff.
  3. Which one is the correct model?
    The one whose predictions matches with what you observe.

Now let us get back to model of borrowchecker

So we can ask the same questions about the it.

How does one develop it? You learn about type systems, you make analogies with other languages that you know. The usual stuff. I think this is not the question we should pursue now.

When is it a good model? When it can explain more phenomena. So this is where we disagree, you think what we might be looking for are cookbooks, niche knowledge areas, just for the sake of demonstration of life time scenarios. Actually, we are supposed to be looking for phenomena that the model supposed to explain, not cookbooks, niche knowledge areas. If our model does not explain these phenomena it is a bad model. So, we should improve it. So, the value we got from examples, or topics relevatnt to borrow checker is not for the sake erudition, but for improving (or even finding) a suitable model.

Which one is the correct model?
The one agrees with the actual conclusions of the borrow checker. But here is the important part, it does not say that the one that follows the same steps with the borrow checker. The steps are in our mental model, we can use it to make predictions about the results of the borrow checker, as long as the results match we do not care even when they do not follow the same steps. So, we should be crystal clear what steps we take when we reason in our mental model and formulate them clearly, and see whether they lead to correct predictions about the results of the borrowchekcer but we dont need to care about and formulate exactly the steps taken by the borrowchecker.

So, what would you say if we just narrow the topic of conversation to the mental model of the borrow checker, and facts and topics that the model is supposed to explain, and its conformance to the results of actual borrow checker? and ignore the acquisition of the mental model, and the nitty gritty details and algorithms of the borrow checker(but not its results)

A couple more earlier threads if you want to deep dive on the higher-ranked stuff

But the boldtype-in-textbook summary is still

  • &T is not a (single, concrete) type [1]
  • Generic type parameters must resolve to a single, concrete type

And the small textbook-infobox-example is

  • fn(&String) -> &String [2] does not satify a <I, O> Fn(&I) -> O [3] bound
    • Because O would have to match &String but that's not a type

  1. and there is no higher-ranked for<'any> &'any T type ↩︎

  2. aka for<'any> fn(&'any String) -> &'any String ↩︎

  3. aka <I, O> for<'any> Fn(&'any I) -> O ↩︎

This talk of geocentric and heliocentric models makes this thread start remind me of Euclid's Elements.

In Euclid's famous book demonstrates 465 proofs of all manner of things, many quite complicated, in 13 chapters. A total of 130,000 words, on 545 pages. Rather like this thread, no?

However Euclid starts with only 5 very simple axioms that school children understand and anyone can remember:

  1. A straight line may be drawn between any two points.
  2. Any terminated straight line may be extended indefinitely.
  3. A circle may be drawn with any given point as center and any given radius.
  4. All right angles are equal.
  5. If two straight lines in a plane are met by another line, and if the sum of the internal angles on one side is less than two right angles, then the straight lines will meet if extended sufficiently on the side on which the sum of the angles is less than two right angles.

And all the rest of the book follows from those axioms. It is not necessary to remember all the proofs in the book. One only has to remember the 5 axioms, then one can recreate everything else.

These axioms form a "model". Typically called Euclidian Geometry. Change one of those axioms and we have different models. Notoriously changing the 5th axiom results in hyperbolic geometry or whatever.

Similarly we see a lot of discussion here, all kinds of demonstrations of borrows and lifetimes. Which, quite frankly, get complex enough I stop following.

The OP asks what is the model of the borrow checker. Surely that is akin to asking what are the axioms of the borrow checker? As far as I can tell they go like this (correct me if I am wrong):

  1. No data can be used before it is created.
  2. No data can be used after it is destroyed.
  3. If data is used for writing there can only be one user.
  4. If data is only used for reading there may be many users.

What have I missed? Following Euclid I feel there should be a fifth axiom.

Of course I have expressed the axioms very non technically, casually speaking of "data" and "using". Perhaps someone could write them more technically referring to "bindings", "references", "borrows" or whatever.

Like Euclid these axioms should be self evident to the reader. Of course we don't want to use uninitiated data (1), of course we don't want use after free(2), of course we don't want race contains(3 and 4). All else that the compiler complains about should be understandable from these few axioms.

Like Euclid with these axioms in mind, the model, everything else should be deducible by the reader, every compiler borrow checker area should be understandable. All be it not so obviously.

That's it, that is my mental model.

I think the union of regions U_n is fine. As a first approximation, we don't need to distinguish between the different points U on a too-granular level - talking about statements (or full subexpressions) is probably enough. This would obfuscate cases where a borrow live in one subexpression, and not live in another subexpression of the same expression (if that is even allowed), but code like this seems sufficiently rare.

I think the same visualization applies, take the union of all A_n regions. This might be more difficult in practice, as the borrow checker might not even compute all of the potential A location, but just picks one arbitrarily. This is okay too (maybe even preferred, if we want to stay close to how existing errors are reported) - since we can fix the first A error, then get a new error message, etc.

This is also a line of reasoning which applies uniformly to both correct and incorrect programs. For a correct program, the set A is empty for every B.

On the other hand, this is two ways of saying the same thing. You agree that "the model" and "tricky cases the model must handle" are different things.

The disagreement is in how useful going over increasingly exotic test cases is to explaining a model. Using the planetary motion analogy, I don't need to work through where the geocentric model is insufficient in order to explain the geocentric model. (In fact, that's rather the inverse of the actual dependency; you need to understand the model to show it's inaccurate.)

The point of a "mental model" IMHO is that it's simpler than the real model, and in order to be simpler it either it merely stops short of considering further implications of the basic axioms, or it is overly strict in some edge cases. A simplified mental model is then "valid" if it does not lead to incorrect deductions; any cases where it oversimplifies, it does so in the safer direction[1] that can be handled by carving out special allowances moving the simplified model towards the actual.

I believe the fifth axiom does exist, and should be something along the lines of the validity/soundness (for safe and unsafe uses respectively) of function lifetime annotations depending solely on the contract of the annotated lifetime signature. Function signatures serve as an abstraction boundary, and must be valid/sound under the other axioms independent of whatever arbitrary (safe) code may be on the other side of the boundary. (Formally, an unbound forall constraint.)

The first refinement of those axioms needs to shift writing/reading to unique/shared, or explain that shared mutability counts as a read. After that, I think it's a complete set of axioms for both safe code and positive-reasoning unsafe code.

Negative reasoning

Negative reasoning relies on having a fully accurate model, because you're relying on something never happening. Arguing the soundness of unsafe is fundamentally a negative reasoning, e.g. "the unsafe preconditions cannot be violated by safe usage of this API surface." The extra tricky part is that the negative reasoning for soundness doesn't just need to hold for this version of the language and these versions of the libraries, it needs to hold for all future semver-compatible language and library versions and all combinations of such.

This is how you get theoretically independently sound unsafe abstractions which are unsound when used together. An easy example I like — it's easy to incorrectly assume that being behind Rc prevents &mut access (but Rc::get_mut exists), or that the type not having been dropped means weak pointers are still valid (but Rc::make_mut exists). Negative reasoning is impossible to do soundly without a fully accurate model splitting things into three — things which are allowed, things which are forbidden, and the open middle; things which are impossible, but not forbidden from being possible.

A simplified model must be idempotent in order to perform negative reasoning. Simplifying inaccuracies are not idempotent, because they forbid some things which are actually allowed to happen. An idempotent simplification must be careful only to move possibilities to the open middle where conclusions cannot be derived from their (non)possibility.

... in Rust

The Stacked Borrows proposed full model contains three types of borrows — shared immutable, shared mutable, and exclusive. This is relevant in that it's not valid to assume that &T references are immutable. The pinning API was designed extremely carefully such that you can still assume &mut T is exclusive, but this is weakened to an API/soundness guarantee rather than a language guarantee, so compiler optimizations based only on the lack of UB can't rely on the lack of nonexclusivity.

The proposed opsem model is very careful to define things in an operational manner, such that the validity of an execution (lack of UB) is possible to show via positive reasoning. Lack of UB is a proof of a negative, but can be shown by proving every operation done is defined. The careful definition of the model and what behaviors are Undefined are what allow the compiler to do negative reasoning and assume that UB does not occur.

Until we have an officially adopted model, any negative reasoning in user code is dangerous. You can soundly do it, if the negative reasoning is purely about code you control. If you're relying on negative reasoning about what code you don't control does, that requirement must be passed on to the caller via the API(s) with that requirement being unsafe.

It's not untenably bad; Rust's unsafe model gives us a powerful way of controlling access to violating preconditions. We can make safe APIs where all soundness conditions are maintained internally to the abstraction. Then we can use those safe APIs without worrying about the subtlety of the soundness proof. Bugs will still happen in safe code, but when they happen, at least it still behaves in a defined manner where debugging tooling can be used to understand what's happening at the same level the code's written at.




  1. Caveat! Such "simplification by inaccuracy" is safe only so long as it is idempotent. See the fold about negative reasoning. ↩︎