tarc_macro.nim 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import macros
  2. var destroyCalled = false
  3. macro bar() =
  4. let s = newTree(nnkAccQuoted, ident"=destroy")
  5. # let s = ident"`=destroy`" # this would not work
  6. result = quote do:
  7. type Foo = object
  8. # proc `=destroy`(a: var Foo) = destroyCalled = true # this would not work
  9. proc `s`(a: var Foo) = destroyCalled = true
  10. block:
  11. let a = Foo()
  12. bar()
  13. doAssert destroyCalled
  14. # custom `op`
  15. var destroyCalled2 = false
  16. macro bar(ident) =
  17. var x = 1.5
  18. result = quote("@") do:
  19. type Foo = object
  20. let `@ident` = 0 # custom op interpolated symbols need quoted (``)
  21. proc `=destroy`(a: var Foo) =
  22. doAssert @x == 1.5
  23. doAssert compiles(@x == 1.5)
  24. let b1 = @[1,2]
  25. let b2 = @@[1,2]
  26. doAssert $b1 == "[1, 2]"
  27. doAssert $b2 == "@[1, 2]"
  28. destroyCalled2 = true
  29. block:
  30. let a = Foo()
  31. bar(someident)
  32. doAssert destroyCalled2
  33. proc `&%`(x: int): int = 1
  34. proc `&%`(x, y: int): int = 2
  35. macro bar2() =
  36. var x = 3
  37. result = quote("&%") do:
  38. var y = &%x # quoting operator
  39. doAssert &%&%y == 1 # unary operator => need to escape
  40. doAssert y &% y == 2 # binary operator => no need to escape
  41. doAssert y == 3
  42. bar2()