Less restrictive mutability rules, again

I'm seeing postings on other forums about new languages whose main feature seems to be a more relaxed borrow checker than Rust. This has come up many times before. I had a go at this back in 2024. The consensus seemed to be that it wasn't enough of a pain point to justify language changes.

But now we are seeing more activity in this area. Everybody has a new "improved Rust" language:

The Ante people identify two problems. One is the scope of a borrow extending beyond the last point of use. See the link above for an example. That's supposed to be fixed in the Polonious borrow checker.

The other is the good old back references problem. That can be handled in Rust with Rc, RefCell, Weak, downgrade, and upgrade. Ir works, but the resulting code is clunky. Dangling weak pointers are possible, although they lead to detected errors. Circular ownership and resulting memory leaks are possible and not easily detected.

So what's current thinking on this? Both problems seem fixable without a new language.

This old discussion again. My opinion is still that for the most part what Rust does works well, and it can even help guide you towards a better design, one that avoids pointer soup. Pointer soup is bad for two reasons: the code becomes harder to understand and reason about, and it is usually less efficient to execute since it tends to be cache unfriendly.

Usually some sort of arena design is a good better substitute since it at least increases data locality if nothing else.

3 Likes

Once again, I would be the one that offer a broader more open minded perspective. It is crucial to avoid being conservative, instead, one should be innovative, acknowledging both weaknesses and strengths, and not stopping at good enough but keep trying to solve the limitations. A limitation of the "borrow checker" in safe Rust is its inability to facilitate "shared mutability" without incurring a performance penalty (e.g., through Rc or RefCell). I encountered this firsthand while building an arena allocator: without resorting to unsafe Rust, I was forced to pay a performance cost for Rc and RefCell just to implement safe shared mutability, a cost that shouldn't actually be necessary, but arises solely due to Rust’s rigid "aliasing XOR mutability" design

Is there a solution that allows for shared mutability, without using unsafe and without the associated performance overhead? Rust could introduce a new type of reference: one that permits shared mutability while remaining guaranteed safe against issues like dangling references, use after free, unaligned addresses, etc, it would retain all the safety guarantees of standard safe references, with the sole exception of the one from exclusive mutability. This would represent a massive improvement over raw unsafe pointers

1 Like

The new reference is an "unsafe" reference, but it is far safer than a raw pointer

there's already a safe shared aliased reference with no unnecessary overhead: &Cell<T>. Sadly it's just not very ergonomic, iirc there's some work on making it more ergonomic by allowing you to easily get &Cell<Field> from &Cell<StructWithField>

2 Likes

No, you are quite mistaken. Cell is not the solution the user needs because it does not provide a reference, rather, it employs a "copy on read" mechanism. Cell does not return a reference, every time you read its value, a deep copy is performed, which incurs a performance cost. It is why, it only works for types that implement the Copy trait. This means it can not be used for Vector, String, Box, or other complex, built in types, as doing so would result in an expensive deep copy (malloc call + memcpy). That is not the solution required here

Cell can be used without needing to deep-copy allocating types, e.g.:

/// this has basically the same cost as normal Vec::push
pub fn push_to_cell_vec<T>(cell_vec: &Cell<Vec<T>>, item: T) {
    let mut v = cell_vec.take(); // no allocation
    v.push(item);
    cell_vec.set(v); // also no allocation
}

with the Cell field access language feature:

pub struct MyType {
    pub items: Vec<Type2>,
    ...
}

pub fn f(v: &Cell<MyType>) {
    // idk what syntax will be selected, so I picked ->
    push_to_cell_vec(v->items, Type2::new());
}
1 Like

This is fundamentally incorrect, it’s not "sharing," but rather "move", meaning only one instance can exist, you might as well just remove the cell entirely because the whole point of a "shared mutable reference" is to allow mutation without having to move the underlying value

Furthermore, because it operates "by value," you can not create two cells that point to the same vector, so it fails to solve the problem

Furthermore, it doesn't solve the limitation that only one mutable operation can occur at a time, the mutation process is still restricted to happening only once at any given moment

