Notes
2026/11/30

Mutable shadow borrowing

There's something interesting we can do if older values are guaranteed to sit lower on the stack than younger ones and heap fragments are never referenced directly. Last-use analysis usually prevents in-place mutation in a purely functional language if the original value will be used again later. But we can relax this slightly by allowing mutability for shadowed variables if there are no other references (but the original reference will come back into scope when the shadowing ends). Here's an example:

x = mut([1, 2])
{
    x = push(x, 3)
    print(x) // [1, 2, 3]
}
print(x) // [1, 2]

In a language like Rust, we could mutably reborrow in the inner scope, but any mutations then remain observable in the outer scope. If we want to keep any mutation in the inner scope unobservable in the outer scope, it seems we can't push onto x in the inner scope, because the mutable borrow from the outer scope is merely shadowed and the original x will come back into scope for the second print(x).

But that's too restrictive. The mutation in the inner scope is not destructive to x as long as we're only pushing/popping/setting new elements and never mutate the existing ones of x. Mutating the borrowed value is then fine as long as we guarantee that we “give it back unchanged” once we're done with it, by truncating it to its old length.

This is easy if our lifetime system already follows a stack-based model where older values sit lower on the stack than younger ones. We only need to keep a watermark that stores the original length of x as part of the mutable borrow in the inner scope. When the inner scope ends and the mutable borrow goes out of scope, we truncate x to its original length. Any mutations that would write to a stack location lower than the watermark simply fail since they would violate referential transparency.

One important detail is that the capacity() of the shadowed variable must also be restored to its original logical capacity, even if we ended up growing the underlying allocation as part of the inner scope. This doesn't mean that we need to undo a heap allocation and move it back into a smaller heap fragment, however. We merely need a way to reduce the logical capacity, thus guaranteeing that e.g. a push() fails when it would need more than the available logical capacity, even if the heap fragment is bigger. The next grow() could then reuse the underlying physical heap fragment if it's still big enough for the new logical capacity.

Would such a system be useful? Hard to say without using it in practice, but it could potentially be useful for append-only patterns where it would be inconvenient if we needed to copy the entire list x every time we wanted to briefly append and then remove something as part of an inner scope. This is the case for a lot of purely functional algorithms that use a stack but would like to avoid cons lists. With mutable shadow borrowing that's possible.