tgetimpl.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. discard """
  2. nimout: '''foo = "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. proc wrappedScope() =
  38. proc dummyproc() = discard
  39. doAssert isSameOwner(foo, dummyproc) == false
  40. doAssert isSameOwner(poo, dummyproc) == false
  41. wrappedScope()
  42. macro check_gen_proc(ex: typed): (bool, bool) =
  43. let lenChoice = bindsym"len"
  44. var is_equal = false
  45. var is_instance_of = false
  46. for child in lenChoice:
  47. if not is_equal:
  48. is_equal = ex[0] == child
  49. if not is_instance_of:
  50. is_instance_of = isInstantiationOf(ex[0], child)
  51. result = nnkTupleConstr.newTree(newLit(is_equal), newLit(is_instance_of))
  52. # check that len(seq[int]) is not equal to bindSym"len", but is instance of it
  53. let a = @[1,2,3]
  54. assert: check_gen_proc(len(a)) == (false, true)
  55. #---------------------------------------------------------------
  56. # issue #16110
  57. macro check(x: type): untyped =
  58. let z = getType(x)
  59. let y = getImpl(z[1])
  60. var sym = y[0]
  61. if sym.kind == nnkPragmaExpr: sym = sym[0]
  62. if sym.kind == nnkPostfix: sym = sym[1]
  63. expectKind(z[1], nnkSym)
  64. expectKind(sym, nnkSym)
  65. expectKind(y[2], nnkObjectTy)
  66. doAssert(sym == z[1])
  67. type
  68. TirePtr = ptr object
  69. code: int
  70. TireRef* = ref object
  71. code: int
  72. TireRef2* {.inheritable.} = ref object
  73. code: int
  74. TireRef3* {.inheritable.} = object
  75. code: int
  76. var z1: TirePtr
  77. check(typeof(z1[]))
  78. var z2: TireRef
  79. check(typeof(z2[]))
  80. var z3: TireRef2
  81. check(typeof(z3[]))
  82. check(TireRef3)