mgenast.nim 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. when defined(gcArc) or defined(gcOrc):
  27. prepareMutation(tst)
  28. writeData(ss, tst[0].addr, 2)
  29. discard readData(ss, tst[0].addr, 2)
  30. macro bindme6UseExposeFalse*(): untyped =
  31. ## with `kDirtyTemplate`, requires passing all referenced symbols
  32. ## which can be tedious
  33. genAstOpt({kDirtyTemplate}, newStringStream, writeData, readData):
  34. var tst = "sometext"
  35. var ss = newStringStream("anothertext")
  36. when defined(gcArc) or defined(gcOrc):
  37. prepareMutation(tst)
  38. writeData(ss, tst[0].addr, 2)
  39. discard readData(ss, tst[0].addr, 2)
  40. proc locafun1(): auto = "in locafun1"
  41. proc locafun2(): auto = "in locafun2"
  42. # locafun3 in caller scope only
  43. macro mixinExample*(): untyped =
  44. genAst:
  45. mixin locafun1
  46. (locafun1(), locafun2(), locafun3())