Moves

Moves

A move hands a value from one place to another without duplicating it. The source gives the value up and holds nothing afterwards. This is the part of Kairo's memory model that works like affine types: a value of a move-only type is used, in the sense of being moved out of, at most once. The compiler checks this in every build, debug and release. The check needs no annotations and has no runtime cost.

This page covers what a move is, which values move, what the compiler catches, what it does not catch, and what happens to a moved-from object. Ownership covers the rest of the model: categories, aliasing, closure captures and destruction order.

The examples use this class. It owns a file descriptor, so it can be moved but not copied:

class File {
    pub var fd: i32
    pub fn File(self, fd: i32) { self.fd = fd }
    @move
    pub fn File(self, other: Self) { self.fd = other.fd; other.fd = -1 }
}

Copy or move: the type decides

Kairo has no move keyword and no move marker at the call site. Whether a transfer copies or moves is decided by the type of the value, through its lifecycle category:

TypeA transfer by value
a class with a @copy constructor (COPY)copies; the source stays usable
a class with a @move constructor (MOVE)moves; the source is moved-from
a class with deleted transfer constructors (NON_TRANSFER)is an error
a class with no transfer constructortakes the weakest category of its bases and fields: COPY if all are COPY, MOVE if any is move-only, NON_TRANSFER if any cannot be transferred
a struct, a primitive, a pointercopies
an enum with payloads, a tuplethe weakest category of its parts
a fixed-size arrayis not transferred whole (SC083E: initialize it from a list literal, or view it through a slice or a pointer; see Collections)
an imported C++ classfollows its C++ copy and move constructors

A transfer by value is any of these: initializing a variable, assigning, passing to a by-value parameter, returning, capturing in a closure by value, and the value of an if expression arm. A const parameter, a C++ T& or const T& parameter, and a pointer borrow the value instead: nothing moves.

Move-only types are affine

A move-only value can be moved out of once. After that the place that held it is moved-from, and any use of it is a compile error until it is assigned a whole new value. A value may also be dropped without ever being moved; the destructor runs at the end of its scope as usual. That is the difference between affine and linear types: Kairo requires at most one use, not exactly one.

fn main() -> i32 {
    var a = File(3)
    var b = a              // moves: a is moved-from
    a = File(4)            // a holds a new value
    return a.fd + b.fd     // ok
}

Copying a move-only value, moving a copyable one

A type that can make copies of itself declares fn copy(const self) -> Self. x.copy() calls it. On a COPY type that declares no copy, x.copy() runs the copy constructor once, and std::copy(x) (import std) returns a copy of either kind. An array is not copyable.

To move explicitly, call std::move(x). It takes x through a @move parameter, so x is moved-from afterwards for every type, a COPY type included, until it is assigned again.

import std

class Token {
    pub var id: i32
    pub fn Token(self, id: i32) { self.id = id }
    @move
    pub fn Token(self, other: Self) { self.id = other.id; other.id = 0 }
    pub fn copy(const self) -> Self { return Token(self.id) }
}

fn main() -> i32 {
    var t = Token(5)
    var u = t.copy()       // a copy: t stays usable
    var v = t              // a move: t is moved-from
    var w = std::move(v)   // an explicit move: v is moved-from
    return u.id + w.id
}

A parameter written @move x: T takes its argument by move, whatever T is; see Parameter passing modes.

Last-use moves

A MOVE value always moves when it is transferred, so there is nothing to optimize there. Three transfers move only when the source is not read again, on any path, including the next iteration of a loop:

  • in a generic body, var y = x where the type of x depends on a type parameter: at an instance whose type cannot be copied it moves, at any other it copies;
  • an expansion xs... of a forwarding pack;
  • a + b where op + is derived from op +=: the left operand moves into the result at its last use, and is copied otherwise.

When the source is read again and its type cannot be copied, the transfer is an error at the instance or at the operator:

fn <T> twice(x: T) -> i32 {
    var y = x
    var z = x              // error SC052E in twice<File>
    return 0
}

