LEVIATHAN vd52e79c4 · d52e79c486

Library

Collections are values

Array, Map and Set are values; the in-place verbs (add, set, remove, ...) change the variable you call them on, the prepositional forms (with, without, concat) return a new value.

since 0.1.0-alpha.1linuxwindowswasm

Description

Array<T>, Map<K, V> and Set<T> are values. Two names never share one collection: copying gives the copy its own value, and a change made through one name is never seen through another.

There are two families of methods, and the name tells them apart.

  • An imperative name mutates the place it is called on and returns nothing: add, addAll, insertAt, removeAt, clear on an Array; set, remove, clear on a Map; add, remove, clear on a Set. These are the in-place verbs. A verb call is a statement.
  • A prepositional or noun-shaped name is pure and returns a new collection, leaving the receiver as it was: with, without, concat, union, except, withAll.
Array<int> xs = [1, 2];
xs.add(3);                       // xs is now [1, 2, 3]
Map<string, int> ages = Map();
ages.set("ann", 30);
Set<int> seen = Set();
seen.add(7);
Array<int> more;
more = xs.concat([4]);           // pure: xs is unchanged, more is [1, 2, 3, 4]

This changes behaviour for existing programs. Before value-model M4 xs.add(3); as a statement compiled and did nothing, and the idiom for change was xs = xs.add(3);. A verb now returns nothing, so xs = xs.add(3), b = a.add(3), return a.add(3) and f(a.add(3)) are compile errors that name the statement to write (xs.add(3);, or Array<int> b = a; b.add(3); to keep the original). A program that relied on the silent no-op now changes the collection. The pure forms with, without and concat still return values; a statement that discards one is a warning that names the in-place twin (m.with(k, v); suggests m.set(k, v);).

The argument order is also part of the change: on a typed collection place, the arguments of a verb are evaluated first, and the place's current value is read afterwards. g.add(f()) where f itself appends to g sees f's append. Through an interface or erased receiver (IIterable<int> f, a generic T) the receiver is read first, by its declared type, and the verb's result then replaces what an argument stored there (see calls).

Consequences:

  • A collection you pass to a function is safe. The function receives its own value. A verb on its parameter is visible only inside the function. A function that wants to hand a changed collection back returns it.

  • Copying is free to the program. Array<int> b = a; gives b its own value. A later a.add(1) leaves b alone, and b.add(1) leaves a alone. The implementation shares storage and copies lazily (copy on write); that is an optimisation you cannot observe.

  • A loop over a collection iterates the value it had when the loop started. A verb on the iterable inside the body does not change the pass.

  • The receiver of a verb is a place: a local, a field (h.xs.add(1)), a global, an element (aa[0].add(1), m[k].add(x)), or this. A temporary has no place, so mk().add(1) or [1, 2].add(3) is a compile error ("cannot mutate a temporary ..."), and so is a verb on a field or element of a temporary value (mkStruct().a.add(1), mkRows()[0].add(1)). A field of a class object is a place however the object is reached: mkObj().a.add(1) and objs()[0].a.add(1) write the object.

  • A verb reads each getter hop of its receiver chain once per call, on every engine. A getter hop is a member or index that the hop's static type reads through a get accessor: a get (w.h.a.add(5) with H get h()), an accessor pair on a class-typed hop, a user get ([]) (w[0].a.add(5)), and the same under an element (w.h.xs[i].add(5)). The store goes into the object the getter returned, so the getter is not read again for it. When it runs:

    • on a typed collection place, after the arguments, with the rest of the place: w.h.a.add(f()) runs f, then get h. The chain's root and its indices still run first (mk().h.a.add(f()) runs mk, f, then get h; w[ix()].a.add(f()) with a user get ([]) runs ix, f, then the indexer).
    • through an interface or erased receiver (by name), with the receiver, before the arguments (see calls): w.g.f.add(f()) with IIterable<int> f runs get g, then f.

    A bare member name inside a method (h.a.add(5) for this.h) is the same hop as its this. form. A static getter is a getter hop too, bare inside its class (sh.a.add(f())) or qualified (W::sh.a.add(f())): f, then get sh. A value-struct property with a get and a set on the chain (w.s.a.add(f()) with S get s() / set s(S v)) also follows the typed order: the arguments, then the getter, the change and the setter (f, get s, set s).

    A hop the static type reads as a plain field is not a getter hop, whatever another class declares under that name: it is re-read after the arguments, so an argument that replaces it sends the store to the new object. Through an erased T the static type shows no getter, so a getter the running class declares runs for the read and again for the store. A compound store differs: p op= e is p = p op e, so a getter on the way runs for the read and again for the store (see reference and value semantics). A mutating call or a set accessor on an element (h.ps[0].bump()) re-resolves the place after the call, to check that the element's collection was not written while it ran (the element-place rule in reference and value semantics). A getter hop that yields an object on the way (a getter-only property, a static getter, a class-typed pair: gg.h.ps[0].bump()) is read ONCE for the call, as a call root is; the check and the store-back go through the object it returned (it used to run twice: for the read and for the store). On a hop the static type reads as a plain field that the running class overrides with a get accessor, that getter runs once more: for the read, for the check and for the store (three times where it used to run twice). Through a property with both a get and a set that yields the collection (gw.ps[0].bump() with Array<P> get ps() / set ps(..)), the getter runs for the read, for the check and for the store's get (three times), then the setter. The check compares VALUES when the two reads differ, so a getter that builds a fresh collection of equal values raises nothing. A getter that builds fresh class instances or fresh closures inside the collection (Array<IB> get r() => [CB(n)], or Array<K> get ks() => [K(() => n)] for a struct K holding a closure) raises, because two reads returned different instances (class instances and closures compare by identity): the collection's value changed, and that is correct under the rule. Per form, through such a pair or such an overridden field (i the index, g a getter run, s the setter), the counts on every engine are:

    form order getter runs
    a mutating call, gw.ps[ix()].bump() igggs 3
    a set accessor, gw.ps[ix()].prop = 5 igggs 3
    a compound set, gw.ps[ix()].prop += 1 iggggs 4

    The order is the element order in calls: the index first, the right-hand side or the arguments, then the getter. The last three runs are the one read of the collection (the element), the check and the store's get. A compound store also reads the element for its old value, after its right-hand side (one more g, M3 Q8).

  • A verb cannot go through a ?. hop in its receiver (w?.h?.a?.add(1)): it is a compile error ("cannot call collection verb 'add' through a '?.' hop in its receiver: narrow first"). Narrow the optional first (if (w != None) { w.h.a.add(1); }). The verb's own ?. on an optional collection (o?.add(2)) is allowed: the receiver is tested first, and when it is None the arguments are not evaluated and nothing changes (as for any a?.m()). The receiver's root and indices still run first and a getter on it runs last, before the null test and the arguments: w.h.xs[ix()]?.add(f()) runs ix, get h, then f (only if the element is not None).

  • Capture. A verb on a captured local inside a lambda (var f = () => { a.add(1); };) is a compile error (cannot call mutating method 'add' on captured 'a' in a lambda: ...): the lambda holds its own copy, so the local would not change. Return the new collection from the lambda instead, or (once ref parameters land) take it as a ref parameter. In a class method's lambda, a verb on a field writes the object's field, because a class this is a reference (xs.add(1)), and so does a verb through a captured class instance (box.xs.add(1)). In a struct method's lambda, this is captured by copy, so xs.add(1) on its field is the same compile error. See lang.primary-expressions.

  • Threads. A worker thread's verb changes the worker's copy; nothing reaches the spawner (see threads). No two threads share a global, in a --lib build too: each C thread that calls into the library has its own copy.

  • A maybe-typed receiver (Array<int>? o) must be narrowed before a verb; o?.add(1) is accepted. A verb called through an erased type parameter or an interface the collection implements is resolved by name: the call is guarded on the receiver, read before the call, and writes the place; its value is the new collection. A maybe-typed temporary keeps the rule that the change lands in the temporary.

