================================== Nim Destructors and Move Semantics ================================== :Authors: Andreas Rumpf :Version: |nimversion| .. default-role:: code .. include:: rstcommon.rst .. contents:: About this document =================== This document describes the upcoming Nim runtime which does not use classical GC algorithms anymore but is based on destructors and move semantics. The new runtime's advantages are that Nim programs become oblivious to the involved heap sizes and programs are easier to write to make effective use of multi-core machines. As a nice bonus, files and sockets and the like will not require manual `close` calls anymore. This document aims to be a precise specification about how move semantics and destructors work in Nim. Motivating example ================== With the language mechanisms described here, a custom seq could be written as: ```nim type myseq*[T] = object len, cap: int data: ptr UncheckedArray[T] proc `=destroy`*[T](x: var myseq[T]) = if x.data != nil: for i in 0..= x.cap: x.cap = max(x.len + 1, x.cap * 2) x.data = cast[typeof(x.data)](realloc(x.data, x.cap * sizeof(T))) x.data[x.len] = y inc x.len proc `[]`*[T](x: myseq[T]; i: Natural): lent T = assert i < x.len x.data[i] proc `[]=`*[T](x: var myseq[T]; i: Natural; y: sink T) = assert i < x.len x.data[i] = y proc createSeq*[T](elems: varargs[T]): myseq[T] = result.cap = elems.len result.len = elems.len result.data = cast[typeof(result.data)](alloc(result.cap * sizeof(T))) for i in 0.. destruction pairs, a proc's return type can be annotated as `lent T`. This is useful for "getter" accessors that seek to allow an immutable view into a container. The `sink` and `lent` annotations allow us to remove most (if not all) superfluous copies and destructions. `lent T` is like `var T` a hidden pointer. It is proven by the compiler that the pointer does not outlive its origin. No destructor call is injected for expressions of type `lent T` or of type `var T`. ```nim type Tree = object kids: seq[Tree] proc construct(kids: sink seq[Tree]): Tree = result = Tree(kids: kids) # converted into: `=sink`(result.kids, kids); wasMoved(kids) `=destroy`(kids) proc `[]`*(x: Tree; i: int): lent Tree = result = x.kids[i] # borrows from 'x', this is transformed into: result = addr x.kids[i] # This means 'lent' is like 'var T' a hidden pointer. # Unlike 'var' this hidden pointer cannot be used to mutate the object. iterator children*(t: Tree): lent Tree = for x in t.kids: yield x proc main = # everything turned into moves: let t = construct(@[construct(@[]), construct(@[])]) echo t[0] # accessor does not copy the element! ``` The cursor pragma ================= Under the `--mm:arc|orc`:option: modes Nim's `ref` type is implemented via the same runtime "hooks" and thus via reference counting. This means that cyclic structures cannot be freed immediately (`--mm:orc`:option: ships with a cycle collector). With the `cursor` pragma one can break up cycles declaratively: ```nim type Node = ref object left: Node # owning ref right {.cursor.}: Node # non-owning ref ``` But please notice that this is not C++'s weak_ptr, it means the right field is not involved in the reference counting, it is a raw pointer without runtime checks. Automatic reference counting also has the disadvantage that it introduces overhead when iterating over linked structures. The `cursor` pragma can also be used to avoid this overhead: ```nim var it {.cursor.} = listRoot while it != nil: use(it) it = it.next ``` In fact, `cursor` more generally prevents object construction/destruction pairs and so can also be useful in other contexts. The alternative solution would be to use raw pointers (`ptr`) instead which is more cumbersome and also more dangerous for Nim's evolution: Later on, the compiler can try to prove `cursor` pragmas to be safe, but for `ptr` the compiler has to remain silent about possible problems. Cursor inference / copy elision =============================== The current implementation also performs `cursor` inference. Cursor inference is a form of copy elision. To see how and when we can do that, think about this question: In `dest = src` when do we really have to *materialize* the full copy? - Only if `dest` or `src` are mutated afterward. If `dest` is a local variable that is simple to analyze. And if `src` is a location derived from a formal parameter, we also know it is not mutated! In other words, we do a compile-time copy-on-write analysis. This means that "borrowed" views can be written naturally and without explicit pointer indirections: ```nim proc main(tab: Table[string, string]) = let v = tab["key"] # inferred as cursor because 'tab' is not mutated. # no copy into 'v', no destruction of 'v'. use(v) useItAgain(v) ``` Hook lifting ============ The hooks of a tuple type `(A, B, ...)` are generated by lifting the hooks of the involved types `A`, `B`, ... to the tuple type. In other words, a copy `x = y` is implemented as `x[0] = y[0]; x[1] = y[1]; ...`, likewise for `=sink` and `=destroy`. Other value-based compound types like `object` and `array` are handled correspondingly. For `object` however, the compiler-generated hooks can be overridden. This can also be important to use an alternative traversal of the involved data structure that is more efficient or in order to avoid deep recursions. Hook generation =============== The ability to override a hook leads to a phase ordering problem: ```nim type Foo[T] = object proc main = var f: Foo[int] # error: destructor for 'f' called here before # it was seen in this module. proc `=destroy`[T](f: var Foo[T]) = discard ``` The solution is to define ``proc `=destroy`[T](f: var Foo[T])`` before it is used. The compiler generates implicit hooks for all types in *strategic places* so that an explicitly provided hook that comes too "late" can be detected reliably. These *strategic places* have been derived from the rewrite rules and are as follows: - In the construct `let/var x = ...` (var/let binding) hooks are generated for `typeof(x)`. - In `x = ...` (assignment) hooks are generated for `typeof(x)`. - In `f(...)` (function call) hooks are generated for `typeof(f(...))`. - For every sink parameter `x: sink T` the hooks are generated for `typeof(x)`. nodestroy pragma ================ The experimental `nodestroy`:idx: pragma inhibits hook injections. This can be used to specialize the object traversal in order to avoid deep recursions: ```nim type Node = ref object x, y: int32 left, right: Node type Tree = object root: Node proc `=destroy`(t: var Tree) {.nodestroy.} = # use an explicit stack so that we do not get stack overflows: var s: seq[Node] = @[t.root] while s.len > 0: let x = s.pop if x.left != nil: s.add(x.left) if x.right != nil: s.add(x.right) # free the memory explicit: dispose(x) # notice how even the destructor for 's' is not called implicitly # anymore thanks to .nodestroy, so we have to call it on our own: `=destroy`(s) ``` As can be seen from the example, this solution is hardly sufficient and should eventually be replaced by a better solution. Copy on write ============= String literals are implemented as "copy on write". When assigning a string literal to a variable, a copy of the literal won't be created. Instead the variable simply points to the literal. The literal is shared between different variables which are pointing to it. The copy operation is deferred until the first write. For example: ```nim var x = "abc" # no copy var y = x # no copy y[0] = 'h' # copy ``` The abstraction fails for `addr x` because whether the address is going to be used for mutations is unknown. `prepareMutation` needs to be called before the "address of" operation. For example: ```nim var x = "abc" var y = x prepareMutation(y) moveMem(addr y[0], addr x[0], 3) assert y == "abc" ```