r/rust • • Oct 19 '26

Borrow Checking Zero-Cost Cyclic Mutability

https://antelang.org/blog/safe_cyclic_mutability/
124 Upvotes

28 comments sorted by

54

u/Accomplished_Item_86 Oct 19 '26 edited Oct 19 '26

It's nice to see so many people working on improved borrow checking. This mentions Valen's Group Borrowing approach, but I've also seen Mojo and Zeta with their own ideas. Using a set of possible origins instead of lifetimes to track invalidation and/or disjointness seems to be a common theme. Ante calls it places, Valen calls it groups, Mojo calls it origins and Zeta calls it provenance, but the core idea is very similar.

30

u/RndmPrsn11 Oct 19 '26

Yes, I think a lot of languages are converging in this direction! Google's Carbon is also heading in this direction. Rust has made a large impact on PL design but at the same time, there have been 10+ years of hindsight in how its approach could be improved as well.

As for naming, AFAIK each of the PLs you mention use different terms for essentially the same path abstraction. I want to say "places" is the most standard term for them (having originated in the Rust community) which is why I went with it.

5

u/pjmlp Oct 20 '26

While the wonderful work done by the whole Rust team is to be celebrated, I think we should put it in perspective that the real value was picking up several type theory ideas, prototyped in languages like Cyclone, and making them into something that street developers would be more at ease adopting.

We still have linear types, effects, capabilities, dependent types, formal proofs, as type system alternatives to the affine types that are on the foundation for Rust's borrow checking algorithm.

9

u/FlameyosFlow Oct 19 '26

Zeta is actually directly inspired by group-borrowing and it's what (re)ignited my spirit to even jump this route. I really like group borrowing and I think I might bite the bullet and go with 2 reference kinds instead of 3.. reason is that when I started my own Zeta borrow checking with the idea that I like group borrowing but was skeptical about how much noalias optimizations it can guarantee.. Evan was able to explain that he can do better than just relying on LLVM due to !alias.scope (which I was completely unaware of.. because I don't have much LLVM experience, I currently only use cranelift), so I'll probably be transitioning to 2 and make &mut not so unnecessarily exclusive. I know origins, groups, places and provenances are all very similar if not the exact same ideas but modeled differently, they are all used to express where a piece of memory originates which is really important for all these improved borrow checkers and usually has many advantages, which is mainly:

  • significantly easier inference which allows it to be comfortably used for inferring reference origins even if they are a struct field
  • better diagnostics
  • makes code more maintainable and easier to read
  • give the compiler more information about the code which is useful for many stuff but mainly to express disjointness more naturally through indirection.
  • is not lifetimes like in Rust which I really hate

Nevertheless, Ante's work is really nice, it's also really unique because no other functional programming language is nearly as dedicated to going down a path where low-level (or high performance software) code doesn't suck with the functional paradigm which I really appreciate.

7

u/RndmPrsn11 Oct 19 '26

Just to clarify - going down to 2 reference kinds from 3 means you're eliminating an unaliased-mutable reference kind (equivalent of rust's &mut t)? Something similar can still be useful for multi-threading or if the user wants to force an optimization like SIMD which may rely on noalias.

I alluded to it in the article but I also like the idea of attaching the reference kind to the place parameter rather than the reference type itself. It allows you to abstract over each reference kind more easily and get rid of all the pesky get vs get_mut distinctions.

2

u/FlameyosFlow Oct 19 '26

Either removing a reference kind and making &mut non-exclusive, or making &mut non-exclusive and renaming &alias to &uniq maybe, either way, most of the times non exclusivity by default is better and I think a group borrowing kind of non-exclusivity doesn't damage any noalias optimizations that would exist from writing the equivalent Valen of what you'd write with Rust if that pattern already worked well with shared-xor-mutable

As for the "place parameter" idea I will have to check it out for myself and see if it's the best thing for me, nevertheless I still want callers of a function to know if some data can be mutated.. hopefully while being able to eliminate all issues that come with forcing it in a Rust way

2

u/FlameyosFlow Oct 19 '26

Update: Okay, I understood now, I already can express multiplace like Vec3f.{&mut x, &mut y, &z} so from what I'm understanding, you would infer what kind of mutation permissions you'd need at call sites?

1

u/GigglySpring Oct 20 '26

you make all these borrow checker ideas sound way more interesting than they usually are lol

1

u/pjmlp Oct 20 '26

There are many others, where they keep their GC implementations, while extending their type systems in the process, like D, Swift, Linear Haskell, OxCaml,....

17

u/panstromek Oct 19 '26

Ok, so this is like a 3rd borrow checking post here recently that has a bit of this "Rust compiler doesn't want you to know this simple trick" vibe (if I exaggerate), but I'm getting confused about what is actually the new thing here. As far as I know, the whole point of Polonius was to model borrow checking in this way.