fn main() -> i32 {
    var a = twice(1)       // ok: i32 is copied
    return twice(File(1))
}
error [SC052E]: 'x' is used after being moved in 'twice<File>': 'File' cannot be copied, so the transfer moves it

What the compiler catches

The check is static and runs on each function body. It follows every path through the body: branches, loops, match arms, try and catch, early return, break and continue. At a join, a value moved on either path counts as moved.

Use after move (SC052E)

Reading a moved-from place, calling a method on it, passing it, or moving it again is SC052E. The notes say where the move happened. When the type declares a public copy, a further note offers a fix-it that appends .copy() at the move, in case a copy was meant.

fn main() -> i32 {
    var a = File(3)
    var b = a
    return a.fd            // error SC052E
}
error [SC052E]: 'a' is used after being moved
note: 'a' was moved here, into 'b'
note: assign a new value to 'a' before using it again

Conditional moves

A value moved on some paths only is moved-from after the paths join:

fn send(f: File) { }

fn run(flag: bool) -> i32 {
    var f = File(3)
    if flag {
        send(f)
    }
    return f.fd            // error SC052E: f may have been moved
}
error [SC052E]: 'f' is used after being moved
note: 'f' was moved here, into a by-value parameter

Moves in loops

A move inside a loop body moves the value again on the next iteration, which is a use after move at the same line. Assign a new value before the iteration ends:

fn send(f: File) { }

fn run() {
    var f = File(3)
    for i in 0..3 {
        send(f)            // error SC052E: moved on the previous iteration
    }
}

fn refill() {
    var f = File(3)
    for i in 0..3 {
        send(f)
        f = File(i)        // ok: f is whole again before the next iteration
    }
}

Closure captures

A closure with no capture list captures what it names by value, so a move-only variable moves into the closure when the closure expression is evaluated. The variable is moved-from from that point, whether or not the closure runs:

fn run() -> i32 {
    var f = File(3)
    var g = fn () -> i32 { return f.fd }
    return f.fd + g()      // error SC052E
}
error [SC052E]: 'f' is used after being moved
note: 'f' was moved here, into the closure that captures it

Capture by pointer (|*f|) moves nothing. A closure whose body leaves a |*x| capture moved-from may run at any time, so the captured variable is moved-from once the closure expression is evaluated.

Moving a part

A move does not have to take a whole variable. Moving a field leaves that field moved-from and the rest of the value usable. Using the moved field, or the value as a whole, is an error until the field is assigned again. The same rule covers a field of self.

class Pair {
    pub var a: File
    pub var b: File
    pub fn Pair(self) { self.a = File(1); self.b = File(2) }
}

fn send(p: Pair) { }

fn run() -> i32 {
    var p = Pair()
    var x = p.a            // p.a is moved-from
    var n = p.b.fd         // ok: p.b is untouched
    send(p)                // error SC052E: p is used while p.a is gone
    p = Pair()             // ok: p is whole again
    return n
}
error [SC052E]: 'p' is used after its part 'p.a' was moved
note: 'p.a' was moved here, into 'x'

Moving an element out of an array or a container leaves the whole container moved-from, because the compiler does not track which index was taken:

fn run() -> i32 {
    var files: [File; 2] = [File(1), File(2)]
    var first = files[0]
    return files[1].fd     // error SC052E
}
error [SC052E]: 'files' is used after 'files[0]' was moved out of it

To take one element and keep the rest, use a method of the container that leaves it valid.

Moves a called function makes

A function that returns while a part of self, of an @inout parameter or of what a parameter points at is still moved-from leaves that part moved-from in the caller's object. Nothing is written in the signature: the compiler reads it from the function's body, wherever the function is defined.

class Holder {
    pub var a: File
    pub var b: File
    pub fn Holder(self) { self.a = File(1); self.b = File(2) }
    pub fn take_a(self) -> File { return self.a }   // leaves self.a moved-from
}

