Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for fields defined in cases #4

Merged
merged 1 commit into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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