destructors.rst 21 KB

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