Skip to content

Commit

Permalink
Implemented blocks calling. Closes #34.
Browse files Browse the repository at this point in the history
  • Loading branch information
yglukhov committed Oct 10, 2024
1 parent 21c812e commit 445fcb0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
26 changes: 26 additions & 0 deletions darwin/objc/blocks.nim
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,29 @@ macro convertToClosure(v: typed): untyped =
proc toBlock*[T: proc](v: T): auto =
## Returns Block[T {.closure.}]
convertToClosure(v)

proc getInvokeType(procType: NimNode): NimNode =
result = copyNimTree(procType)
let pragmas = result[1]

var i = 0
while i < pragmas.len:
if pragmas[i].kind in {nnkSym, nnkIdent} and $pragmas[i] == "closure":
pragmas.del(i)
else:
inc i

pragmas.add(ident"cdecl")

result.params.insert(1, newIdentDefs(ident"<theblock>", ident"pointer"))

macro invokeAux(b: untyped, procType: typedesc, f: pointer, args: untyped): untyped =
let procT = getTypeImpl(procType)[1]
# echo treeRepr procT
result = newCall(newTree(nnkCast, getInvokeType(procT), f), b)
for s in args:
result.add(s)
# echo "invokeAux: ", repr result

template call*[T](b: Block[T], args: varargs[untyped]): untyped =
invokeAux(b, T, cast[ptr BlockLiteral[T]](b).invoke, (args))
10 changes: 10 additions & 0 deletions tests/tarrays.nim
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,13 @@ proc test() =
doAssert(elems == @["hello", "bye"])

test()

proc testBlock() =
var v = 5
let bl = toBlock() do(a: int):
echo "Block called"
v = v + a
bl.call(123)
doAssert(v == 127)

testBlock()

0 comments on commit 445fcb0

Please sign in to comment.