destructors.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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 source's destructor does
  94. not free the resources afterwards 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 about 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.
  129. Move semantics
  130. ==============
  131. A "move" can be regarded as an optimized copy operation. If the source of the
  132. copy operation is not used afterwards, the copy can be replaced by a move. This
  133. document uses the notation ``lastReadOf(x)`` to describe that ``x`` is not
  134. used afterwards. This property is computed by a static control flow analysis
  135. but can also be enforced by using ``system.move`` explicitly.
  136. Swap
  137. ====
  138. The need to check for self-assignments and also the need to destroy previous
  139. objects inside ``=copy`` and ``=sink`` is a strong indicator to treat
  140. ``system.swap`` as a builtin primitive of its own that simply swaps every
  141. field in the involved objects via ``copyMem`` or a comparable mechanism.
  142. In other words, ``swap(a, b)`` is **not** implemented
  143. as ``let tmp = move(b); b = move(a); a = move(tmp)``.
  144. This has further consequences:
  145. * Objects that contain pointers that point to the same object are not supported
  146. by Nim's model. Otherwise swapped objects would end up in an inconsistent state.
  147. * Seqs can use ``realloc`` in the implementation.
  148. Sink parameters
  149. ===============
  150. To move a variable into a collection usually ``sink`` parameters are involved.
  151. A location that is passed to a ``sink`` parameter should not be used afterwards.
  152. This is ensured by a static analysis over a control flow graph. If it cannot be
  153. proven to be the last usage of the location, a copy is done instead and this
  154. copy is then passed to the sink parameter.
  155. A sink parameter
  156. *may* be consumed once in the proc's body but doesn't have to be consumed at all.
  157. The reason for this is that signatures
  158. like ``proc put(t: var Table; k: sink Key, v: sink Value)`` should be possible
  159. without any further overloads and ``put`` might not take ownership of ``k`` if
  160. ``k`` already exists in the table. Sink parameters enable an affine type system,
  161. not a linear type system.
  162. The employed static analysis is limited and only concerned with local variables;
  163. however object and tuple fields are treated as separate entities:
  164. .. code-block:: nim
  165. proc consume(x: sink Obj) = discard "no implementation"
  166. proc main =
  167. let tup = (Obj(), Obj())
  168. consume tup[0]
  169. # ok, only tup[0] was consumed, tup[1] is still alive:
  170. echo tup[1]
  171. Sometimes it is required to explicitly ``move`` a value into its final position:
  172. .. code-block:: nim
  173. proc main =
  174. var dest, src: array[10, string]
  175. # ...
  176. for i in 0..high(dest): dest[i] = move(src[i])
  177. An implementation is allowed, but not required to implement even more move
  178. optimizations (and the current implementation does not).
  179. Sink parameter inference
  180. ========================
  181. The current implementation can do a limited form of sink parameter
  182. inference. But it has to be enabled via `--sinkInference:on`, either
  183. on the command line or via a `push` pragma.
  184. To enable it for a section of code, one can
  185. use `{.push sinkInference: on.}`...`{.pop.}`.
  186. The `.nosinks`:idx: pragma can be used to disable this inference
  187. for a single routine:
  188. .. code-block:: nim
  189. proc addX(x: T; child: T) {.nosinks.} =
  190. x.s.add child
  191. The details of the inference algorithm are currently undocumented.
  192. Rewrite rules
  193. =============
  194. **Note**: There are two different allowed implementation strategies:
  195. 1. The produced ``finally`` section can be a single section that is wrapped
  196. around the complete routine body.
  197. 2. The produced ``finally`` section is wrapped around the enclosing scope.
  198. The current implementation follows strategy (2). This means that resources are
  199. destroyed at the scope exit.
  200. ::
  201. var x: T; stmts
  202. --------------- (destroy-var)
  203. var x: T; try stmts
  204. finally: `=destroy`(x)
  205. g(f(...))
  206. ------------------------ (nested-function-call)
  207. g(let tmp;
  208. bitwiseCopy tmp, f(...);
  209. tmp)
  210. finally: `=destroy`(tmp)
  211. x = f(...)
  212. ------------------------ (function-sink)
  213. `=sink`(x, f(...))
  214. x = lastReadOf z
  215. ------------------ (move-optimization)
  216. `=sink`(x, z)
  217. wasMoved(z)
  218. v = v
  219. ------------------ (self-assignment-removal)
  220. discard "nop"
  221. x = y
  222. ------------------ (copy)
  223. `=copy`(x, y)
  224. f_sink(g())
  225. ----------------------- (call-to-sink)
  226. f_sink(g())
  227. f_sink(notLastReadOf y)
  228. -------------------------- (copy-to-sink)
  229. (let tmp; `=copy`(tmp, y);
  230. f_sink(tmp))
  231. f_sink(lastReadOf y)
  232. ----------------------- (move-to-sink)
  233. f_sink(y)
  234. wasMoved(y)
  235. Object and array construction
  236. =============================
  237. Object and array construction is treated as a function call where the
  238. function has ``sink`` parameters.
  239. Destructor removal
  240. ==================
  241. ``wasMoved(x);`` followed by a `=destroy(x)` operation cancel each other
  242. out. An implementation is encouraged to exploit this in order to improve
  243. efficiency and code sizes. The current implementation does perform this
  244. optimization.
  245. Self assignments
  246. ================
  247. ``=sink`` in combination with ``wasMoved`` can handle self-assignments but
  248. it's subtle.
  249. The simple case of ``x = x`` cannot be turned
  250. into ``=sink(x, x); wasMoved(x)`` because that would lose ``x``'s value.
  251. The solution is that simple self-assignments are simply transformed into
  252. an empty statement that does nothing.
  253. The complex case looks like a variant of ``x = f(x)``, we consider
  254. ``x = select(rand() < 0.5, x, y)`` here:
  255. .. code-block:: nim
  256. proc select(cond: bool; a, b: sink string): string =
  257. if cond:
  258. result = a # moves a into result
  259. else:
  260. result = b # moves b into result
  261. proc main =
  262. var x = "abc"
  263. var y = "xyz"
  264. # possible self-assignment:
  265. x = select(true, x, y)
  266. Is transformed into:
  267. .. code-block:: nim
  268. proc select(cond: bool; a, b: sink string): string =
  269. try:
  270. if cond:
  271. `=sink`(result, a)
  272. wasMoved(a)
  273. else:
  274. `=sink`(result, b)
  275. wasMoved(b)
  276. finally:
  277. `=destroy`(b)
  278. `=destroy`(a)
  279. proc main =
  280. var
  281. x: string
  282. y: string
  283. try:
  284. `=sink`(x, "abc")
  285. `=sink`(y, "xyz")
  286. `=sink`(x, select(true,
  287. let blitTmp = x
  288. wasMoved(x)
  289. blitTmp,
  290. let blitTmp = y
  291. wasMoved(y)
  292. blitTmp))
  293. echo [x]
  294. finally:
  295. `=destroy`(y)
  296. `=destroy`(x)
  297. As can be manually verified, this transformation is correct for
  298. self-assignments.
  299. Lent type
  300. =========
  301. ``proc p(x: sink T)`` means that the proc ``p`` takes ownership of ``x``.
  302. To eliminate even more creation/copy <-> destruction pairs, a proc's return
  303. type can be annotated as ``lent T``. This is useful for "getter" accessors
  304. that seek to allow an immutable view into a container.
  305. The ``sink`` and ``lent`` annotations allow us to remove most (if not all)
  306. superfluous copies and destructions.
  307. ``lent T`` is like ``var T`` a hidden pointer. It is proven by the compiler
  308. that the pointer does not outlive its origin. No destructor call is injected
  309. for expressions of type ``lent T`` or of type ``var T``.
  310. .. code-block:: nim
  311. type
  312. Tree = object
  313. kids: seq[Tree]
  314. proc construct(kids: sink seq[Tree]): Tree =
  315. result = Tree(kids: kids)
  316. # converted into:
  317. `=sink`(result.kids, kids); wasMoved(kids)
  318. `=destroy`(kids)
  319. proc `[]`*(x: Tree; i: int): lent Tree =
  320. result = x.kids[i]
  321. # borrows from 'x', this is transformed into:
  322. result = addr x.kids[i]
  323. # This means 'lent' is like 'var T' a hidden pointer.
  324. # Unlike 'var' this hidden pointer cannot be used to mutate the object.
  325. iterator children*(t: Tree): lent Tree =
  326. for x in t.kids: yield x
  327. proc main =
  328. # everything turned into moves:
  329. let t = construct(@[construct(@[]), construct(@[])])
  330. echo t[0] # accessor does not copy the element!
  331. The .cursor annotation
  332. ======================
  333. Under the ``--gc:arc|orc`` modes Nim's `ref` type is implemented via the same runtime
  334. "hooks" and thus via reference counting. This means that cyclic structures cannot be freed
  335. immediately (``--gc:orc`` ships with a cycle collector). With the ``.cursor`` annotation
  336. one can break up cycles declaratively:
  337. .. code-block:: nim
  338. type
  339. Node = ref object
  340. left: Node # owning ref
  341. right {.cursor.}: Node # non-owning ref
  342. But please notice that this is not C++'s weak_ptr, it means the right field is not
  343. involved in the reference counting, it is a raw pointer without runtime checks.
  344. Automatic reference counting also has the disadvantage that it introduces overhead
  345. when iterating over linked structures. The ``.cursor`` annotation can also be used
  346. to avoid this overhead:
  347. .. code-block:: nim
  348. var it {.cursor.} = listRoot
  349. while it != nil:
  350. use(it)
  351. it = it.next
  352. In fact, ``.cursor`` more generally prevents object construction/destruction pairs
  353. and so can also be useful in other contexts. The alternative solution would be to
  354. use raw pointers (``ptr``) instead which is more cumbersome and also more dangerous
  355. for Nim's evolution: Later on the compiler can try to prove ``.cursor`` annotations
  356. to be safe, but for ``ptr`` the compiler has to remain silent about possible
  357. problems.
  358. Cursor inference / copy elision
  359. ===============================
  360. The current implementation also performs `.cursor` inference. Cursor inference is
  361. a form of copy elision.
  362. To see how and when we can do that, think about this question: In `dest = src` when
  363. do we really have to *materialize* the full copy? - Only if `dest` or `src` are mutated
  364. afterwards. If `dest` is a local variable that is simple to analyse. And if `src` is a
  365. location derived from a formal parameter, we also know it is not mutated! In other
  366. words, we do a compile-time copy-on-write analysis.
  367. This means that "borrowed" views can be written naturally and without explicit pointer
  368. indirections:
  369. .. code-block:: nim
  370. proc main(tab: Table[string, string]) =
  371. let v = tab["key"] # inferred as .cursor because 'tab' is not mutated.
  372. # no copy into 'v', no destruction of 'v'.
  373. use(v)
  374. useItAgain(v)
  375. Hook lifting
  376. ============
  377. The hooks of a tuple type ``(A, B, ...)`` are generated by lifting the
  378. hooks of the involved types ``A``, ``B``, ... to the tuple type. In
  379. other words, a copy ``x = y`` is implemented
  380. as ``x[0] = y[0]; x[1] = y[1]; ...``, likewise for ``=sink`` and ``=destroy``.
  381. Other value-based compound types like ``object`` and ``array`` are handled
  382. correspondingly. For ``object`` however, the compiler generated hooks
  383. can be overridden. This can also be important to use an alternative traversal
  384. of the involved datastructure that is more efficient or in order to avoid
  385. deep recursions.
  386. Hook generation
  387. ===============
  388. The ability to override a hook leads to a phase ordering problem:
  389. .. code-block:: nim
  390. type
  391. Foo[T] = object
  392. proc main =
  393. var f: Foo[int]
  394. # error: destructor for 'f' called here before
  395. # it was seen in this module.
  396. proc `=destroy`[T](f: var Foo[T]) =
  397. discard
  398. The solution is to define ``proc `=destroy`[T](f: var Foo[T])`` before
  399. it is used. The compiler generates implicit
  400. hooks for all types in *strategic places* so that an explicitly provided
  401. hook that comes too "late" can be detected reliably. These *strategic places*
  402. have been derived from the rewrite rules and are as follows:
  403. - In the construct ``let/var x = ...`` (var/let binding)
  404. hooks are generated for ``typeof(x)``.
  405. - In ``x = ...`` (assignment) hooks are generated for ``typeof(x)``.
  406. - In ``f(...)`` (function call) hooks are generated for ``typeof(f(...))``.
  407. - For every sink parameter ``x: sink T`` the hooks are generated
  408. for ``typeof(x)``.
  409. nodestroy pragma
  410. ================
  411. The experimental `nodestroy`:idx: pragma inhibits hook injections. This can be
  412. used to specialize the object traversal in order to avoid deep recursions:
  413. .. code-block:: nim
  414. type Node = ref object
  415. x, y: int32
  416. left, right: Node
  417. type Tree = object
  418. root: Node
  419. proc `=destroy`(t: var Tree) {.nodestroy.} =
  420. # use an explicit stack so that we do not get stack overflows:
  421. var s: seq[Node] = @[t.root]
  422. while s.len > 0:
  423. let x = s.pop
  424. if x.left != nil: s.add(x.left)
  425. if x.right != nil: s.add(x.right)
  426. # free the memory explicit:
  427. dispose(x)
  428. # notice how even the destructor for 's' is not called implicitly
  429. # anymore thanks to .nodestroy, so we have to call it on our own:
  430. `=destroy`(s)
  431. As can be seen from the example, this solution is hardly sufficient and
  432. should eventually be replaced by a better solution.