tgetimpl.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. discard """
  2. nimout: '''"muhaha"
  3. proc poo(x, y: int) =
  4. let y = x
  5. echo ["poo"]'''
  6. """
  7. import macros
  8. const
  9. foo = "muhaha"
  10. proc poo(x, y: int) =
  11. let y = x
  12. echo "poo"
  13. macro m(x: typed): untyped =
  14. echo repr x.getImpl
  15. m(foo)
  16. m(poo)
  17. #------------
  18. macro checkOwner(x: typed, check_id: static[int]): untyped =
  19. let sym = case check_id:
  20. of 0: x
  21. of 1: x.getImpl.body[0][0][0]
  22. of 2: x.getImpl.body[0][0][^1]
  23. of 3: x.getImpl.body[1][0]
  24. else: x
  25. result = newStrLitNode($sym.owner.symKind)
  26. macro isSameOwner(x, y: typed): untyped =
  27. result =
  28. if x.owner == y.owner: bindSym"true"
  29. else: bindSym"false"
  30. static:
  31. doAssert checkOwner(foo, 0) == "nskModule"
  32. doAssert checkOwner(poo, 0) == "nskModule"
  33. doAssert checkOwner(poo, 1) == "nskProc"
  34. doAssert checkOwner(poo, 2) == "nskProc"
  35. doAssert checkOwner(poo, 3) == "nskModule"
  36. doAssert isSameOwner(foo, poo)
  37. doAssert isSameOwner(foo, echo) == false
  38. doAssert isSameOwner(poo, len) == false
  39. #---------------------------------------------------------------
  40. macro check_gen_proc(ex: typed): (bool, bool) =
  41. let lenChoice = bindsym"len"
  42. var is_equal = false
  43. var is_instance_of = false
  44. for child in lenChoice:
  45. if not is_equal:
  46. is_equal = ex[0] == child
  47. if not is_instance_of:
  48. is_instance_of = isInstantiationOf(ex[0], child)
  49. result = nnkTupleConstr.newTree(newLit(is_equal), newLit(is_instance_of))
  50. # check that len(seq[int]) is not equal to bindSym"len", but is instance of it
  51. let a = @[1,2,3]
  52. assert: check_gen_proc(len(a)) == (false, true)
  53. #---------------------------------------------------------------
  54. # issue #16110
  55. macro check(x: type): untyped =
  56. let z = getType(x)
  57. let y = getImpl(z[1])
  58. let sym = if y[0].kind == nnkSym: y[0] else: y[0][0]
  59. expectKind(z[1], nnkSym)
  60. expectKind(sym, nnkSym)
  61. expectKind(y[2], nnkObjectTy)
  62. doAssert(sym == z[1])
  63. type
  64. TirePtr = ptr object
  65. code: int
  66. TireRef* = ref object
  67. code: int
  68. TireRef2* {.inheritable.} = ref object
  69. code: int
  70. TireRef3* {.inheritable.} = object
  71. code: int
  72. var z1: TirePtr
  73. check(typeof(z1[]))
  74. var z2: TireRef
  75. check(typeof(z2[]))
  76. var z3: TireRef2
  77. check(typeof(z3[]))
  78. check(TireRef3)