fn run() -> i32 {
    var h = Holder()
    var x = h.take_a()
    return h.b.fd + h.a.fd   // error SC052E: h.a, by the call to take_a
}
error [SC052E]: 'h.a' is used after being moved
note: 'h.a' was moved here, by the call to 'take_a'
note: it is moved here, and not assigned again before the body returns

A function that moves its argument only on one outcome leaves it moved-from only on that outcome. Three outcomes are told apart: returning true or false, returning null or a value, and panicking or returning. The caller sees the outcome when the call is the condition of an if or a loop, alone or under !, &&, ||, ?, == null or != null; when a local initialised from the call is tested that way; when the function returns the call's result; and in the catch arms of a try, for a panic. Anywhere else the argument counts as moved.

class Queue {
    pub var slot: File
    pub var full: bool = false
    pub fn Queue(self) { self.slot = File(0) }
    pub fn push(self, @inout v: File) -> bool {
        if self.full { return false }   // v untouched
        self.slot = v                   // v moved
        return true
    }
}

fn run() -> i32 {
    var q = Queue()
    var t = File(3)
    var ok = q.push(&t)
    if !ok {
        return t.fd                     // ok: push returned false, t is whole
    }
    return t.fd                         // error SC052E: push returned true
}
error [SC052E]: 't' is used after being moved
note: 't' was moved here, by the call to 'push', when it returns true

A function with no body the compiler can read (one declared in Kairo and implemented in C or C++) is taken at its worst: after the call, every move-only value it could have moved out of is moved-from. That is a non-const receiver, an @inout argument, and what a pointer to non-const points at. Declare the parameter const, or take a pointer to const, when the function only reads; declare it @move when it takes the value.

class Holder {
    pub var f: File
    pub fn Holder(self) { self.f = File(1) }
}

fn native_fill(@inout h: Holder)   // implemented in C++

fn run() -> i32 {
    var h = Holder()
    native_fill(&h)
    return h.f.fd                   // error SC052E
}
error [SC052E]: 'h' is used after being moved
note: 'h' was moved here, by the call to 'native_fill', whose body cannot be read and is taken to move it

A C or C++ function whose body is in an imported header is read too: if the body binds an argument passed as T& or T* to a T&&, directly or through a function it passes the argument on to, the argument is moved-from after the call. See Calling C and C++.

Moving out through a pointer or reference (SC182E)

A move-only value reached through a pointer or a reference cannot be moved out: that would leave the object moved-from for every other reader of it, where the compiler cannot follow. Copy it, borrow it, or hand it off explicitly with cxx::std::move (ffi "c++" import "utility"). A local, a by-value parameter, self and their fields still move.

class Pair {
    pub var a: File
    pub var b: File
    pub fn Pair(self) { self.a = File(1); self.b = File(2) }
}

fn take(p: *Pair) -> i32 {
    var a = p->a           // error SC182E
    return a.fd
}
error [SC182E]: cannot move a value of type 'File' out of 'p->a': it is reached through a pointer or a reference
note: the transfer into 'a' would leave the object moved-from for every other reader of it; copy it, borrow it, or hand it off with 'cxx::std::move(...)'
note: borrow it instead: 'var *a = &p->a'
ffi "c++" import "utility"

class Pair {
    pub var a: File
    pub var b: File
    pub fn Pair(self) { self.a = File(1); self.b = File(2) }
}

fn take(p: *Pair) -> i32 {
    var *c = &p->a                  // ok: a borrow
    var d = cxx::std::move(p->a)    // ok: explicit hand-off; p->a is moved-from
    return c->fd + d.fd
}

After cxx::std::move(*p), reading *p through the same pointer is SC052E.

const values

A const value is never moved from. Passing one to a @move parameter is SC301E. Transferring one by value when its type cannot be copied is SC182E: it can be neither moved nor copied.

fn keep(@move f: File) { }
fn send(f: File) { }

fn run() {
    const f = File(3)
    keep(f)                // error SC301E
    send(f)                // error SC182E
}
error [SC301E]: 'f' is const, so it cannot be passed to a '@move' parameter, which leaves its argument moved-from
error [SC182E]: cannot copy a value of type 'File': it declares a move constructor and no copy constructor

