fork download
  1. import macros
  2.  
  3. macro mkmac(a, b, c: untyped): untyped =
  4. result = newStmtList()
  5. result.add quote do:
  6. `a` * (`b` + `c`)
  7.  
  8. macro mkmacro(fn: static[string]): untyped =
  9. result = newStmtList()
  10.  
  11. var body = newStmtList()
  12. body.add("write".newCall("stdout".ident, "TEST\n".newStrLitNode))
  13.  
  14. var bra = nnkBracket.newTree
  15. bra.add(3.newIntLitNode)
  16. bra.add(7.newIntLitNode)
  17. bra.add(1.newIntLitNode)
  18. let seq = bra.prefix("@")
  19. let seqLit = @[3, 7, 1].newLit
  20. body.add("echo".newCall(nnkInFix.newTree("==".ident, seq, seqLit)))
  21.  
  22. let ast: NimNode = getAst mkmac("x".ident, "y".ident, "z".ident)
  23. body.add(newAssignment("result".ident, ast))
  24.  
  25. result.add(newProc(fn.ident.postfix("*"),
  26. ["int".ident,
  27. newIdentDefs("x".ident, "int".ident),
  28. newIdentDefs("y".ident, "int".ident),
  29. newIdentDefs("z".ident, "int".ident)],
  30. body, nnkProcDef, newEmptyNode()))
  31.  
  32. let hoge: int = 3
  33. mkmacro "fuga"
  34. echo hoge.fuga(4, 1)
  35.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.nim(25, 21) Error: type mismatch: got <NimNode, array[0..3, NimNode], NimNode, NimNodeKind, NimNode>
but expected one of: 
proc newProc(name = newEmptyNode(); params: openArray[NimNode] = [newEmptyNode()];
            body: NimNode = newStmtList(); procType = nnkProcDef): NimNode

expression: newProc(postfix(ident(fn), "*"), [ident("int"), newIdentDefs(ident("x"),
    ident("int"), newEmptyNode()), newIdentDefs(ident("y"), ident("int"),
    newEmptyNode()), newIdentDefs(ident("z"), ident("int"), newEmptyNode())], body,
        nnkProcDef, newEmptyNode())
stdout
Standard output is empty