That's mostly not true. You do not need to perform a copy, nor need the Copy trait. In addition to what @programmerjake shared, there is also an unstable get_cloned which allows you to perform the "copy on read" without requiring Copy, although this cannot be implemented for all types implementing Clone. Most notably however this allows cloning a Rc<T> out of a Cell<Rc<T>>, which unlocks a lot of usecases. Ante has a similar problem though! There are different Clone traits based on the kind of reference you want to use to clone, and not all types can implement both of them.

Ultimately you cannot get a shared or mutable reference to the insides of a &Cell<T>, but that's also true of the "shared mutable" references in e.g. Ante.

Again, Ante for example has very similar limitations. Their "shared mutable" cannot give you access (any kind of access, including "shared mutable") to the insides of a unstable-stable type (which includes Vec, String, Box and enums, exactly the types you're complaining cannot be used with Cell!).

I should mention though that Ante appears to have "stable" references that allow you get this kind of access, but they have a different tradeoff: you are not allowed to mutate the shape of any unstable-shape type, or any type that could contain them.


Overall Ante and other similar languages are not magic. Most "shared mutable" references have very similar semantics as &Cell<T> with some syntax sugar on top for some "simple" usecases. They show that we can have a much better dev experience using Cell, but fundamentally there are limitations that both have to share and which make writing some kind of code impossible.

2 Likes

The getter method for the cell performs a copy. What @programmerjake is doing stems from a fundamental misunderstanding specifically this :

So the unstable get_cloned is not the needed solutiom. It still performs a "copy on read"

Edit: the name _cloned() already communicates it is duplicating the value. Still it is not the solution for the problem that I brought to the table, so kinda irrelevant

That is exactly what I’ve been saying all along: it’s a limitation of Rust. I also proposed a solution for it above

I wasn’t referring to Ante at all, I just wanted to point out a certain mindset, the tendency to think, "This is good enough," and then stop, which reflects a lack of pursuing the best possible solution

I provided my own solution above

It's totally sharing, just Vec doesn't have any API for Cell<Vec<T>>:

let v = Cell::new(Vec::new());
let a_bunch_of_shared_references = [&v; 4];
push_to_cell_vec(a_bunch_of_shared_references[0], a_bunch_of_shared_references);
// now v contains a bunch of references to itself

// push some more references, now through a different reference:
push_to_cell_vec(a_bunch_of_shared_references[3], a_bunch_of_shared_references);

you can't have two separate Cell's containing the same (by identity, not equality) value ever. what you can do, however, is have multiple references to a Cell<T>, which is basically like how C++ pointers/references work, the C++ equivalent of &Cell<T> would be something like T * or T &.

That's inherent to having a type (Vec) that is not designed to be modified simultaneously. Languages that don't stop you from modifying something simultaneously generally misbehave when you do, e.g. C++ std::vector has iterator invalidation which means it's generally UB to modify it simultaneously like that. IIRC Java has similar issues, just it causes misbehavior instead of UB. Python also misbehaves, e.g. here on my computer it skips the 3 when iterating:

l = [1, 2, 3, 4]
for i in l:
    print(i, l)
    if i == 2: del l[1]
    print(i, l)

outputs:

1 [1, 2, 3, 4]
1 [1, 2, 3, 4]
2 [1, 2, 3, 4]
2 [1, 3, 4]
4 [1, 3, 4]
4 [1, 3, 4]
1 Like

I think you'll have to define what is a "read" for you.

From this other comment it appears that to you &Cell<T> is not a "reference", but it is! Don't you see the & there?

Are you perhaps complaining that it doesn't provide a shared reference (a &T)? Then imagine we introduce a shiny new &shrmut T, but it doesn't allow you to get a &T out of it. Would that be ok with you?


Which "solution"? This one?

This is a wish, not a solution.

The restrictions on shared references, mutable references, Cell<T>, etc etc all exist to guarantee that safety. Some restrictions might be artificial and only exist because we haven't found an ergonomic way to lift them, others are fundamental in the model you're using. You want a safe reference without the fundamental restrictions that make it safe, which doesn't exist. The only thing you can do is exchange some restrictions with others, which might unlock usecases that don't require some of the freedom that you have with other solutions.

I'll consider it a "solution" when you propose a set of restrictions that are sound and enable ergonomic shared mutability.


You're being blind here. Do you not see the effort people are putting into improving Cell, like Cell::get_cloned and field projections? Just because people don't completely change how the language work doesn't mean they aren't looking for ways to improve it. You also need to consider what an experimental language and a solid production-ready one can afford to do and when.

2 Likes

So, that is a shared reference to the cell itself, not to the T, which, in that case, does allow the code to compile. Unfortunately, however, the code style incurs unnecessary performance costs. Take a look at this assembly comparison

use std::cell::Cell;

#[unsafe(no_mangle)]
fn a1(a: &Cell<Vec<i32>>) {
    let mut _v = a.take();
    _v.push(10);
    
    a.set(_v);
}


#[unsafe(no_mangle)]
fn a2(a: *mut Vec<i32>) {
    unsafe { (*a).push(10); }
}

The Cell :

a1:
	pushq	%r14
	pushq	%rbx
	subq	$24, %rsp
	movq	%rdi, %rbx
	movq	16(%rdi), %rax
	movq	%rax, 16(%rsp)
	movups	(%rdi), %xmm0
	movaps	%xmm0, (%rsp)
	movq	$0, (%rdi)
	movq	$4, 8(%rdi)
	movq	$0, 16(%rdi)
	movq	16(%rsp), %r14
	cmpq	(%rsp), %r14
	jne	.LBB8_2
	movq	%rsp, %rdi
	callq	<alloc::raw_vec::RawVec<i32>>::grow_one

.LBB8_2:
	movq	8(%rsp), %rax
	movl	$10, (%rax,%r14,4)
	incq	%r14
	movq	%r14, 16(%rsp)
	movq	(%rbx), %rsi
	movq	8(%rbx), %rdi
	movq	%r14, 16(%rbx)
	movaps	(%rsp), %xmm0
	movups	%xmm0, (%rbx)
	testq	%rsi, %rsi
	je	.LBB8_3
	shlq	$2, %rsi
	movl	$4, %edx
	addq	$24, %rsp
	popq	%rbx
	popq	%r14
	jmpq	*__rustc::__rust_dealloc@GOTPCREL(%rip)

.LBB8_3:
	addq	$24, %rsp
	popq	%rbx
	popq	%r14
	retq
	movq	%rax, %rbx
	movq	(%rsp), %rsi
	testq	%rsi, %rsi
	je	.LBB8_6
	movq	8(%rsp), %rdi
	shlq	$2, %rsi
	movl	$4, %edx
	callq	*__rustc::__rust_dealloc@GOTPCREL(%rip)

.LBB8_6:
	movq	%rbx, %rdi
	callq	_Unwind_Resume@PLT

The zero cost high performance one if there is reference that I talked about before :

a2:
	pushq	%r14
	pushq	%rbx
	pushq	%rax
	movq	16(%rdi), %r14
	cmpq	(%rdi), %r14
	je	.LBB9_1

.LBB9_2:
	movq	8(%rdi), %rax
	movl	$10, (%rax,%r14,4)
	incq	%r14
	movq	%r14, 16(%rdi)
	addq	$8, %rsp
	popq	%rbx
	popq	%r14
	retq

.LBB9_1:
	movq	%rdi, %rbx
	callq	<alloc::raw_vec::RawVec<i32>>::grow_one
	movq	%rbx, %rdi
	jmp	.LBB9_2

The version using the cell performs redundant unnecerery operations: it copies the metadata, zeroes out the original metadata, carries out a mutation, and then copies the metadata once more, all of which translates to extra memory writes. This scales at O(n) relative to the size of the metadata, for a Vec, that’s 24 bytes. Since the set method also copies the metadata, you end up with 48 bytes of copying, plus the overhead of zeroing out the original metadata. Now, consider a "fat" struct, for instance, one containing five Vecs and five Strings, where the metadata size reaches 240 bytes (24 bytes × 10). That results in 480 bytes of copying, and the cost of the zeroing process, all for just a single call

In reality, it should only require copying 8 bytes, the size of a reference, regardless of the actual size of the metadata being pointed to, so it is constant O(1), then would simply perform the mutation and be done without any copying again

that's where you can use the field projection I was talking about earlier to go from p: &Cell<My240ByteStruct> to p->one_of_the_vecs which has type &Cell<Vec<T>>.

Vec itself could also add new API so you can push directly to a &Cell<Vec<T>> which works because Vec can do field projection again to get access to its length, pointer, and capacity fields, on those reading/writing is just as efficient as if you were using a &mut Vec<T> (ignoring LLVM noalias stuff).

Cell<Vec<T>> can have any API where you don't hand out references to the T values, so it can have push, pop, by-value replacements for indexing (set_element, get_element, replace_element), len, and more.

2 Likes

I’ve already defined it above, if you care to read it: The solutiom that is needed is zero cost, equivalent to a raw pointer

If you read the definition of the getter for the cell, it returns a value, not a reference. The cell method mentioned above no longer meets the criteria because it incurs unnecessary performance costs (refer to my comment prior to this one)

The reference I’m proposing possesses all the standard capabilities of a regular reference, it can be converted into an &T just like any ordinary reference. The only difference is that the restriction on exclusive mutability has been lifted (reread my explanation on this before commenting further to make it clear)

Even though I’ve already written it out clearly and explicitly, it seems like you jumped straight to posting a comment without reading what the people you’re trying to chat with have already said. Doing this just leads to the constant repetition of points that have, in fact, already been written down. Here it is :

Once again, you’ve jumped straight to commenting without reading through the previous comments from the person you’re trying to chat with. I never wrote "safe reference", I explicitly wrote "unsafe reference", which is intended as an improvement over raw pointers, with zero cost. Here :

That is a solution design guaranteed to be implementable because it is sensible

Before you reply again, please go back and read all my previous comments, don’t let this happen again

No, I’m pointing out the limitations, specifically, being forced to pay a performance cost to work around them, with no zero cost alternatives available. Furthermore, there’s been no improvement in zero cost safety options. I only want to disable the checks for exclusive mutability, I shouldn't be forced to also disable checks for dangling pointers, use after free, unaligned addresses, and other checks that are completely unrelated to the requirements of shared mutability. Raw pointers and UnsafeCell disable all checks, whereas what is actually required for shared mutability is only the disabling of checks specifically for shared mutability

Will 'pin projection' be capable of creating complex data structures with interconnected references, such as graphs?

1 Like

And they are not disabled indeed, or provide a Miri-accepted example when they do.

assuming you meant field projections on Cell, yes, if you allocate the &Cells somehow so they have the same lifetime, e.g. using typed_arena. pin projection is an entirely unrelated thing allowing you to go from Pin<&mut Struct> to Pin<&mut Field>.

I decided to write out an example implementation of a Vec with a &Cell<Vec<T>> API:

They are disabled, run them yourself here to see it

use std::cell::UnsafeCell;

fn main() {
    let mut a = vec![10];
    
    let b = &raw mut a;
    
    drop(a); // b becomes dangling
    
    // but then, use after free. compiles successfully 
    unsafe { (*b).push(20); }
    
    // same story
    
    let cell = UnsafeCell::new(vec![10]);
    let b = cell.get();
    
    drop(cell);
    
    unsafe {
        (*b).push(20);
    }
}

The message you quoted says:

You asked explicitly for a reference that doesn't need unsafe: that's the opposite of an "unsafe reference".

You also asked for it to keep the same guarantees as the current references, but you never proved how that would be accomplished.

There are no checks for "dangling pointers, use after free, unaligned addresses" in Rust. The guarantee of their absense comes as a consequence of the borrowing rules, of which exclusive mutability is a fundamental part of. The moment you no longer enforce exclusive mutability, and you don't add equivalent restrictions like Cell does, then all those issue before possible again.