LEVIATHAN vd52e79c4 · d52e79c486

Types

Reference vs value semantics

Which types are shared when assigned or passed (class instances) and which are copied (primitives, structs, arrays).

since 0.1.0-alpha.1linuxwindowswasm

Description

A type is either a reference type or a value type, and that decides what an assignment or a function call does with it.

  • Instances of a class are references. Assigning one to another variable, or passing it to a function, shares the same object. A change made through either name is visible through the other.
  • Primitives, struct values and arrays are values. Assigning or passing one makes an independent copy. A change to the copy does not affect the original.

Sharing versus copying

use io::console;

class Counter {
    int n = 0;
}
struct Point {
    int x = 0;
    int y = 0;
}

void bumpClass(Counter c) { c.n = c.n + 1; }
void bumpInt(int n) { n = n + 1; }
void movePoint(Point p) { p.x = 99; }

Counter c1 = Counter();
Counter c2 = c1;
c2.n = 5;
bumpClass(c1);
console.writeln(c1.n);

int a = 1;
bumpInt(a);
console.writeln(a);

Point p1 = Point(1, 2);
Point p2 = p1;
p2.x = 10;
movePoint(p1);
console.writeln(p1.x);
6
1
1

Rules

  • A class instance is shared by every variable, field, parameter and collection slot that refers to it.
  • A primitive (int, float, bool, char, string, decimal and the sized numeric types) is copied on assignment and when passed.
  • A struct is copied on assignment, on passing as an argument and when read out of a collection into a variable or an argument (P q = xs[0];). Mutating the copy leaves the original unchanged.
  • A place is a variable (a local, a parameter or a global), this, a field of a place, an element or map value of a place (xs[0], m["k"]), and a property with both a get and a set accessor reached through a place (an indexer with both get ([]) and set ([]) too). A member of a class instance is a place wherever the instance came from, because the instance is shared. Everything else is a temporary: the result of a call (f(), xs.at(0), m.at("k")), of a construction (P(1)), of an operator or of await, the value of an assignment ((a = b)), the result of a ?:, a match or a ??, a property or indexer with only a get accessor, and a field or element of a temporary (f().p, f()[0] of an array that f returns). Whether a property has a set goes by the type it is read through: through interface I { P get p(); } the property is a temporary, also when the object's class holds p in a plain field. The type a member is read through decides the shape of a store: a plain field or a property with a set is writable, and a store through it is get, change, set; the set is a member write and runs the setter of the object's own class if it has one; if the object's own class holds a plain field, the change made in place is the store and nothing else is written. This changes behaviour for existing programs: a store or a mutating call through a plain field of the static view, on an object whose class holds an accessor pair of that name, now runs that class's setter with the changed value, where it used to change only the getter's temporary. A getter-only property of a definite collection type is a temporary like a struct: an index store through it, plain or compound (h.r[0] = 5, h.r[0] += 5 with Array<int> get r()), is the same compile error, and only a maybe-typed temporary is unchecked (a T get r() that holds an array: the store lands in the temporary and the slot is unchanged). A compound store p op= e is p = p op e: the sub-expressions of the place (mk() and ix() in mk().a[ix()] += 1) are evaluated once, and the place itself is read for the old value and again as the base of the store, so a getter on the way runs for the read and again for the store (mk().a[ix()] += 1 with a pair a runs mk, ix, the getter, the getter, the setter: for an element, the root and the indices run first and the old value is read after the right-hand side, the element order in calls).
  • Mutating a temporary whose type is a struct is a compile error, because the change would be lost with the temporary: a mutating call on it, a store to one of its fields or elements (plain or compound) and a set or set ([]) accessor on it (xs.at(0).bump(), f().x = 3, (t ? a : b).x += 1, h.q.x = 3 with only get q) report cannot mutate a temporary 'P' (a call result): the change would be lost; store it in a variable first, naming the kind of temporary. A temporary whose type is an interface, an optional or a type parameter is not checked: mutating it is allowed, also when the type is an optional of a struct (mkp()?.bump() with P? mkp()). When it holds a struct, the change lands in the temporary, and the place it was read from, if any, is unchanged ((l = m).add(1) with interface-typed l and m changes neither); when it holds a class instance, the instance changes.
  • A struct stored in a field is a place: calling a mutating method on it through the field (h.p.bump(), this.p.bump(), a bare p.bump() inside the class, or a nested a.b.c.bump()) changes that field in place, exactly as assigning through it (h.p.x = 5) does. An element of an array, and a value of a map, is a place in the same way: xs[0].x = 5, xs[0].x += 1, xs[0].p.x = 5, xs[0].bump(), xs[0].p.bump() and m["k"].bump() change the element in the collection. Such a write reads the element, changes it and stores it back into the collection, so another array that shares the same contents (Array<P> ys = xs;) keeps the old element, and a mutating method that throws keeps the changes it made before the throw. An element whose declared type is an interface, a generic or an optional type is a place in the same way when it holds a struct (a[0].add(1) with Array<IB>, m["k"].prop = 4). Every index on the way to the element is evaluated once, first; then the arguments or the right-hand side; then the element is read (the element order in calls). A mutating method runs on a copy of the element, and what it does to the element through this is stored back into the collection when it returns. While the method runs, changing that collection's value is a run-time error; reads are fine. A write counts whatever path it takes: a store into the same element (xs[0] = P(9, 9)) or another one, a swap, a removal of the element or of its map key, add, removeAt, remove, a mutating call on another element of it, a replacement of the whole collection. The error is raised when the method returns: a RuntimeException that names the collection, the element and the remedy (copy the element out, call the method on the copy and store it back, or change the collection after the call). The write itself has happened, and the copy is dropped. A class instance held in a maybe-typed collection (below) is shared, so it keeps the changes the method made to it. A method that throws keeps its own exception: the copy is stored back when the collection was not written, and dropped when it was. The check compares the collection the place holds after the call with the one the element was read from. A call that leaves the place holding that very collection again (Array<P> s = xs; xs.add(p); xs = s;, or xs = xs) is therefore not detected, and nothing is lost: the copy is stored back into it. An equal-value write is no change of value either (xs[1] = xs[1], or storing a P equal to the one there, field by field, by their bits): no error, and the copy is stored back. A write to another collection is no error. Neither is a write to an outer collection that leaves the element's own collection in place (gq[1] = .. or gq[0].n = .. during gq[0].rs[0].bump()), and nothing is lost by it: the copy is stored back into gq[0].rs as it is after the call. This changes behaviour for existing programs: such a write used to be overwritten by the element's copy, or to lose it. A set accessor run on an element (xs[0].prop = 5, an element's set ([])) follows the same rule. Its window opens after the element's index has run, and the collection is read once there, so an index that writes the collection (xs[f()].prop = 5) is no error, as for a call. A hop on the way to the collection that reads through a get and yields an object, whose field the next hop reads, is a getter-only property, a static getter or a class-typed property with a get and a set (gg.h.ps[0].bump() with H get h(), S.viaS.ps[0].bump()). It roots the rest of the path in that object, as a call does (mk().ps[0].bump()). Its getter runs once for the call, and the element read, the check and the store-back all go through the object it returned. The check reads the collection again after the call. Through a field that the static type reads as a plain field but the running class overrides with a get accessor, that getter runs once more. Through a property with both a get and a set that yields the collection itself, or a struct holding it (h.ps[0].bump() with Array<P> get ps() / set ps(..)), the store is get, change, set: the getter runs for the read, again for the check and again for the store's get. A change to the value during the call (a replacement through the setter, an element store through the property, a store into the field behind it) raises before the set; otherwise the set writes the copy back. A getter that builds a fresh collection on every read raises nothing when nothing was written, because the two reads have the same value. An element of a maybe-typed collection (Array<IB>) is a place whatever it holds, so the rule holds also when it holds a class instance; an element of Array<C> for a class C is shared, never copied, and is no such place. A struct reached through a method call is a temporary, so xs.at(0).bump() is a compile error.
  • The variable of a for loop over an array of structs holds a copy of each element; writing to it, or calling a mutating method on it, leaves the array unchanged.
  • A field typed as an interface, or as a generic or optional type, is a place in the same way when it holds a struct: a mutating call through it changes the stored value, also when that field is inside another struct (h.w.b.add(1) with struct W { IB b; }, or a bare b.add(1) in a method of W), and through any number of such fields, reached by . or ?. (gs[i].w?.p?.m(a) and loc.w?.p?.m(a) with struct S { W? w; } and struct W { P? p; }): the call changes the struct in its place. A ?. field that holds None runs no argument and stores nothing; when an argument stores None into such a field, the call does not run and nothing is stored. Below a property with a get and a set (d.pd.w?.p?.m(a), o.po?.q?.m(a)) the call is get, change, set: the getter once, the arguments, the call, the setter once; None at any hop runs the getter only. A store made to the field during the call wins: the call finishes on the value it started with, and the field keeps what was stored.
  • An index store into an element of an array or map whose element type is an interface, a generic or an optional type (a[0][0] = 4 with Array<IB>) runs the element's set ([]) and stores the element back, as for a struct element. An index store through a property with both a get and a set accessor (h.b[0] = 4) reads the property, stores into what it read and passes the result to the setter: get, change, set. Through a property with only a set accessor the store changes the field the property reads, which is then passed to the setter too. Through a property with only a get accessor it changes the getter's value, a temporary, and nothing else, on every engine. Through a plain field of interface type it changes the stored struct in place, and a store the setter makes to that field wins (nothing is written back over it). The element's store-back also happens when the path reaches the collection through a class instance that a call or a ?: yields (mk().a[0][0] = 4): the instance is shared. A mutating call or a set accessor store through an element of a maybe-typed collection, or through a property with both a get and a set (a[0].add(1), m["k"].prop = 4, h.b.prop = 4, h.b.add(4), h.r.bump()), changes the collection or the property: get, change, set. A struct element reached through such a class instance is a place too (mk().ps[0].x = 3): a field store or a mutating call on it changes the element in the shared object.
  • Storing a struct variable into an array literal ([loc]) or with add copies it; the collection owns its own copy.
  • An array is a value: Array<int> ys = xs; makes ys an independent array, so ys[0] = 99; does not change xs. Methods such as add return a new array and leave the receiver unchanged.
  • A copy of a collection is shallow. An array of class instances copies the references, so both arrays still point at the same objects.
  • A closure captures an object by reference, so mutations through it are shared. It captures a primitive local by value, and a struct or collection local the same way: the closure keeps its own copy, taken when the closure is created, so later changes to the variable are not seen by the closure. A write to that copy inside the closure is a compile error: assigning the captured variable, storing into a field or element of it, or calling a mutating method or a collection verb on it (cannot assign to captured 'n' in a lambda, see lang.primary-expressions). Return the new value instead, or (once ref parameters land) take the variable as a ref parameter. Which writes count goes by declared type: a store through a struct's set ([]) is one; a mutating call or a collection verb on a captured value typed as an interface or an optional is an error too, whatever it holds, while one on a class-typed capture is allowed (the object is shared). A struct this inside a lambda in a struct method is captured by copy in the same way.