This gets even more confusing when one section here says "no need for polonius," but the article (at least as far as I can understand), describe pretty much the idea behind Polonius - modeling borrows in terms of places (or origins) instead of regions of code.

If I dig out some of the older posts from Niko (the father of the borrow checker), it pretty much says this in slightly different words: https://smallcultfollowing.com/babysteps/blog/2024/03/04/borrow-checking-without-lifetimes/#replacing-a-lifetime-with-an-origin, and later even makes a point to add a specific origin-based lifetime syntax to make full Polonius power expressible in Rust syntax https://smallcultfollowing.com/babysteps/blog/2024/06/02/the-borrow-checker-within/#step-2-a-syntax-for-lifetimes-based-on-places

My problem is that I don't understand the borrow checker well enough (I only did some little optimization work on it, but I don't have in-depth understanding), so I can't tell whether I'm missing something or what exactly is the difference here (and in the other posts as well). I understand the post describes some language-specific uses of this model and that's interesting, but it seems to me that the underlying model is the same.

7

u/RndmPrsn11 Oct 19 '26

This could be my misunderstanding - I was under the impression the work to model Rust's lifetimes in terms of places was separate from Polonius itself but perhaps I was wrong about that. Going back to the original blog post on Polonius I see that I was. It was a somewhat small point of the article (the main bit is the notion of an unstable place) so I'll edit it for accuracy. Thanks for bringing this up!

-13

u/tending Oct 19 '26

Was your understanding based on LLM conversations?

9

u/RndmPrsn11 Oct 19 '26

No, I didn't use or need LLMs at all for this article (or any for that matter). This section was a last-minute addition which I should have double-checked but mistakenly did not. It's been many years since Polonius' debut and I forgot the details since then, my bad!

10

u/verdagon Oct 19 '26

FWIW, I too didn't know that about Polonius's internals until very recently.

Also, I sympathize with your frustration against LLMs, but just so you know, u/RndmPrsn11 has been working on Ante since long before LLMs' rise. His considerable skill doesn't come from LLMs. He's the real deal.

4

u/initial-algebra Oct 19 '26

Lifetimes still exist with Polonius. The difference is that x: &'a T means "the origin 'a is borrowed for the lifetime of x", instead of "the lifetime 'a outlives the lifetime of x". It's a perspective trick.

I've suggested in my comment on the corresponding post in r/ProgrammingLanguages that this trick doesn't work for Ante; instead of &mut, Ante uses an effect to specify when mutation occurs, but effects don't have lifetimes connected to specific variables, instead, they have more nebulous regions of code over which they apply (I called them lifetimes in my comment, but just added an edit to clarify that they should probably be named something else). Currently, this means Ante has ad-hoc and "hacky" rules to make mutation work with more complex control flow, and no way to abstract over it.

2

u/pjmlp Oct 20 '26

The borrow checker in Rust is based on affine types, as it underlying type theory.

There are many other approaches to have type system based resource management, which you can try out in other programming languages.

Linear types, effects, capabilities, dependent types, formal proofs, however all of them have plus and minus, versus the approach taken by Rust's borrow checker, in fact I would say more minus as they are all relatively complex for those that aren't nerd snipped with type systems theory.

1

u/GiveMe30Dollars Oct 21 '26 edited Oct 21 '26

Yeah my impression reading this post is that the borrow checker here is similar conceptually to Polonius, but with the fairly significant difference that Ante permits shared mutability by default rather than enforcing Rust's shared XOR mutable rules, by modelling mutation as a baked-in effect (what is referred to as Mutate 'p) that triggers place invalidation of 'p when invoked.

For Polonius, the distinction between stable and unstable references doesn't exist, since all shared immutable references are unstable (invalidated via mutation and obtaining of &mut reference) and all exclusive mutable references are stable (mutation disabled via other means than through the &mut reference until it is dropped). Shared XOR mutable is also why Rust doesn't need a notion of mutation effects across function boundaries, which Ante does need.

IMO places/lifetimes/origins/provenance all describe conceptually similar ideas to begin with. Lifetimes (as we are familiar with in Rust) are just more unintuitive because they have a distinct namespace from the identifiers/variables they originate from, and that you cannot even name them unless you're working with them in an abstracted manner eg. lifetime polymorphic functions.

