timpl_ast.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import std/macros
  2. import std/assertions
  3. block: # issue #16639
  4. type Foo[T] = object
  5. when true:
  6. x: float
  7. type Bar = object
  8. when true:
  9. x: float
  10. macro test() =
  11. let a = getImpl(bindSym"Foo")[^1]
  12. let b = getImpl(bindSym"Bar")[^1]
  13. doAssert treeRepr(a) == treeRepr(b)
  14. test()
  15. import strutils
  16. block: # issues #9899, ##14708
  17. macro implRepr(a: typed): string =
  18. result = newLit(repr(a.getImpl))
  19. type
  20. Option[T] = object
  21. when false: discard # issue #14708
  22. when false: x: int
  23. when T is (ref | ptr):
  24. val: T
  25. else:
  26. val: T
  27. has: bool
  28. static: # check information is retained
  29. let r = implRepr(Option)
  30. doAssert "when T is" in r
  31. doAssert r.count("val: T") == 2
  32. doAssert "has: bool" in r
  33. block: # try to compile the output
  34. macro parse(s: static string) =
  35. result = parseStmt(s)
  36. parse("type " & implRepr(Option))
  37. block: # issue #22639
  38. type
  39. Spectrum[N: static int] = object
  40. data: array[N, float]
  41. AngleInterpolator = object
  42. data: seq[Spectrum[60]]
  43. proc initInterpolator(num: int): AngleInterpolator =
  44. result = AngleInterpolator()
  45. for i in 0 ..< num:
  46. result.data.add Spectrum[60]()
  47. macro genCompatibleTuple(t: typed): untyped =
  48. let typ = t.getType[1].getTypeImpl[2]
  49. result = nnkTupleTy.newTree()
  50. for i, ch in typ: # is `nnkObjectTy`
  51. result.add nnkIdentDefs.newTree(ident(ch[0].strVal), # ch is `nnkIdentDefs`
  52. ch[1],
  53. newEmptyNode())
  54. proc fullSize[T: object | tuple](x: T): int =
  55. var tmp: genCompatibleTuple(T)
  56. result = 0
  57. for field, val in fieldPairs(x):
  58. result += sizeof(val)
  59. doAssert result == sizeof(tmp)
  60. let reflectivity = initInterpolator(1)
  61. for el in reflectivity.data:
  62. doAssert fullSize(el) == sizeof(el)
  63. doAssert fullSize(reflectivity.data[0]) == sizeof(reflectivity.data[0])
  64. doAssert genCompatibleTuple(Spectrum[60]) is tuple[data: array[60, float]]
  65. doAssert genCompatibleTuple(Spectrum[120]) is tuple[data: array[120, float]]
  66. type Foo[T] = object
  67. data: T
  68. doAssert genCompatibleTuple(Foo[int]) is tuple[data: int]
  69. doAssert genCompatibleTuple(Foo[float]) is tuple[data: float]