destructors.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. ==================================
  2. Nim Destructors and Move Semantics
  3. ==================================
  4. :Authors: Andreas Rumpf
  5. :Version: |nimversion|
  6. .. contents::
  7. About this document
  8. ===================
  9. This document describes the upcoming Nim runtime which does
  10. not use classical GC algorithms anymore but is based on destructors and
  11. move semantics. The new runtime's advantages are that Nim programs become
  12. oblivious to the involved heap sizes and programs are easier to write to make
  13. effective use of multi-core machines. As a nice bonus, files and sockets and
  14. the like will not require manual ``close`` calls anymore.
  15. This document aims to be a precise specification about how
  16. move semantics and destructors work in Nim.
  17. Motivating example
  18. ==================
  19. With the language mechanisms described here, a custom seq could be
  20. written as:
  21. .. code-block:: nim
  22. type
  23. myseq*[T] = object
  24. len, cap: int
  25. data: ptr UncheckedArray[T]
  26. proc `=destroy`*[T](x: var myseq[T]) =
  27. if x.data != nil:
  28. for i in 0..<x.len: `=destroy`(x[i])
  29. dealloc(x.data)
  30. proc `=copy`*[T](a: var myseq[T]; b: myseq[T]) =
  31. # do nothing for self-assignments:
  32. if a.data == b.data: return
  33. `=destroy`(a)
  34. wasMoved(a)
  35. a.len = b.len
  36. a.cap = b.cap
  37. if b.data != nil:
  38. a.data = cast[typeof(a.data)](alloc(a.cap * sizeof(T)))
  39. for i in 0..<a.len:
  40. a.data[i] = b.data[i]
  41. proc `=sink`*[T](a: var myseq[T]; b: myseq[T]) =
  42. # move assignment, optional.
  43. # Compiler is using `=destroy` and `copyMem` when not provided
  44. `=destroy`(a)
  45. wasMoved(a)
  46. a.len = b.len
  47. a.cap = b.cap
  48. a.data = b.data
  49. proc add*[T](x: var myseq[T]; y: sink T) =
  50. if x.len >= x.cap: resize(x)
  51. x.data[x.len] = y
  52. inc x.len
  53. proc `[]`*[T](x: myseq[T]; i: Natural): lent T =
  54. assert i < x.len
  55. x.data[i]
  56. proc `[]=`*[T](x: var myseq[T]; i: Natural; y: sink T) =
  57. assert i < x.len
  58. x.data[i] = y
  59. proc createSeq*[T](elems: varargs[T]): myseq[T] =
  60. result.cap = elems.len
  61. result.len = elems.len
  62. result.data = cast[typeof(result.data)](alloc(result.cap * sizeof(T)))
  63. for i in 0..<result.len: result.data[i] = elems[i]
  64. proc len*[T](x: myseq[T]): int {.inline.} = x.len
  65. Lifetime-tracking hooks
  66. =======================
  67. The memory management for Nim's standard ``string`` and ``seq`` types as
  68. well as other standard collections is performed via so-called
  69. "Lifetime-tracking hooks" or "type-bound operators". There are 3 different
  70. hooks for each (generic or concrete) object type ``T`` (``T`` can also be a
  71. ``distinct`` type) that are called implicitly by the compiler.
  72. (Note: The word "hook" here does not imply any kind of dynamic binding
  73. or runtime indirections, the implicit calls are statically bound and
  74. potentially inlined.)
  75. `=destroy` hook
  76. ---------------
  77. A `=destroy` hook frees the object's associated memory and releases
  78. other associated resources. Variables are destroyed via this hook when
  79. they go out of scope or when the routine they were declared in is about
  80. to return.
  81. The prototype of this hook for a type ``T`` needs to be:
  82. .. code-block:: nim
  83. proc `=destroy`(x: var T)
  84. The general pattern in ``=destroy`` looks like:
  85. .. code-block:: nim
  86. proc `=destroy`(x: var T) =
  87. # first check if 'x' was moved to somewhere else:
  88. if x.field != nil:
  89. freeResource(x.field)
  90. `=sink` hook
  91. ------------
  92. A `=sink` hook moves an object around, the resources are stolen from the source
  93. and passed to the destination. It is ensured that the source's destructor does
  94. not free the resources afterward by setting the object to its default value
  95. (the value the object's state started in). Setting an object ``x`` back to its
  96. default value is written as ``wasMoved(x)``. When not provided the compiler
  97. is using a combination of `=destroy` and `copyMem` instead. This is efficient
  98. hence users rarely need to implement their own `=sink` operator, it is enough to
  99. provide `=destroy` and `=copy`, compiler will take care of the rest.
  100. The prototype of this hook for a type ``T`` needs to be:
  101. .. code-block:: nim
  102. proc `=sink`(dest: var T; source: T)
  103. The general pattern in ``=sink`` looks like:
  104. .. code-block:: nim
  105. proc `=sink`(dest: var T; source: T) =
  106. `=destroy`(dest)
  107. wasMoved(dest)
  108. dest.field = source.field
  109. **Note**: ``=sink`` does not need to check for self-assignments.
  110. How self-assignments are handled is explained later in this document.
  111. `=copy` hook
  112. ---------------
  113. The ordinary assignment in Nim conceptually copies the values. The ``=copy`` hook
  114. is called for assignments that couldn't be transformed into ``=sink``
  115. operations.
  116. The prototype of this hook for a type ``T`` needs to be:
  117. .. code-block:: nim
  118. proc `=copy`(dest: var T; source: T)
  119. The general pattern in ``=copy`` looks like:
  120. .. code-block:: nim
  121. proc `=copy`(dest: var T; source: T) =
  122. # protect against self-assignments:
  123. if dest.field != source.field:
  124. `=destroy`(dest)
  125. wasMoved(dest)
  126. dest.field = duplicateResource(source.field)
  127. The ``=copy`` proc can be marked with the ``{.error.}`` pragma. Then any assignment
  128. that otherwise would lead to a copy is prevented at compile-time. This looks like:
  129. .. code-block:: nim
  130. proc `=copy`(dest: var T; source: T) {.error.}
  131. but a custom error message (e.g., ``{.error: "custom error".}``) will not be emitted
  132. by the compiler. Notice that there is no ``=`` before the ``{.error.}`` pragma.
  133. Move semantics
  134. ==============
  135. A "move" can be regarded as an optimized copy operation. If the source of the
  136. copy operation is not used afterward, the copy can be replaced by a move. This
  137. document uses the notation ``lastReadOf(x)`` to describe that ``x`` is not
  138. used afterwards. This property is computed by a static control flow analysis
  139. but can also be enforced by using ``system.move`` explicitly.
  140. Swap
  141. ====
  142. The need to check for self-assignments and also the need to destroy previous
  143. objects inside ``=copy`` and ``=sink`` is a strong indicator to treat
  144. ``system.swap`` as a builtin primitive of its own that simply swaps every
  145. field in the involved objects via ``copyMem`` or a comparable mechanism.
  146. In other words, ``swap(a, b)`` is **not** implemented
  147. as ``let tmp = move(b); b = move(a); a = move(tmp)``.
  148. This has further consequences:
  149. * Objects that contain pointers that point to the same object are not supported
  150. by Nim's model. Otherwise swapped objects would end up in an inconsistent state.
  151. * Seqs can use ``realloc`` in the implementation.
  152. Sink parameters
  153. ===============
  154. To move a variable into a collection usually ``sink`` parameters are involved.
  155. A location that is passed to a ``sink`` parameter should not be used afterward.
  156. This is ensured by a static analysis over a control flow graph. If it cannot be
  157. proven to be the last usage of the location, a copy is done instead and this
  158. copy is then passed to the sink parameter.
  159. A sink parameter
  160. *may* be consumed once in the proc's body but doesn't have to be consumed at all.
  161. The reason for this is that signatures
  162. like ``proc put(t: var Table; k: sink Key, v: sink Value)`` should be possible
  163. without any further overloads and ``put`` might not take ownership of ``k`` if
  164. ``k`` already exists in the table. Sink parameters enable an affine type system,
  165. not a linear type system.
  166. The employed static analysis is limited and only concerned with local variables;
  167. however, object and tuple fields are treated as separate entities:
  168. .. code-block:: nim
  169. proc consume(x: sink Obj) = discard "no implementation"
  170. proc main =
  171. let tup = (Obj(), Obj())
  172. consume tup[0]
  173. # ok, only tup[0] was consumed, tup[1] is still alive:
  174. echo tup[1]
  175. Sometimes it is required to explicitly ``move`` a value into its final position:
  176. .. code-block:: nim
  177. proc main =
  178. var dest, src: array[10, string]
  179. # ...
  180. for i in 0..high(dest): dest[i] = move(src[i])
  181. An implementation is allowed, but not required to implement even more move
  182. optimizations (and the current implementation does not).
  183. Sink parameter inference
  184. ========================
  185. The current implementation can do a limited form of sink parameter
  186. inference. But it has to be enabled via `--sinkInference:on`, either
  187. on the command line or via a `push` pragma.
  188. To enable it for a section of code, one can
  189. use `{.push sinkInference: on.}`...`{.pop.}`.
  190. The `.nosinks`:idx: pragma can be used to disable this inference
  191. for a single routine:
  192. .. code-block:: nim
  193. proc addX(x: T; child: T) {.nosinks.} =
  194. x.s.add child
  195. The details of the inference algorithm are currently undocumented.
  196. Rewrite rules
  197. =============
  198. **Note**: There are two different allowed implementation strategies:
  199. 1. The produced ``finally`` section can be a single section that is wrapped
  200. around the complete routine body.
  201. 2. The produced ``finally`` section is wrapped around the enclosing scope.
  202. The current implementation follows strategy (2). This means that resources are
  203. destroyed at the scope exit.
  204. ::
  205. var x: T; stmts
  206. --------------- (destroy-var)
  207. var x: T; try stmts
  208. finally: `=destroy`(x)
  209. g(f(...))
  210. ------------------------ (nested-function-call)
  211. g(let tmp;
  212. bitwiseCopy tmp, f(...);
  213. tmp)
  214. finally: `=destroy`(tmp)
  215. x = f(...)
  216. ------------------------ (function-sink)
  217. `=sink`(x, f(...))
  218. x = lastReadOf z
  219. ------------------ (move-optimization)
  220. `=sink`(x, z)
  221. wasMoved(z)
  222. v = v
  223. ------------------ (self-assignment-removal)
  224. discard "nop"
  225. x = y
  226. ------------------ (copy)
  227. `=copy`(x, y)
  228. f_sink(g())
  229. ----------------------- (call-to-sink)
  230. f_sink(g())
  231. f_sink(notLastReadOf y)
  232. -------------------------- (copy-to-sink)
  233. (let tmp; `=copy`(tmp, y);
  234. f_sink(tmp))
  235. f_sink(lastReadOf y)
  236. ----------------------- (move-to-sink)
  237. f_sink(y)
  238. wasMoved(y)
  239. Object and array construction
  240. =============================
  241. Object and array construction is treated as a function call where the
  242. function has ``sink`` parameters.
  243. Destructor removal
  244. ==================
  245. ``wasMoved(x);`` followed by a `=destroy(x)` operation cancel each other
  246. out. An implementation is encouraged to exploit this in order to improve
  247. efficiency and code sizes. The current implementation does perform this
  248. optimization.
  249. Self assignments
  250. ================
  251. ``=sink`` in combination with ``wasMoved`` can handle self-assignments but
  252. it's subtle.
  253. The simple case of ``x = x`` cannot be turned
  254. into ``=sink(x, x); wasMoved(x)`` because that would lose ``x``'s value.
  255. The solution is that simple self-assignments are simply transformed into
  256. an empty statement that does nothing.
  257. The complex case looks like a variant of ``x = f(x)``, we consider
  258. ``x = select(rand() < 0.5, x, y)`` here:
  259. .. code-block:: nim
  260. proc select(cond: bool; a, b: sink string): string =
  261. if cond:
  262. result = a # moves a into result
  263. else:
  264. result = b # moves b into result
  265. proc main =
  266. var x = "abc"
  267. var y = "xyz"
  268. # possible self-assignment:
  269. x = select(true, x, y)
  270. Is transformed into:
  271. .. code-block:: nim
  272. proc select(cond: bool; a, b: sink string): string =
  273. try:
  274. if cond:
  275. `=sink`(result, a)
  276. wasMoved(a)
  277. else:
  278. `=sink`(result, b)
  279. wasMoved(b)
  280. finally:
  281. `=destroy`(b)
  282. `=destroy`(a)
  283. proc main =
  284. var
  285. x: string
  286. y: string
  287. try:
  288. `=sink`(x, "abc")
  289. `=sink`(y, "xyz")
  290. `=sink`(x, select(true,
  291. let blitTmp = x
  292. wasMoved(x)
  293. blitTmp,
  294. let blitTmp = y
  295. wasMoved(y)
  296. blitTmp))
  297. echo [x]
  298. finally:
  299. `=destroy`(y)
  300. `=destroy`(x)
  301. As can be manually verified, this transformation is correct for
  302. self-assignments.
  303. Lent type
  304. =========
  305. ``proc p(x: sink T)`` means that the proc ``p`` takes ownership of ``x``.
  306. To eliminate even more creation/copy <-> destruction pairs, a proc's return
  307. type can be annotated as ``lent T``. This is useful for "getter" accessors
  308. that seek to allow an immutable view into a container.
  309. The ``sink`` and ``lent`` annotations allow us to remove most (if not all)
  310. superfluous copies and destructions.
  311. ``lent T`` is like ``var T`` a hidden pointer. It is proven by the compiler
  312. that the pointer does not outlive its origin. No destructor call is injected
  313. for expressions of type ``lent T`` or of type ``var T``.
  314. .. code-block:: nim
  315. type
  316. Tree = object
  317. kids: seq[Tree]
  318. proc construct(kids: sink seq[Tree]): Tree =
  319. result = Tree(kids: kids)
  320. # converted into:
  321. `=sink`(result.kids, kids); wasMoved(kids)
  322. `=destroy`(kids)
  323. proc `[]`*(x: Tree; i: int): lent Tree =
  324. result = x.kids[i]
  325. # borrows from 'x', this is transformed into:
  326. result = addr x.kids[i]
  327. # This means 'lent' is like 'var T' a hidden pointer.
  328. # Unlike 'var' this hidden pointer cannot be used to mutate the object.
  329. iterator children*(t: Tree): lent Tree =
  330. for x in t.kids: yield x
  331. proc main =
  332. # everything turned into moves:
  333. let t = construct(@[construct(@[]), construct(@[])])
  334. echo t[0] # accessor does not copy the element!
  335. The .cursor annotation
  336. ======================
  337. Under the ``--gc:arc|orc`` modes Nim's `ref` type is implemented via the same runtime
  338. "hooks" and thus via reference counting. This means that cyclic structures cannot be freed
  339. immediately (``--gc:orc`` ships with a cycle collector). With the ``.cursor`` annotation
  340. one can break up cycles declaratively:
  341. .. code-block:: nim
  342. type
  343. Node = ref object
  344. left: Node # owning ref
  345. right {.cursor.}: Node # non-owning ref
  346. But please notice that this is not C++'s weak_ptr, it means the right field is not
  347. involved in the reference counting, it is a raw pointer without runtime checks.
  348. Automatic reference counting also has the disadvantage that it introduces overhead
  349. when iterating over linked structures. The ``.cursor`` annotation can also be used
  350. to avoid this overhead:
  351. .. code-block:: nim
  352. var it {.cursor.} = listRoot
  353. while it != nil:
  354. use(it)
  355. it = it.next
  356. In fact, ``.cursor`` more generally prevents object construction/destruction pairs
  357. and so can also be useful in other contexts. The alternative solution would be to
  358. use raw pointers (``ptr``) instead which is more cumbersome and also more dangerous
  359. for Nim's evolution: Later on, the compiler can try to prove ``.cursor`` annotations
  360. to be safe, but for ``ptr`` the compiler has to remain silent about possible
  361. problems.
  362. Cursor inference / copy elision
  363. ===============================
  364. The current implementation also performs `.cursor` inference. Cursor inference is
  365. a form of copy elision.
  366. To see how and when we can do that, think about this question: In `dest = src` when
  367. do we really have to *materialize* the full copy? - Only if `dest` or `src` are mutated
  368. afterwards. If `dest` is a local variable that is simple to analyze. And if `src` is a
  369. location derived from a formal parameter, we also know it is not mutated! In other
  370. words, we do a compile-time copy-on-write analysis.
  371. This means that "borrowed" views can be written naturally and without explicit pointer
  372. indirections:
  373. .. code-block:: nim
  374. proc main(tab: Table[string, string]) =
  375. let v = tab["key"] # inferred as .cursor because 'tab' is not mutated.
  376. # no copy into 'v', no destruction of 'v'.
  377. use(v)
  378. useItAgain(v)
  379. Hook lifting
  380. ============
  381. The hooks of a tuple type ``(A, B, ...)`` are generated by lifting the
  382. hooks of the involved types ``A``, ``B``, ... to the tuple type. In
  383. other words, a copy ``x = y`` is implemented
  384. as ``x[0] = y[0]; x[1] = y[1]; ...``, likewise for ``=sink`` and ``=destroy``.
  385. Other value-based compound types like ``object`` and ``array`` are handled
  386. correspondingly. For ``object`` however, the compiler-generated hooks
  387. can be overridden. This can also be important to use an alternative traversal
  388. of the involved data structure that is more efficient or in order to avoid
  389. deep recursions.
  390. Hook generation
  391. ===============
  392. The ability to override a hook leads to a phase ordering problem:
  393. .. code-block:: nim
  394. type
  395. Foo[T] = object
  396. proc main =
  397. var f: Foo[int]
  398. # error: destructor for 'f' called here before
  399. # it was seen in this module.
  400. proc `=destroy`[T](f: var Foo[T]) =
  401. discard
  402. The solution is to define ``proc `=destroy`[T](f: var Foo[T])`` before
  403. it is used. The compiler generates implicit
  404. hooks for all types in *strategic places* so that an explicitly provided
  405. hook that comes too "late" can be detected reliably. These *strategic places*
  406. have been derived from the rewrite rules and are as follows:
  407. - In the construct ``let/var x = ...`` (var/let binding)
  408. hooks are generated for ``typeof(x)``.
  409. - In ``x = ...`` (assignment) hooks are generated for ``typeof(x)``.
  410. - In ``f(...)`` (function call) hooks are generated for ``typeof(f(...))``.
  411. - For every sink parameter ``x: sink T`` the hooks are generated
  412. for ``typeof(x)``.
  413. nodestroy pragma
  414. ================
  415. The experimental `nodestroy`:idx: pragma inhibits hook injections. This can be
  416. used to specialize the object traversal in order to avoid deep recursions:
  417. .. code-block:: nim
  418. type Node = ref object
  419. x, y: int32
  420. left, right: Node
  421. type Tree = object
  422. root: Node
  423. proc `=destroy`(t: var Tree) {.nodestroy.} =
  424. # use an explicit stack so that we do not get stack overflows:
  425. var s: seq[Node] = @[t.root]
  426. while s.len > 0:
  427. let x = s.pop
  428. if x.left != nil: s.add(x.left)
  429. if x.right != nil: s.add(x.right)
  430. # free the memory explicit:
  431. dispose(x)
  432. # notice how even the destructor for 's' is not called implicitly
  433. # anymore thanks to .nodestroy, so we have to call it on our own:
  434. `=destroy`(s)
  435. As can be seen from the example, this solution is hardly sufficient and
  436. should eventually be replaced by a better solution.