destructors.rst 21 KB

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