File: tgensym.nim

package info (click to toggle)
nim 0.19.4-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 462,356 kB
  • sloc: sh: 11,089; ansic: 4,699; makefile: 706; python: 309; sql: 297; asm: 141; xml: 13
file content (65 lines) | stat: -rw-r--r-- 2,270 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import nativesockets, asyncdispatch, macros
var p = newDispatcher()
var sock = newAsyncNativeSocket()

proc convertReturns(node, retFutureSym: NimNode): NimNode {.compileTime.} =
  case node.kind
  of nnkReturnStmt:
    result = newCall(newIdentNode("complete"), retFutureSym, node[0])
  else:
    result = node
    for i in 0 .. <node.len:
      result[i] = convertReturns(node[i], retFutureSym)

macro async2(prc: untyped): untyped =
  expectKind(prc, nnkProcDef)

  var outerProcBody = newNimNode(nnkStmtList)

  # -> var retFuture = newFuture[T]()
  var retFutureSym = newIdentNode("retFuture") #genSym(nskVar, "retFuture")
  outerProcBody.add(
    newVarStmt(retFutureSym,
      newCall(
        newNimNode(nnkBracketExpr).add(
          newIdentNode("newFuture"),
          prc[3][0][1])))) # Get type from return type of this proc.

  # -> iterator nameIter(): FutureBase {.closure.} = <proc_body>
  # Changing this line to: newIdentNode($prc[0].ident & "Iter") # will make it work.
  var iteratorNameSym = genSym(nskIterator, $prc[0].ident & "Iter")
  assert iteratorNameSym.symKind == nskIterator
  #var iteratorNameSym = newIdentNode($prc[0].ident & "Iter")
  var procBody = prc[6].convertReturns(retFutureSym)

  var closureIterator = newProc(iteratorNameSym, [newIdentNode("FutureBase")],
                                procBody, nnkIteratorDef)
  closureIterator[4] = newNimNode(nnkPragma).add(newIdentNode("closure"))
  outerProcBody.add(closureIterator)

  # -> var nameIterVar = nameIter
  # -> var first = nameIterVar()
  var varNameIterSym = newIdentNode($prc[0].ident & "IterVar") #genSym(nskVar, $prc[0].ident & "IterVar")
  var varNameIter = newVarStmt(varNameIterSym, iteratorNameSym)
  outerProcBody.add varNameIter
  var varFirstSym = genSym(nskVar, "first")
  assert varFirstSym.symKind ==  nskVar
  var varFirst = newVarStmt(varFirstSym, newCall(varNameIterSym))
  outerProcBody.add varFirst


  result = prc

  # Remove the 'closure' pragma.
  for i in 0 .. <result[4].len:
    if result[4][i].ident == !"async":
      result[4].del(i)

  result[6] = outerProcBody

proc readStuff(): Future[string] {.async2.} =
  var fut = connect(sock, "irc.freenode.org", Port(6667))
  yield fut
  var fut2 = recv(sock, 50)
  yield fut2
  return fut2.read