destructors.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. x.data = nil
  31. proc `=copy`*[T](a: var myseq[T]; b: myseq[T]) =
  32. # do nothing for self-assignments:
  33. if a.data == b.data: return
  34. `=destroy`(a)
  35. a.len = b.len
  36. a.cap = b.cap
  37. if b.data != nil:
  38. a.data = cast[type(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. a.len = b.len
  46. a.cap = b.cap
  47. a.data = b.data
  48. proc add*[T](x: var myseq[T]; y: sink T) =
  49. if x.len >= x.cap: resize(x)
  50. x.data[x.len] = y
  51. inc x.len
  52. proc `[]`*[T](x: myseq[T]; i: Natural): lent T =
  53. assert i < x.len
  54. x.data[i]
  55. proc `[]=`*[T](x: var myseq[T]; i: Natural; y: sink T) =
  56. assert i < x.len
  57. x.data[i] = y
  58. proc createSeq*[T](elems: varargs[T]): myseq[T] =
  59. result.cap = elems.len
  60. result.len = elems.len
  61. result.data = cast[type(result.data)](alloc(result.cap * sizeof(T)))
  62. for i in 0..<result.len: result.data[i] = elems[i]
  63. proc len*[T](x: myseq[T]): int {.inline.} = x.len
  64. Lifetime-tracking hooks
  65. =======================
  66. The memory management for Nim's standard ``string`` and ``seq`` types as
  67. well as other standard collections is performed via so called
  68. "Lifetime-tracking hooks" or "type-bound operators". There are 3 different
  69. hooks for each (generic or concrete) object type ``T`` (``T`` can also be a
  70. ``distinct`` type) that are called implicitly by the compiler.
  71. (Note: The word "hook" here does not imply any kind of dynamic binding
  72. or runtime indirections, the implicit calls are statically bound and
  73. potentially inlined.)
  74. `=destroy` hook
  75. ---------------
  76. A `=destroy` hook frees the object's associated memory and releases
  77. other associated resources. Variables are destroyed via this hook when
  78. they go out of scope or when the routine they were declared in is about
  79. to return.
  80. The prototype of this hook for a type ``T`` needs to be:
  81. .. code-block:: nim
  82. proc `=destroy`(x: var T)
  83. The general pattern in ``=destroy`` looks like:
  84. .. code-block:: nim
  85. proc `=destroy`(x: var T) =
  86. # first check if 'x' was moved to somewhere else:
  87. if x.field != nil:
  88. freeResource(x.field)
  89. x.field = nil
  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. dest.field = source.field
  108. **Note**: ``=sink`` does not need to check for self-assignments.
  109. How self-assignments are handled is explained later in this document.
  110. `=copy` hook
  111. ---------------
  112. The ordinary assignment in Nim conceptually copies the values. The ``=copy`` hook
  113. is called for assignments that couldn't be transformed into ``=sink``
  114. operations.
  115. The prototype of this hook for a type ``T`` needs to be:
  116. .. code-block:: nim
  117. proc `=copy`(dest: var T; source: T)
  118. The general pattern in ``=copy`` looks like:
  119. .. code-block:: nim
  120. proc `=copy`(dest: var T; source: T) =
  121. # protect against self-assignments:
  122. if dest.field != source.field:
  123. `=destroy`(dest)
  124. dest.field = duplicateResource(source.field)
  125. The ``=copy`` proc can be marked with the ``{.error.}`` pragma. Then any assignment
  126. that otherwise would lead to a copy is prevented at compile-time.
  127. Move semantics
  128. ==============
  129. A "move" can be regarded as an optimized copy operation. If the source of the
  130. copy operation is not used afterwards, the copy can be replaced by a move. This
  131. document uses the notation ``lastReadOf(x)`` to describe that ``x`` is not
  132. used afterwards. This property is computed by a static control flow analysis
  133. but can also be enforced by using ``system.move`` explicitly.
  134. Swap
  135. ====
  136. The need to check for self-assignments and also the need to destroy previous
  137. objects inside ``=copy`` and ``=sink`` is a strong indicator to treat
  138. ``system.swap`` as a builtin primitive of its own that simply swaps every
  139. field in the involved objects via ``copyMem`` or a comparable mechanism.
  140. In other words, ``swap(a, b)`` is **not** implemented
  141. as ``let tmp = move(b); b = move(a); a = move(tmp)``.
  142. This has further consequences:
  143. * Objects that contain pointers that point to the same object are not supported
  144. by Nim's model. Otherwise swapped objects would end up in an inconsistent state.
  145. * Seqs can use ``realloc`` in the implementation.
  146. Sink parameters
  147. ===============
  148. To move a variable into a collection usually ``sink`` parameters are involved.
  149. A location that is passed to a ``sink`` parameter should not be used afterwards.
  150. This is ensured by a static analysis over a control flow graph. If it cannot be
  151. proven to be the last usage of the location, a copy is done instead and this
  152. copy is then passed to the sink parameter.
  153. A sink parameter
  154. *may* be consumed once in the proc's body but doesn't have to be consumed at all.
  155. The reason for this is that signatures
  156. like ``proc put(t: var Table; k: sink Key, v: sink Value)`` should be possible
  157. without any further overloads and ``put`` might not take owership of ``k`` if
  158. ``k`` already exists in the table. Sink parameters enable an affine type system,
  159. not a linear type system.
  160. The employed static analysis is limited and only concerned with local variables;
  161. however object and tuple fields are treated as separate entities:
  162. .. code-block:: nim
  163. proc consume(x: sink Obj) = discard "no implementation"
  164. proc main =
  165. let tup = (Obj(), Obj())
  166. consume tup[0]
  167. # ok, only tup[0] was consumed, tup[1] is still alive:
  168. echo tup[1]
  169. Sometimes it is required to explicitly ``move`` a value into its final position:
  170. .. code-block:: nim
  171. proc main =
  172. var dest, src: array[10, string]
  173. # ...
  174. for i in 0..high(dest): dest[i] = move(src[i])
  175. An implementation is allowed, but not required to implement even more move
  176. optimizations (and the current implementation does not).
  177. Sink parameter inference
  178. ========================
  179. The current implementation does a limited form of sink parameter
  180. inference. The `.nosinks`:idx: pragma can be used to disable this inference
  181. for a single routine:
  182. .. code-block:: nim
  183. proc addX(x: T; child: T) {.nosinks.} =
  184. x.s.add child
  185. To disable it for a section of code, one can
  186. use `{.push sinkInference: off.}`...`{.pop.}`.
  187. The details of the inference algorithm are currently undocumented.
  188. Rewrite rules
  189. =============
  190. **Note**: There are two different allowed implementation strategies:
  191. 1. The produced ``finally`` section can be a single section that is wrapped
  192. around the complete routine body.
  193. 2. The produced ``finally`` section is wrapped around the enclosing scope.
  194. The current implementation follows strategy (1). This means that resources are
  195. not destroyed at the scope exit, but at the proc exit.
  196. ::
  197. var x: T; stmts
  198. --------------- (destroy-var)
  199. var x: T; try stmts
  200. finally: `=destroy`(x)
  201. g(f(...))
  202. ------------------------ (nested-function-call)
  203. g(let tmp;
  204. bitwiseCopy tmp, f(...);
  205. tmp)
  206. finally: `=destroy`(tmp)
  207. x = f(...)
  208. ------------------------ (function-sink)
  209. `=sink`(x, f(...))
  210. x = lastReadOf z
  211. ------------------ (move-optimization)
  212. `=sink`(x, z)
  213. wasMoved(z)
  214. v = v
  215. ------------------ (self-assignment-removal)
  216. discard "nop"
  217. x = y
  218. ------------------ (copy)
  219. `=copy`(x, y)
  220. f_sink(g())
  221. ----------------------- (call-to-sink)
  222. f_sink(g())
  223. f_sink(notLastReadOf y)
  224. -------------------------- (copy-to-sink)
  225. (let tmp; `=copy`(tmp, y);
  226. f_sink(tmp))
  227. f_sink(lastReadOf y)
  228. ----------------------- (move-to-sink)
  229. f_sink(y)
  230. wasMoved(y)
  231. Object and array construction
  232. =============================
  233. Object and array construction is treated as a function call where the
  234. function has ``sink`` parameters.
  235. Destructor removal
  236. ==================
  237. ``wasMoved(x);`` followed by a `=destroy(x)` operation cancel each other
  238. out. An implementation is encouraged to exploit this in order to improve
  239. efficiency and code sizes.
  240. Self assignments
  241. ================
  242. ``=sink`` in combination with ``wasMoved`` can handle self-assignments but
  243. it's subtle.
  244. The simple case of ``x = x`` cannot be turned
  245. into ``=sink(x, x); wasMoved(x)`` because that would lose ``x``'s value.
  246. The solution is that simple self-assignments are simply transformed into
  247. an empty statement that does nothing.
  248. The complex case looks like a variant of ``x = f(x)``, we consider
  249. ``x = select(rand() < 0.5, x, y)`` here:
  250. .. code-block:: nim
  251. proc select(cond: bool; a, b: sink string): string =
  252. if cond:
  253. result = a # moves a into result
  254. else:
  255. result = b # moves b into result
  256. proc main =
  257. var x = "abc"
  258. var y = "xyz"
  259. # possible self-assignment:
  260. x = select(true, x, y)
  261. Is transformed into:
  262. .. code-block:: nim
  263. proc select(cond: bool; a, b: sink string): string =
  264. try:
  265. if cond:
  266. `=sink`(result, a)
  267. wasMoved(a)
  268. else:
  269. `=sink`(result, b)
  270. wasMoved(b)
  271. finally:
  272. `=destroy`(b)
  273. `=destroy`(a)
  274. proc main =
  275. var
  276. x: string
  277. y: string
  278. try:
  279. `=sink`(x, "abc")
  280. `=sink`(y, "xyz")
  281. `=sink`(x, select(true,
  282. let blitTmp = x
  283. wasMoved(x)
  284. blitTmp,
  285. let blitTmp = y
  286. wasMoved(y)
  287. blitTmp))
  288. echo [x]
  289. finally:
  290. `=destroy`(y)
  291. `=destroy`(x)
  292. As can be manually verified, this transformation is correct for
  293. self-assignments.
  294. Lent type
  295. =========
  296. ``proc p(x: sink T)`` means that the proc ``p`` takes ownership of ``x``.
  297. To eliminate even more creation/copy <-> destruction pairs, a proc's return
  298. type can be annotated as ``lent T``. This is useful for "getter" accessors
  299. that seek to allow an immutable view into a container.
  300. The ``sink`` and ``lent`` annotations allow us to remove most (if not all)
  301. superfluous copies and destructions.
  302. ``lent T`` is like ``var T`` a hidden pointer. It is proven by the compiler
  303. that the pointer does not outlive its origin. No destructor call is injected
  304. for expressions of type ``lent T`` or of type ``var T``.
  305. .. code-block:: nim
  306. type
  307. Tree = object
  308. kids: seq[Tree]
  309. proc construct(kids: sink seq[Tree]): Tree =
  310. result = Tree(kids: kids)
  311. # converted into:
  312. `=sink`(result.kids, kids); wasMoved(kids)
  313. `=destroy`(kids)
  314. proc `[]`*(x: Tree; i: int): lent Tree =
  315. result = x.kids[i]
  316. # borrows from 'x', this is transformed into:
  317. result = addr x.kids[i]
  318. # This means 'lent' is like 'var T' a hidden pointer.
  319. # Unlike 'var' this hidden pointer cannot be used to mutate the object.
  320. iterator children*(t: Tree): lent Tree =
  321. for x in t.kids: yield x
  322. proc main =
  323. # everything turned into moves:
  324. let t = construct(@[construct(@[]), construct(@[])])
  325. echo t[0] # accessor does not copy the element!
  326. Owned refs
  327. ==========
  328. Let ``W`` be an ``owned ref`` type. Conceptually its hooks look like:
  329. .. code-block:: nim
  330. proc `=destroy`(x: var W) =
  331. if x != nil:
  332. assert x.refcount == 0, "dangling unowned pointers exist!"
  333. `=destroy`(x[])
  334. x = nil
  335. proc `=`(x: var W; y: W) {.error: "owned refs can only be moved".}
  336. proc `=sink`(x: var W; y: W) =
  337. `=destroy`(x)
  338. bitwiseCopy x, y # raw pointer copy
  339. Let ``U`` be an unowned ``ref`` type. Conceptually its hooks look like:
  340. .. code-block:: nim
  341. proc `=destroy`(x: var U) =
  342. if x != nil:
  343. dec x.refcount
  344. proc `=`(x: var U; y: U) =
  345. # Note: No need to check for self-assignments here.
  346. if y != nil: inc y.refcount
  347. if x != nil: dec x.refcount
  348. bitwiseCopy x, y # raw pointer copy
  349. proc `=sink`(x: var U, y: U) {.error.}
  350. # Note: Moves are not available.
  351. Hook lifting
  352. ============
  353. The hooks of a tuple type ``(A, B, ...)`` are generated by lifting the
  354. hooks of the involved types ``A``, ``B``, ... to the tuple type. In
  355. other words, a copy ``x = y`` is implemented
  356. as ``x[0] = y[0]; x[1] = y[1]; ...``, likewise for ``=sink`` and ``=destroy``.
  357. Other value-based compound types like ``object`` and ``array`` are handled
  358. correspondingly. For ``object`` however, the compiler generated hooks
  359. can be overridden. This can also be important to use an alternative traversal
  360. of the involved datastructure that is more efficient or in order to avoid
  361. deep recursions.
  362. Hook generation
  363. ===============
  364. The ability to override a hook leads to a phase ordering problem:
  365. .. code-block:: nim
  366. type
  367. Foo[T] = object
  368. proc main =
  369. var f: Foo[int]
  370. # error: destructor for 'f' called here before
  371. # it was seen in this module.
  372. proc `=destroy`[T](f: var Foo[T]) =
  373. discard
  374. The solution is to define ``proc `=destroy`[T](f: var Foo[T])`` before
  375. it is used. The compiler generates implicit
  376. hooks for all types in *strategic places* so that an explicitly provided
  377. hook that comes too "late" can be detected reliably. These *strategic places*
  378. have been derived from the rewrite rules and are as follows:
  379. - In the construct ``let/var x = ...`` (var/let binding)
  380. hooks are generated for ``typeof(x)``.
  381. - In ``x = ...`` (assignment) hooks are generated for ``typeof(x)``.
  382. - In ``f(...)`` (function call) hooks are generated for ``typeof(f(...))``.
  383. - For every sink parameter ``x: sink T`` the hooks are generated
  384. for ``typeof(x)``.
  385. nodestroy pragma
  386. ================
  387. The experimental `nodestroy`:idx: pragma inhibits hook injections. This can be
  388. used to specialize the object traversal in order to avoid deep recursions:
  389. .. code-block:: nim
  390. type Node = ref object
  391. x, y: int32
  392. left, right: owned Node
  393. type Tree = object
  394. root: owned Node
  395. proc `=destroy`(t: var Tree) {.nodestroy.} =
  396. # use an explicit stack so that we do not get stack overflows:
  397. var s: seq[owned Node] = @[t.root]
  398. while s.len > 0:
  399. let x = s.pop
  400. if x.left != nil: s.add(x.left)
  401. if x.right != nil: s.add(x.right)
  402. # free the memory explicit:
  403. dispose(x)
  404. # notice how even the destructor for 's' is not called implicitly
  405. # anymore thanks to .nodestroy, so we have to call it on our own:
  406. `=destroy`(s)
  407. As can be seen from the example, this solution is hardly sufficient and
  408. should eventually be replaced by a better solution.