if expression arms

The arms of an if expression are values. An arm of a move-only type that names a local or a by-value parameter moves it into the result. An arm that names a field, an element, a const parameter or a pointer's target cannot be moved from, and the type has no copy, so it is SC182E. Write x.copy() where the type can be copied, or borrow the value.

class Box {
    pub var f: File
    pub fn Box(self) { self.f = File(1) }
}

fn pick(c: bool, b: *Box) -> File {
    var local = File(2)
    return if c => local else => b->f   // error SC182E at 'b->f'
}

fn either(c: bool) -> File {
    var x = File(1)
    var y = File(2)
    return if c => x else => y          // ok: moves x or y
}
error [SC182E]: cannot copy a value of type 'File': it declares a move constructor and no copy constructor
note: an 'if' expression copies this arm into its value, and moving out of it would leave the place moved-from

match and loop binders

A loop or case binder takes its value by its type:

BinderResult
x: T, with a written typeconverts the element into a new value of T, as var y: T = elem does; never a borrow
const xborrows the element
x (case var x), element not copyableborrows the element read-only
x (case var x), element COPYa copy

A borrowing binder cannot be moved out of. Passing it by value is SC182E:

fn take(f: File) -> i32 { return f.fd }

fn total(v: [File]) -> i32 {
    var n = 0
    for f in v {
        n += take(f)       // error SC182E: f borrows its element
    }
    return n
}
error [SC182E]: cannot copy a value of type 'File': it declares a move constructor and no copy constructor
note: 'f' borrows its element, so the transfer into a by-value parameter cannot move it away, and moving is the only transfer its type has

