timpl_ast.nim 2.3 KB

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