Make asyncjs Future[void] play nicely with last line discardable calls

This commit is contained in:
Alexander Ivanov 2017-12-19 13:57:37 +02:00
commit 7f6afa9e9b
2 changed files with 36 additions and 5 deletions

View file

@ -83,20 +83,46 @@ proc replaceReturn(node: var NimNode) =
replaceReturn(son) replaceReturn(son)
inc z inc z
proc isFutureVoid(node: NimNode): bool =
result = node.kind == nnkBracketExpr and
node[0].kind == nnkIdent and $node[0] == "Future" and
node[1].kind == nnkIdent and $node[1] == "void"
proc generateJsasync(arg: NimNode): NimNode = proc generateJsasync(arg: NimNode): NimNode =
assert arg.kind == nnkProcDef assert arg.kind == nnkProcDef
result = arg result = arg
var isVoid = false
if arg.params[0].kind == nnkEmpty: if arg.params[0].kind == nnkEmpty:
result.params[0] = nnkBracketExpr.newTree(ident("Future"), ident("void")) result.params[0] = nnkBracketExpr.newTree(ident("Future"), ident("void"))
isVoid = true
elif isFutureVoid(arg.params[0]):
isVoid = true
var code = result.body var code = result.body
replaceReturn(code) replaceReturn(code)
result.body = nnkStmtList.newTree() result.body = nnkStmtList.newTree()
var q = quote:
var awaitFunction = quote:
proc await[T](f: Future[T]): T {.importcpp: "(await #)".} proc await[T](f: Future[T]): T {.importcpp: "(await #)".}
proc jsResolve[T](a: T): Future[T] {.importcpp: "#".} result.body.add(awaitFunction)
result.body.add(q)
var resolve: NimNode
var jsResolveNode = ident("jsResolve")
if isVoid:
resolve = quote:
var `jsResolveNode` {.importcpp: "undefined".}: Future[void]
else:
resolve = quote:
proc jsResolve[T](a: T): Future[T] {.importcpp: "#".}
result.body.add(resolve)
for child in code: for child in code:
result.body.add(child) result.body.add(child)
if isVoid:
var voidFix = quote:
return `jsResolveNode`
result.body.add(voidFix)
result.pragma = quote: result.pragma = quote:
{.codegenDecl: "async function $2($3)".} {.codegenDecl: "async function $2($3)".}

View file

@ -3,6 +3,7 @@ discard """
output: ''' output: '''
0 0
x x
e
''' '''
""" """
@ -12,15 +13,19 @@ import asyncjs
# for js # for js
proc y(e: int): Future[string] proc y(e: int): Future[string]
proc x(e: int) {.async.} = proc e: int {.discardable.} =
echo "e"
return 2
proc x(e: int): Future[void] {.async.} =
var s = await y(e) var s = await y(e)
echo s echo s
e()
proc y(e: int): Future[string] {.async.} = proc y(e: int): Future[string] {.async.} =
echo 0 echo 0
return "x" return "x"
discard x(2) discard x(2)