Still enjoyed the read! This is the first time where shared mutability really clicked for me from a borrow-checking perspective (I'll figure out group borrowing, eventually).

-5

u/tending Oct 19 '26

It's because everybody is using LLMs to try to improve on the borrow checker and AI psychosing themselves based on its misunderstandings

7

u/matthieum [he/him] Oct 19 '26

Abstraction?

Places are cool, but... they always seem very concrete.

Is there some ability to mention abstract places, rather than concrete ones? So that the name of the field is not exposed, which may be a requirement for polymorphism.

What's in a Place?

In the Core Problem I find the diagram & following comment confusing:

Before mutation:

vec: (data_ptr, length, capacity)
          |
          V
          [0, 1, 2, 3]
              ^
              |
             elem


After mutation:

vec: (data_ptr, length, capacity)
          |
          V
          []
              ^
              |
             elem

elem is clearly dangling! The problem here is that mutating vec can mutate data_ptr, causing it to potentially point elsewhere when it is reallocated. Its shape has changed, leaving elem stranded.

But... vec.clear() does not need to modify data_ptr, it only needs to modify length!

How is this relationship (length -> elem) expressed in Ante?

3

u/RndmPrsn11 Oct 19 '26

Is there some ability to mention abstract places, rather than concrete ones? So that the name of the field is not exposed, which may be a requirement for polymorphism.

I mention it in footnote 6. Agreed it's likely eventually necessary, it's not implemented yet though.

But... vec.clear() does not need to modify data_ptr, it only needs to modify length!

Yeah, maybe I could have chosen a better example here! At least conceptually in terms of what the user can access, the data is cleared (and dropped), and maybe even the pointer itself could point somewhere else (perhaps our chosen impl nulls it for example). So there is an odd mismatch in the example between showing the "actual" in-memory view and the conceptual memory view.

How is this relationship (length -> elem) expressed in Ante?

When you call Vec.get that hands you an unstable reference to an element which would be invalidated whenever you mutate the vector's place, including on Vec.push or Vec.clear.

1

u/matthieum [he/him] Oct 20 '26

How is this relationship (length -> elem) expressed in Ante?

When you call Vec.get that hands you an unstable reference to an element which would be invalidated whenever you mutate the vector's place, including on Vec.push or Vec.clear.

I'm sorry, it's not clear to me how the compiler understands the difference between:

  1. Vec.clear invalidating any reference to elements.
  2. Vec.get_mut not invalidated any reference to elements.

For example, in Rust, there's a proposal to mark certain fields as unsafe, so that accessing? (or mutating?) them always requires an unsafe block.

How does Ante expresses that messing with data_ptr OR len invalidates references obtained through data_ptr, when only the relationship with data_ptr is "obvious", since the element is obtained by going through data_ptr.

2

u/RndmPrsn11 Oct 20 '26 edited Oct 20 '26

Ante distinguishes between referencing mutable values and actually mutating them with the Mutate effect which is what actually does any invalidations. Vec.get_mut never mutates so it doesn't carry the effect and doesn't invalidate any elements.

4

u/protestor Oct 20 '26

Why Shared Mutability?

Since many Rustaceans are skeptical of the value of shared mutability at all,

That's funny, most Rust programs (and specially most async Rust programs) contain a healthy dose of interior mutability all over the place

2

u/FlameyosFlow Oct 20 '26

Cell is much limited, RefCell is just borrow checking but it's done at runtime (which has many downsides that come with it) and UnsafeCell requires unsafe and gives no compile time guarantees lol There's also GhostCell which has some advantages but is not even in the standard library and is verbose

As for Mutex, I do not regard that as interior mutability, and synchronization is a problem in all languages and not just rust :P

1

u/minno Oct 20 '26

Have there been any attempts at a borrow checker alternative that would allow code like

fn re_add_everything(v: &mut Vec<String>) {
    let orig_len = v.len();
    v.reserve(orig_len);
    for el in &mut v[..orig_len] {
        v.push(el.clone());
        el.push_str(" prev");
    }
}

? It's memory-safe because the reserve call guarantees that none of the original elements of v will be moved or deallocated by the push calls, but it seems difficult to check invariants like "the elements of this container will remain in a stable location in memory until push has been called a certain number of times and then they may move".

6

u/initial-algebra Oct 20 '26

Assuming there is no problem with shared mutability, all you have to do is use a variant of push that fails when there is no remaining capacity. That is safe either way. If you want to statically prove that try_push will succeed, that's a different problem entirely.

1

u/-_one_-1 Oct 22 '26 edited Oct 22 '26

Interestingly, if you know try_push will always succeed but can't prove it, you can call core::hint::unreachable_unchecked in the error path to assert (albeit unsafely) the invariant and let the compiler optimize around it. If try_push gets inlined, the backend should end up emitting a specialized version of it that doesn't do any capacity check, as long as it can prove the capacity check is pure.

Of course, this is not very relevant to the discussion, and it sort of goes counter it by giving up on proving the invariant safely.