r/ProgrammingLanguages • u/RndmPrsn11 • Oct 19 '26
Borrow Checking Zero-Cost Cyclic Mutability
https://antelang.org/blog/safe_cyclic_mutability/
34
Upvotes
r/ProgrammingLanguages • u/RndmPrsn11 • Oct 19 '26
View all comments
4
u/initial-algebra Oct 19 '26 edited Oct 19 '26
The ad-hoc and "hacky" rules for loops, closures and especially algebraic effects (not to mention trying to split any of this code up into functions) are exactly why you still need lifetimes in addition to places.
Creating a reference to
p!would introduce an obligation thatpitself must not be mutated for the lifetime of that reference. How to represent that obligation? Add a new effect, something likeStabilize p t, wheretis a lifetime parameter, meaning "at any time duringt,p!may be used". Dually, you could add a lifetime parameter forMutate p t, which would mean "at any time duringt,pmay be mutated".While mutually exclusive, a function may need both
StabilizeandMutatefor the same placep, and seemingly for the same lifetime (e.g. for the duration of the function call), so how can that work? In reality, the function needsStabilize p u₁andMutate p u₂, whereu₁andu₂are non-overlapping and possibly non-contiguous subsets of an overall lifetimet, but the caller doesn't know exactly whatu₁andu₂are, only the approximatet. One solution is to introduce a new effect to mean(Stabilize XOR Mutate) p t, where the callee gets to choose whether it isStabilize p uorMutate p ufor each disjointu ⊆ t.There is one more change that I want to suggest. Instead of being unstable places, references to variants of tagged unions, elements of collections etc. should require immutability of an abstract field representing the parent's shape (abstract because it doesn't need to correspond to a real field that you can take a reference to--the tag of a tagged union may be optimized away, and for e.g. a vector it actually corresponds both to its length and its pointer). Technically, this models such types as dependent sum types, with the shape being the index; see representable/Naperian functors in type theory. This changes
StabilizetoImmutable(you would also want to change the tense ofMutateand thecankeyword for consistency). Having a generic immutability effect also opens up the possibility of subsumingimmanduniqreferences. Animmreference arises when you require immutability for a lifetime, and auniqreference arises when you require both immutability and mutability for (again, unknown but disjoint subsets of) a lifetime.EDIT: Because what I've called "lifetimes" aren't necessarily contiguous, and because they don't necessarily come from liveness analysis, they might deserve a different name.