The same rule for Array, Map and Set

use io::console;

void grow(Array<int> xs) {
    xs[0] = 100;
    xs.add(1);
    console.writeln(xs);
}
Array<int> a = [1, 2];
grow(a);
console.writeln(a);
Map<string, int> m = Map();
m.set("a", 1);
Map<string, int> copy;
copy = m;
copy["a"] = 50;
copy.set("b", 2);
console.writeln(m);
console.writeln(copy);
Set<int> s = Set([1, 2]);
Set<int> t = s;
t.add(3);
console.writeln(s.toString());
console.writeln(t.toString());
[100, 2, 1]
[1, 2]
{a: 1}
{a: 50, b: 2}
{1, 2}
{1, 2, 3}

Rules

  • An imperative method (add, addAll, insertAt, removeAt, set, remove, clear) changes the place it is called on and returns nothing. A prepositional method (with, without, concat, union, except, withAll) is pure: it returns a new collection.
  • A verb's value cannot be used. b = a.add(3), return a.add(3), f(a.add(3)) and a.add(1).add(2) are errors; write the statement, or copy first (Array<int> b = a; b.add(3);).
  • A verb needs a place for a receiver; a temporary is an error.
  • Arguments are evaluated before the place's current value is read.
  • xs[i] = v and m[k] = v store into the variable's own collection; no other holder sees it.
  • Passing a collection to a function, assigning it to another variable, or storing it in a field never lets a later change through one name show through another.
  • Equality and keys are by value too: two collections are == when they hold equal values — arrays element by element in order, maps and sets regardless of order — and a collection is a valid Map key or Set element by its contents.
  • The value rule covers the collection itself, not the objects inside it. A collection of class instances holds references to those objects: a new collection made from it points at the same instances, and a change made to an instance through one collection is seen through the other. Struct elements are values: reading a[i] into a variable gives a copy. Writing through the element itself — a[i].x = 5, a[i].x += 1, a[i].p.x = 5, or a mutating call a[i].move(1) — changes the element in the collection. It is the same as reading the element, changing it and storing it back with a[i] = ..., so another variable that shares the collection keeps the old element. A Map value works the same way (m[k].x = 5).
  • Map and Set keep insertion order. Replacing the value of an existing key in a Map keeps that key in its original position; removing a key and adding it again puts it at the end.

Examples

Objects inside a collection stay shared

use io::console;

class Counter {
    int n = 0;
    void bump() { n = n + 1; }
}
Counter c = Counter();
Array<Counter> original = [c];
Array<Counter> longer = original;
longer.add(Counter());
longer[0].bump();
console.writeln(original[0].n);
console.writeln(longer.length());
console.writeln(original.length());
1
2
1

Notes

Collections stored in a class field follow the same rule: the field is a place, and a method that changes the collection calls the verb on it, for example items.add(x);.

See also

  • Array — An ordered sequence of values of one type, Array<T>, with value semantics.
  • Map — An associative collection from keys of type K to values of type V, with value semantics.
  • Set — A collection of distinct values of type T, with value semantics.