The implementation of the borrow checker


#1

I want to implement a borrow checker myself, so I tried to find some documentation about it. The resources is surprising few. The main introduction point of the implementation is here, but as someone on the irc said, it is “ancient” (1 year seems ancient in the sense of rust …) Is there any plan to release a new version of the doc?


#2

What specifically I don’t understand is the difference of checking mutability and aliasability. Isn’t aliasability equivalent to immutability?


#3

Not quite. You might have interior mutability.


#4

i.e. Cell types?


#5

Atomics are another good example


#6

Seems like the document doesn’t mention them at all …


#7

The difference between aliasability and mutability is about closure captures, not about interior mutability.

Borrow checker knows nothing about interior mutability, IIRC, that’s why interior mutability primitives are implemented with raw pointers.

This comment describes why immutable but not aliasable data is used: https://github.com/rust-lang/rust/blob/6d620843f62b6cf3182528ffcaa877eba461bfbb/src/librustc/ty/mod.rs#L577-L612 As the comment explains, this is not strictly necessary, the language could require mut annotations from users instead, but author of the current scheme (something tells me it was @nikomatsakis) decided that this would be too cruel.


#8

Is the aliasability check not needed without closures? I want to know the minimal design first, and then generalize the scheme further with special kinds of rules for ergonomics.


#9

@AndyShiue I’ve made a quick experiment and removed UniqueImmBorrow from the compiler (replaced with MutBorrow). Here’s what effect it had on the standard library: https://github.com/petrochenkov/rust/commit/42752eaec2f8795fba695e823881e3fbd2e50c74 The code that is penalized most is written in functional style and used in &mut self methods. However it doesn’t affect correctness, only some extra mut annotations are required. So if you are writing a minimal borrow checker, then UniqueImmBorrow can certainly be omitted.


#10

Local variables are never aliasable as they are accessible only within the stack frame.

I still don’t understand aliasability checking. Why does it say local variables aren’t aliasable?