Skip to content

Commit

Permalink
Merge pull request #4 from recloser/cases
Browse files Browse the repository at this point in the history
add support for fields defined in cases
  • Loading branch information
zevv authored Jan 15, 2020
2 parents 2f95909 + c59cbb2 commit 2f57d0a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
27 changes: 26 additions & 1 deletion tests/tests.nim
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ type
Sub = object
foo: Foo

Cases = object
x: int
case cond: int8
of 1:
case secondCond: bool
of true:
y: int
of false:
z: string
w: int
of 2:
a: int
else:
b: float


suite "with":

test "basic object":
Expand Down Expand Up @@ -161,4 +177,13 @@ suite "with":
check field1 == 100
check field2 == "something"


test "fields in case":
var cases = Cases(cond: 1, secondCond: false, x: 123, z: "hello", w: 321)
with cases:
check secondCond == false
check x == 123
check z == "hello"
check w == 321
check compiles(y == 0)
check compiles(a == 0)
check compiles(b == 0.0)
9 changes: 8 additions & 1 deletion with.nim
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,21 @@

import macros

proc getAllIdentDefs(x: NimNode): seq[NimNode] =
for n in x:
if n.kind == nnkIdentDefs:
result &= n
elif n.kind in {nnkRecCase, nnkRecList, nnkOfBranch, nnkElse}:
result &= getAllIdentDefs(n)

proc createInner(x: NimNode): NimNode =
result = newStmtList()
var t = getTypeImpl(x)
if t.kind == nnkRefTy:
t = getTypeImpl(t[0])
assert(t.kind in {nnkObjectTy, nnkTupleTy}, "`with` must be called with " &
"either objects or tuples.")
for field in (if t.kind == nnkObjectTy: t[2] else: t):
for field in getAllIdentDefs(if t.kind == nnkObjectTy: t[2] else: t):
let name = newIdentNode($field[0])
if field[1].kind == nnkProcTy:
result.add quote do:
Expand Down

0 comments on commit 2f57d0a

Please sign in to comment.