tgensymgeneric.nim 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. discard """
  2. output: '''true'''
  3. """
  4. # We need to open the gensym'ed symbol again so that the instantiation
  5. # creates a fresh copy; but this is wrong the very first reason for gensym
  6. # is that scope rules cannot be used! So simply removing 'sfGenSym' does
  7. # not work. Copying the symbol does not work either because we're already
  8. # the owner of the symbol! What we need to do is to copy the symbol
  9. # in the generic instantiation process...
  10. type
  11. TA = object
  12. x: int
  13. TB = object
  14. x: string
  15. template genImpl() =
  16. var gensymed: T
  17. when T is TB:
  18. gensymed.x = "abc"
  19. else:
  20. gensymed.x = 123
  21. result = move gensymed
  22. proc gen[T](x: T): T =
  23. genImpl()
  24. var
  25. a: TA
  26. b: TB
  27. let x = gen(a)
  28. let y = gen(b)
  29. doAssert x.x == 123
  30. doAssert y.x == "abc"
  31. # test symbol equality
  32. import macros
  33. static:
  34. let sym1 = genSym()
  35. let sym2 = genSym()
  36. let sym3 = sym1
  37. let nimsym = sym1.symbol
  38. doAssert sym1 == sym1
  39. doAssert sym2 != sym3
  40. doAssert sym2.symbol != sym3.symbol
  41. doAssert sym3 == sym1
  42. doAssert sym1.symbol == sym1.symbol
  43. doAssert nimsym == nimsym
  44. echo "true"