taliassyntax.nim 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. type Foo = object
  2. bar: int
  3. var foo = Foo(bar: 10)
  4. template bar: int = foo.bar
  5. doAssert bar == 10
  6. bar = 15
  7. doAssert bar == 15
  8. var foo2 = Foo(bar: -10)
  9. doAssert bar == 15
  10. # works in generics
  11. proc genericProc[T](x: T): string =
  12. $(x, bar)
  13. doAssert genericProc(true) == "(true, 15)"
  14. # redefine
  15. template bar: int {.redefine.} = foo2.bar
  16. doAssert bar == -10
  17. block: # subscript
  18. var bazVal = @[1, 2, 3]
  19. template baz: seq[int] = bazVal
  20. doAssert baz[1] == 2
  21. proc genericProc2[T](x: T): string =
  22. result = $(x, baz[1])
  23. baz[1] = 7
  24. doAssert genericProc2(true) == "(true, 2)"
  25. doAssert baz[1] == 7
  26. baz[1] = 14
  27. doAssert baz[1] == 14
  28. block: # type alias
  29. template Int2: untyped = int
  30. let x: Int2 = 123
  31. proc generic[T](): string =
  32. template U: untyped = T
  33. var x: U
  34. result = $typeof(x)
  35. doAssert result == $U
  36. doAssert result == $T
  37. doAssert generic[int]() == "int"
  38. doAssert generic[Int2]() == "int"
  39. doAssert generic[string]() == "string"
  40. doAssert generic[seq[int]]() == "seq[int]"
  41. doAssert generic[seq[Int2]]() == "seq[int]"
  42. discard generic[123]()
  43. proc genericStatic[X; T: static[X]](): string =
  44. template U: untyped = T
  45. result = $U
  46. doAssert result == $T
  47. doAssert genericStatic[int, 123]() == "123"
  48. doAssert genericStatic[Int2, 123]() == "123"
  49. doAssert genericStatic[(string, bool), ("a", true)]() == "(\"a\", true)"
  50. block: # issue #13515
  51. template test: bool = true
  52. # compiles:
  53. if not test:
  54. doAssert false
  55. # does not compile:
  56. template x =
  57. if not test:
  58. doAssert false
  59. x
  60. import macros
  61. block: # issue #21727
  62. template debugAnnotation(s: typed): string =
  63. astToStr s
  64. macro cpsJump(x: int): untyped =
  65. result = newLit(debugAnnotation(cpsJump))
  66. doAssert cpsJump(13) == "cpsJump"