flix icon indicating copy to clipboard operation
flix copied to clipboard

When can memory be allocated in a region? Does every mutable data structure need a clone?

Open magnus-madsen opened this issue 2 months ago • 3 comments

I encountered the following problem:

I want to implement:

    pub def shuffle(a: Array[a, r]): Array[a, r] \ {r, Shuffle} = {
        let len = Array.length(a);
        let perm = Shuffle.permutation(len);
        // Apply the permutation: result[i] = a[perm[i]]
        let tmp = Array.init(???, i -> Array.get(Vector.get(i, perm), a), len);
        // write back into a.
    }

I need to create a temporary array (although I later realized maybe I can use a vector).

The problem/question is:

  • How can I do that without access to an rc?

And when am I allowed to cheat (e.g. by calling Java):

  • Is user-defined code allowed to cheat (e.g. create memory without an rc but belonging to a region)?
  • Is library-defined code allowed to cheat (e.g. create memory without an rc but belonging to a region)?

Alternatively, do we need every data structure to have a clone which is like copy but duplicates into the same region?

Does Array need to hold onto an RC? How would that even work? :/

magnus-madsen avatar Oct 01 '25 06:10 magnus-madsen

The tmp array is well-scoped so a local region seems fine?

pub def shuffle(a: Array[a, r]): Array[a, r] \ {r, Shuffle} =
    region rc {
        let len = Array.length(a);
        let perm = Shuffle.permutation(len);
        // Apply the permutation: result[i] = a[perm[i]]
        let tmp = Array.init(rc, i -> Array.get(Vector.get(i, perm), a), len);
        // write back into a.
       ???
    }

JonathanStarup avatar Oct 01 '25 13:10 JonathanStarup

And when am I allowed to cheat

Right now you can cheat whenever you want and nothing goes wrong. I don't think that can be answered before region values do something.

JonathanStarup avatar Oct 01 '25 13:10 JonathanStarup

Does Array need to hold onto an RC? How would that even work? :/

Funny, I just read about WeakHashMap. We can store region values in a global map by reference equality. And the entries in this map automatically follow GC of the relevant keys. Array.rc(arr) is Global.regions.get(arr)

JonathanStarup avatar Oct 01 '25 13:10 JonathanStarup