tgenericmacrotypes.nim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # issue #7974
  2. import macros
  3. macro genTypeA(arg: typed): untyped =
  4. if arg.typeKind != ntyTypeDesc:
  5. error("expected typedesc", arg)
  6. result = arg.getTypeInst[1]
  7. macro genTypeB(arg: typed): untyped =
  8. if arg.typeKind != ntyTypeDesc:
  9. error("expected typedesc", arg)
  10. let typeSym = arg.getTypeInst[1]
  11. result =
  12. nnkTupleTy.newTree(
  13. nnkIdentDefs.newTree(
  14. ident"a", typeSym, newEmptyNode()
  15. )
  16. )
  17. type
  18. # this is the trivial case, MyTypeA[T] is basically just T, nothing else. But it works.
  19. MyTypeA[T] = genTypeA(T)
  20. # in this case I generate `tuple[a: T]`. This this is something the compiler does not want
  21. MyTypeB[T] = genTypeB(T)
  22. # these are just alias types for int32 and float32, nothing really happens, but it works
  23. var a1: MyTypeA[int32]
  24. doAssert a1 is MyTypeA[int32]
  25. doAssert a1 is int32
  26. a1 = 0'i32
  27. var a2: MyTypeA[float32]
  28. doAssert a2 is MyTypeA[float32]
  29. doAssert a2 is float32
  30. a2 = 0'f32
  31. var a3: MyTypeA[float32]
  32. doAssert a3 is MyTypeA[float32]
  33. doAssert a3 is float32
  34. a3 = 0'f32
  35. var b1: MyTypeB[int32] # cannot generate VM code fur tuple[a: int32]
  36. doAssert b1 is MyTypeB[int32]
  37. doAssert b1 is tuple[a: int32]
  38. b1 = (a: 0'i32)
  39. var b2: MyTypeB[float32]
  40. doAssert b2 is MyTypeB[float32]
  41. doAssert b2 is tuple[a: float32]
  42. b2 = (a: 0'f32)
  43. var b3: MyTypeB[float32]
  44. doAssert b3 is MyTypeB[float32]
  45. doAssert b3 is tuple[a: float32]
  46. b3 = (a: 0'f32)