wrapnils.nim 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. ## This module allows evaluating expressions safely against the following conditions:
  2. ## * nil dereferences
  3. ## * field accesses with incorrect discriminant in case objects
  4. ##
  5. ## `default(T)` is returned in those cases when evaluating an expression of type `T`.
  6. ## This simplifies code by reducing need for if-else branches.
  7. ##
  8. ## Note: experimental module, unstable API.
  9. #[
  10. TODO:
  11. consider handling indexing operations, eg:
  12. doAssert ?.default(seq[int])[3] == default(int)
  13. ]#
  14. import macros
  15. runnableExamples:
  16. type Foo = ref object
  17. x1: string
  18. x2: Foo
  19. x3: ref int
  20. var f: Foo
  21. assert ?.f.x2.x1 == "" # returns default value since `f` is nil
  22. var f2 = Foo(x1: "a")
  23. f2.x2 = f2
  24. assert ?.f2.x1 == "a" # same as f2.x1 (no nil LHS in this chain)
  25. assert ?.Foo(x1: "a").x1 == "a" # can use constructor inside
  26. # when you know a sub-expression doesn't involve a `nil` (e.g. `f2.x2.x2`),
  27. # you can scope it as follows:
  28. assert ?.(f2.x2.x2).x3[] == 0
  29. assert (?.f2.x2.x2).x3 == nil # this terminates ?. early
  30. runnableExamples:
  31. # ?. also allows case object
  32. type B = object
  33. b0: int
  34. case cond: bool
  35. of false: discard
  36. of true:
  37. b1: float
  38. var b = B(cond: false, b0: 3)
  39. doAssertRaises(FieldDefect): discard b.b1 # wrong discriminant
  40. doAssert ?.b.b1 == 0.0 # safe
  41. b = B(cond: true, b1: 4.5)
  42. doAssert ?.b.b1 == 4.5
  43. # lvalue semantics are preserved:
  44. if (let p = ?.b.b1.addr; p != nil): p[] = 4.7
  45. doAssert b.b1 == 4.7
  46. proc finalize(n: NimNode, lhs: NimNode, level: int): NimNode =
  47. if level == 0:
  48. result = quote: `lhs` = `n`
  49. else:
  50. result = quote: (let `lhs` = `n`)
  51. proc process(n: NimNode, lhs: NimNode, label: NimNode, level: int): NimNode =
  52. var n = n.copyNimTree
  53. var it = n
  54. let addr2 = bindSym"addr"
  55. var old: tuple[n: NimNode, index: int]
  56. while true:
  57. if it.len == 0:
  58. result = finalize(n, lhs, level)
  59. break
  60. elif it.kind == nnkCheckedFieldExpr:
  61. let dot = it[0]
  62. let obj = dot[0]
  63. let objRef = quote do: `addr2`(`obj`)
  64. # avoids a copy and preserves lvalue semantics, see tests
  65. let check = it[1]
  66. let okSet = check[1]
  67. let kind1 = check[2]
  68. let tmp = genSym(nskLet, "tmpCase")
  69. let body = process(objRef, tmp, label, level + 1)
  70. let tmp3 = nnkDerefExpr.newTree(tmp)
  71. it[0][0] = tmp3
  72. let dot2 = nnkDotExpr.newTree(@[tmp, dot[1]])
  73. if old.n != nil: old.n[old.index] = dot2
  74. else: n = dot2
  75. let assgn = finalize(n, lhs, level)
  76. result = quote do:
  77. `body`
  78. if `tmp3`.`kind1` notin `okSet`: break `label`
  79. `assgn`
  80. break
  81. elif it.kind in {nnkHiddenDeref, nnkDerefExpr}:
  82. let tmp = genSym(nskLet, "tmp")
  83. let body = process(it[0], tmp, label, level + 1)
  84. it[0] = tmp
  85. let assgn = finalize(n, lhs, level)
  86. result = quote do:
  87. `body`
  88. if `tmp` == nil: break `label`
  89. `assgn`
  90. break
  91. elif it.kind == nnkCall: # consider extending to `nnkCallKinds`
  92. # `copyNimTree` needed to avoid `typ = nil` issues
  93. old = (it, 1)
  94. it = it[1].copyNimTree
  95. else:
  96. old = (it, 0)
  97. it = it[0]
  98. macro `?.`*(a: typed): auto =
  99. ## Transforms `a` into an expression that can be safely evaluated even in
  100. ## presence of intermediate nil pointers/references, in which case a default
  101. ## value is produced.
  102. let lhs = genSym(nskVar, "lhs")
  103. let label = genSym(nskLabel, "label")
  104. let body = process(a, lhs, label, 0)
  105. result = quote do:
  106. var `lhs`: type(`a`)
  107. block `label`:
  108. `body`
  109. `lhs`
  110. # the code below is not needed for `?.`
  111. from options import Option, isSome, get, option, unsafeGet, UnpackDefect
  112. macro `??.`*(a: typed): Option =
  113. ## Same as `?.` but returns an `Option`.
  114. runnableExamples:
  115. import std/options
  116. type Foo = ref object
  117. x1: ref int
  118. x2: int
  119. # `?.` can't distinguish between a valid vs invalid default value, but `??.` can:
  120. var f1 = Foo(x1: int.new, x2: 2)
  121. doAssert (??.f1.x1[]).get == 0 # not enough to tell when the chain was valid.
  122. doAssert (??.f1.x1[]).isSome # a nil didn't occur in the chain
  123. doAssert (??.f1.x2).get == 2
  124. var f2: Foo
  125. doAssert not (??.f2.x1[]).isSome # f2 was nil
  126. doAssertRaises(UnpackDefect): discard (??.f2.x1[]).get
  127. doAssert ?.f2.x1[] == 0 # in contrast, this returns default(int)
  128. let lhs = genSym(nskVar, "lhs")
  129. let lhs2 = genSym(nskVar, "lhs")
  130. let label = genSym(nskLabel, "label")
  131. let body = process(a, lhs2, label, 0)
  132. result = quote do:
  133. var `lhs`: Option[type(`a`)]
  134. block `label`:
  135. var `lhs2`: type(`a`)
  136. `body`
  137. `lhs` = option(`lhs2`)
  138. `lhs`
  139. template fakeDot*(a: Option, b): untyped =
  140. ## See top-level example.
  141. let a1 = a # to avoid double evaluations
  142. type T = Option[typeof(unsafeGet(a1).b)]
  143. if isSome(a1):
  144. let a2 = unsafeGet(a1)
  145. when typeof(a2) is ref|ptr:
  146. if a2 == nil:
  147. default(T)
  148. else:
  149. option(a2.b)
  150. else:
  151. option(a2.b)
  152. else:
  153. # nil is "sticky"; this is needed, see tests
  154. default(T)
  155. # xxx this should but doesn't work: func `[]`*[T, I](a: Option[T], i: I): Option {.inline.} =
  156. func `[]`*[T, I](a: Option[T], i: I): auto {.inline.} =
  157. ## See top-level example.
  158. if isSome(a):
  159. # correctly will raise IndexDefect if a is valid but wraps an empty container
  160. result = option(a.unsafeGet[i])
  161. func `[]`*[U](a: Option[U]): auto {.inline.} =
  162. ## See top-level example.
  163. if isSome(a):
  164. let a2 = a.unsafeGet
  165. if a2 != nil:
  166. result = option(a2[])
  167. when false:
  168. # xxx: expose a way to do this directly in std/options, e.g.: `getAsIs`
  169. proc safeGet[T](a: Option[T]): T {.inline.} =
  170. get(a, default(T))