A case binder in a constructor pattern has one more option. When an arm moves it out (as the arm's value, in a return, as a by-value argument, or as an initializer) and the match owns what it tests, the binder takes the payload by move. The match owns a temporary, a non-const local and a by-value parameter. The tested value is moved-from from that point. Over any other value (a const parameter, what a pointer points at) the same move is SC182E.

enum Slot { Full { f: File }, Empty }

fn take(f: File) -> i32 { return f.fd }
fn take_slot(s: Slot) -> i32 { return 1 }

fn run(s: Slot) -> i32 {
    var n = match s {
        case .Full(var f) => take(f)   // s's payload moves into f
        default           => 0
    }
    return n + take_slot(s)            // error SC052E
}
error [SC052E]: 's' is used after being moved
note: 's' was moved here, by the match, whose binder 'f' takes its payload

Over a generator, a move-only element is moved into the binder: the generator gives each value up when it is resumed. See Loops.

Values that cannot be moved (SC051E)

A NON_TRANSFER value passed where it would be moved, for example to a @move parameter, is SC051E. The message says why the type cannot be moved.

class Lock {
    pub fn Lock(self) { }
    @copy fn Lock(self, const other: Self) = delete
    @move fn Lock(self, other: Self) = delete
}

fn keep(@move l: Lock) { }

fn run() {
    var l = Lock()
    keep(l)                // error SC051E
}
error SC051E: cannot move a value of type 'Lock': its move constructor is deleted

Borrowed and moved by the same call

A call that borrows a value in one argument and moves it in a later argument would hand the callee a moved-from value:

fn both(const a: File, b: File) { }

fn run() {
    var f = File(3)
    both(f, f)             // error
}
error [SC001E]: 'f' is borrowed by this argument and moved by a later argument of the same call, so the call reads a moved-from value

A @move constructor that never writes its source (SC001W)

A @move constructor with a body that only reads other, in a class with a destructor that holds a pointer, leaves source and target holding the same address. Some moved-from objects are still destroyed (see Which moves are destructive), so the destructor would run on both. That is the warning SC001W:

class Owns {
    var p: unsafe *i32

    fn Owns(self) { self.p = &null }
    @move fn Owns(self, other: Self) { self.p = other.p }   // warning SC001W
    fn op finally(self) { }
}
warning [SC001W]: the '@move' constructor of 'Owns' never writes 'other', so both objects keep the resource and the destructor runs on each
note: the destructor is here; reset the source's fields in the constructor

Reset every pointer the source holds in the constructor (other.p = &null).

In generic code

In a generic body, a by-value transfer of a T out of storage the body does not own (*p, p->f, self.f) moves at an instance whose type cannot be copied and copies at every other. Reading that storage again before assigning it is SC052E at that instance, and copying out of a const place is SC182E there.


What the compiler does not catch

The check follows names, not memory. These leave a moved-from value behind with no diagnostic:

  • A second name for the same object. A pointer taken before the move still reaches the moved-from object, and the compiler does not connect the two. The same holds for a raw unsafe *T, and for two pointer parameters that point at one object.

    fn run() -> i32 {
        var a = File(1)
        var p: *File = &a
        var b = a
        return p->fd           // not caught: reads the moved-from a
    }
  • A call the compiler does not look into. A call through a function pointer, a stored closure or an interface, and an override reached through a virtual call, are not read. A virtual call reads the body of the method it names, not of the override that runs.

    class Holder {
        pub var a: File
        pub fn Holder(self) { self.a = File(1) }
    }
    
    fn steal(@inout h: Holder) -> i32 { var x = h.a; return x.fd }
    
    fn run() -> i32 {
        var h = Holder()
        var f = steal
        f(&h)                  // not caught: steal moves h.a
        return h.a.fd
    }
  • A capture moved inside its closure. The closure's own copy is moved-from after the first call, and a second call reads it:

    fn send(f: File) -> i32 { return f.fd }
    
    fn run() -> i32 {
        var f = File(3)
        var g = fn () -> i32 { return send(f) }
        return g() + g()       // not caught: the second call moves a moved-from capture
    }
  • Other places. A user-defined operator that leaves an operand moved-from; a constructor that leaves part of its own self moved-from; a field whose type is a generic parameter, moved out of self in a generic body; indexing a raw pointer (p[i]); a place reached through a call's result; and, of two files that import each other, the file checked first.

  • C and C++ code. Nothing inside C or C++ code is checked. At a call into it, a body the compiler cannot read (defined in a .cpp file, a virtual call, a call through a pointer) is taken to move every argument it could, unless -fno-strict-cxx-moves is given; then it is taken to borrow, an assumption --print-unchecked-assumptions lists. A call into the C++ standard library that ships with the toolchain is taken not to move under either setting.

  • Nothing at run time. There is no runtime check for a moved-from access. Where the static check does not reach, a read of a moved-from object reads whatever its @move constructor left there.

An imported C++ type is checked like a Kairo type: using a moved-from C++ local is SC052E. What differs is what happens to the moved-from object, below.


Destructive moves

A move of a Kairo MOVE class that has a destructor is destructive in the cases listed below: the moved-from object is not destroyed again, and the destructor runs once, on the object that owns the value last. In C++, by contrast, a move leaves the source in a valid but unspecified state, and the source's destructor still runs at the end of its scope.

import std::io::println

class Res {
    var id: i32 = 0
    fn Res(self, id: i32) { self.id = id }
    @move fn Res(self, other: Self) {
        self.id = other.id
        other.id = 0
    }
    fn op finally(self) { println(f"~Res {self.id}") }
}

fn maybe(give: bool) {
    var a = Res(1)
    if give {
        var b = a
        println("moved into b")
    }
    println("end of scope")
}

fn main() -> i32 {
    maybe(true)
    maybe(false)
    return 0
}
moved into b
~Res 1
end of scope
end of scope
~Res 1

On each path the destructor runs once. When a is moved, b destroys the value at the end of the if block, and nothing is destroyed for a. When it is not, a is destroyed at the end of its scope. There is no ~Res 0 line: the emptied source is never destroyed.

How the compiler does it

  • A value moved on every path out of its scope is not destroyed at the end of that scope.
  • A value moved on some paths only carries a drop flag, a hidden bool set when the value is built and cleared by the move. The end of the scope destroys the value only when the flag is still set.
  • Assigning a whole new value to a moved-from variable builds the value in place. Nothing old is destroyed or assigned, since nothing is there. So a loop that moves a variable and assigns it again runs one destructor per value built.
  • Assigning a moved-from local to a live variable destroys the variable's old value and moves the new one in. Nothing is left behind in the source.
  • Moving a field out of a local leaves the rest of the local to be destroyed as usual, without that field.
  • Moving a value into a closure by value hands it to the closure, which destroys it when the closure is destroyed.
  • A by-value parameter is the caller's object, not a copy of it. When the function's body is compiled with the call, the argument's storage is handed over: the function destroys the value, or moves it on, and the caller destroys nothing. A function that only reads the parameter leaves the value to the caller, and so does a call through a vtable, a fn value or an interface, where the body is not known. A @relocatable class is still passed by value in registers.

The rule does not change the order of destruction: the values that are still owned at the end of a scope are destroyed in reverse declaration order, as always. See Destruction Order.

Which moves are destructive

A move is destructive when both of these hold:

  • The type is a Kairo class of category MOVE, that is not polymorphic (no virtual method or virtual base), whose bases and by-value fields are each trivially destroyed or destructive themselves. A class that holds a C++ type with a destructor is not destructive, and neither is a class whose defaulted @move copies a COPY field.
  • The move transfers a whole local by value in a plain function body: an initialization, an assignment, a by-value argument, a return, or a by-value closure capture. Or it moves a field out of a local on every path, when the local's class has no destructor of its own and is declared in the same file and namespace as the function.

Every other move leaves a moved-from object that is still destroyed at the end of its owner's scope, as in C++:

  • an imported C++ type, and the cases of the type rule above;
  • an argument to a @move parameter, std::move(x) included: the parameter refers to the caller's object, which the caller still destroys;
  • cxx::std::move(...) of a value reached through a pointer;
  • a value moved out of a closure's capture, a global, a static, a field of self or a pointer's target;
  • a local of an async function or of a closure, a local of a constructor body or of an eval function, and a local whose type is a generic parameter;
  • a local returned on one path when another local is returned on another;
  • a temporary assigned over a live value (a = Res(2) while a holds a value): the emptied temporary is destroyed;
  • a field moved on some paths only, out of a value whose class has a destructor of its own, or inside a method, a closure or a generic function;
  • enums, tuples, nullables and arrays holding a destructive type.

Calling finally() on a local after it was moved is an error (SC052E), like any other use of a moved-from variable.

What this means for a type with a destructor

A destructor never sees an object whose value was moved out by a destructive move. It can still see one through the moves listed above. So a @move constructor must leave its source safe to destroy: reset every pointer and handle it hands over, as Res above sets other.id = 0. SC001W catches the common mistake.

A destructor that counts or logs (~Res above) shows the difference: after a destructive move it runs once for the value, not once for each object that held it.

Differences from C++

Kairo classC++ class
Use of the moved-from variablecompile error (SC052E) until it is assignedallowed; the object is valid but unspecified
Destructor of the moved-from objectdoes not run, after a destructive moveruns at the end of its scope
Value moved on one path onlya drop flag decides at the end of the scopethe destructor runs on both paths
Assigning to a moved-from variablebuilds a new value in placecalls operator= on the moved-from object

A C++ caller of a Kairo function, through an emitted header, sees ordinary C++ moves: the object it passes is destroyed by C++'s rules.


Summary

CategoryA transfer by valueSource afterDestroyed
COPYcopiesusableboth copies, each at the end of its scope
MOVEmovesmoved-from, an error to use until assignedonce, by the last owner, after a destructive move; see Which moves are destructive
NON_TRANSFERis an error (SC182E for a copy, SC051E for a move)at the end of its scope
structcopies, byte for byteusablenothing to destroy
C++ move-only typemovesmoved-from, an error to use until assignedboth objects, by C++'s rules

See also