File: tmacro5.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 (59 lines) | stat: -rw-r--r-- 1,542 bytes parent folder | download
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
import macros,json

var decls{.compileTime.}: seq[NimNode] = @[]
var impls{.compileTime.}: seq[NimNode] = @[]

macro importImpl_forward(name, returns: untyped): untyped =
  result = newNimNode(nnkEmpty)
  var func_name = newNimNode(nnkAccQuoted)
  func_name.add newIdentNode("import")
  func_name.add name

  var res = newNimNode(nnkProcDef)
  res.add newNimNode(nnkPostfix)
  res[0].add newIdentNode("*")
  res[0].add func_name
  res.add newNimNode(nnkEmpty)
  res.add newNimNode(nnkEmpty)
  res.add newNimNode(nnkFormalParams)
  res[3].add returns
  var p1 = newNimNode(nnkIdentDefs)
  p1.add newIdentNode("dat")
  p1.add newIdentNOde("JsonNode")
  p1.add newNimNode(nnkEmpty)
  res[3].add p1
  var p2 = newNimNode(nnkIdentDefs)
  p2.add newIdentNode("errors")
  p2.add newNimNode(nnkVarTy)
  p2.add newNimNode(nnkEmpty)
  p2[1].add newNimNode(nnkBracketExpr)
  p2[1][0].add newIdentNode("seq")
  p2[1][0].add newIdentNode("string")
  res[3].add p2

  res.add newNimNode(nnkEmpty)
  res.add newNimNode(nnkEmpty)
  res.add newNimNode(nnkEmpty)

  decls.add res
  echo(repr(res))

macro importImpl(name, returns, body: untyped): typed =
  #var res = getAST(importImpl_forward(name, returns))
  discard getAST(importImpl_forward(name, returns))
  var res = copyNimTree(decls[decls.high])
  res[6] = body
  echo repr(res)
  impls.add res

macro okayy: typed =
  result = newNimNode(nnkStmtList)
  for node in decls: result.add node
  for node in impls: result.add node

importImpl(Item, int):
  echo 42
importImpl(Foo, int16):
  echo 77

okayy