mgenast.nim 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import std/genasts
  2. import std/macros
  3. # Using a enum instead of, say, int, to make apparent potential bugs related to
  4. # forgetting converting to NimNode via newLit, see bug #9607
  5. type Foo* = enum kfoo0, kfoo1, kfoo2, kfoo3, kfoo4
  6. proc myLocalPriv(): auto = kfoo1
  7. proc myLocalPriv2(): auto = kfoo1
  8. macro bindme2*(): untyped =
  9. genAst: myLocalPriv()
  10. macro bindme3*(): untyped =
  11. ## myLocalPriv must be captured explicitly
  12. genAstOpt({kDirtyTemplate}, myLocalPriv): myLocalPriv()
  13. macro bindme4*(): untyped =
  14. ## calling this won't compile because `myLocalPriv` isn't captured
  15. genAstOpt({kDirtyTemplate}): myLocalPriv()
  16. macro bindme5UseExpose*(): untyped =
  17. genAst: myLocalPriv2()
  18. macro bindme5UseExposeFalse*(): untyped =
  19. genAstOpt({kDirtyTemplate}): myLocalPriv2()
  20. # example from bug #7889
  21. from std/streams import newStringStream, readData, writeData
  22. macro bindme6UseExpose*(): untyped =
  23. genAst:
  24. var tst = "sometext"
  25. var ss = newStringStream("anothertext")
  26. writeData(ss, tst[0].addr, 2)
  27. discard readData(ss, tst[0].addr, 2)
  28. macro bindme6UseExposeFalse*(): untyped =
  29. ## with `kDirtyTemplate`, requires passing all referenced symbols
  30. ## which can be tedious
  31. genAstOpt({kDirtyTemplate}, newStringStream, writeData, readData):
  32. var tst = "sometext"
  33. var ss = newStringStream("anothertext")
  34. writeData(ss, tst[0].addr, 2)
  35. discard readData(ss, tst[0].addr, 2)
  36. proc locafun1(): auto = "in locafun1"
  37. proc locafun2(): auto = "in locafun2"
  38. # locafun3 in caller scope only
  39. macro mixinExample*(): untyped =
  40. genAst:
  41. mixin locafun1
  42. (locafun1(), locafun2(), locafun3())