Examples

Arrays copy; the objects inside them do not:

Arrays are values, their elements may not be

use io::console;

class Counter {
    int n = 0;
}

Array<int> xs = [1, 2, 3];
Array<int> ys = xs;
ys[0] = 99;
ys.add(4);
console.writeln(xs[0]);
console.writeln(xs.length());
console.writeln(ys.length());
Array<Counter> list = [Counter()];
Array<Counter> list2 = list;
list2[0].n = 4;
console.writeln(list[0].n);
1
3
4
4

A mutating call through an interface-typed field changes the stored value, also inside a struct:

A mutating call through an interface-typed field

use io::console;

interface IB {
    mutating int add(int n);
    int get();
}

struct B : IB {
    int v;
    new B(int a) { v = a; }
    mutating int add(int n) { v = v + n; return v; }
    int get() => v;
}

struct W {
    IB b = B(1);
}

class H {
    W w = W();
}

H h = H();
h.w.b.add(1);
console.writeln(h.w.b.get());
2

A closure captures an object live but a primitive by value:

A struct in a field or an array element is a place; a struct bound to a variable is a copy:

Mutating a struct through a field, a variable and an element

use io::console;

struct P {
    int x;
    int y;
    mutating void bump() { x = x + 1; }
}
class H {
    P p = P(1, 2);
}
void run() {
    H h = H();
    h.p.bump();
    console.writeln(h.p.x);
    P q = h.p;
    q.bump();
    console.writeln(q.x);
    console.writeln(h.p.x);
    Array<P> xs = [P(5, 6)];
    Array<P> ys = xs;
    xs[0].bump();
    xs[0].y += 10;
    console.writeln(xs[0].x);
    console.writeln(xs[0].y);
    console.writeln(ys[0].x);
}
run();
2
3
2
6
16
5

What a closure captures

use io::console;

class Box {
    int v = 0;
}

void run() {
    int seen = 0;
    Box box = Box();
    () => int inc = () => {
        box.v = box.v + 1;
        return seen + 1;
    };
    seen = inc();
    seen = inc();
    console.writeln(seen);
    console.writeln(box.v);
}
run();
1
2

Notes

To share mutable state between a closure and its caller, put the state in a small class and capture the instance, not a local int: writing a captured int inside the closure is a compile error. Or return the new value from the closure and assign it outside.

See also