koka-lang / koka

Koka language compiler and interpreter
http://koka-lang.org
Other
3.16k stars 151 forks source link

Reference counting local variables #522

Closed TimWhiting closed 1 week ago

TimWhiting commented 1 month ago

I've noticed that local variables hold an extra reference when modifying (x := x.modify()). In hindsight this is obvious, but obviously it also means that local variables work against Perceus's reuse. (And it would be especially nice to use this in combination with vectors or other large aggregate values, which could reflect on the reference count to mutate in place).

It would be good to change the semantics of :=to somehow benefit from Perceus and unique reference counts.

Essentially the value should be extracted from the location leaving a ctx<loc<v>>, and the value should be available on the right hand side, filling in the hole for the location after getting the result of the rhs expression, however, the main issue I see is that if the right hand side throws an exception or otherwise escapes the context we are in trouble if we mutated the value contained in the variable. (Though in the particular case of exceptions since we are exiting the local context in which the variable is accessible there will no longer be a local variable, and we would need to drop - actually free it assuming a unique reference count and if it isn't returned).

This is one place where constraining a polymorphic effect row to only contain linear effects (or linear plus final ctl) could be useful.

Is my observation correct as far as needing to constrain the effects in the right hand side to linear + final ctl, or is there another approach that allows for x to have a unique reference count on the right hand side of an assignment?

Additionally this poses serious problems for handler operations that want to use a local variable efficiently as well, since capturing the location in each operation clause will cause multiple increments of the reference count.