ttypeinfo.nim 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import std/typeinfo
  2. import std/assertions
  3. type
  4. TE = enum
  5. blah, blah2
  6. TestObj = object
  7. test, asd: int
  8. case test2: TE
  9. of blah:
  10. help: string
  11. else:
  12. nil
  13. var test = @[0,1,2,3,4]
  14. var x = toAny(test)
  15. var y = 78
  16. x[4] = toAny(y)
  17. doAssert x[2].getInt == 2
  18. var test2: tuple[name: string, s: int] = ("test", 56)
  19. var x2 = toAny(test2)
  20. var i = 0
  21. for n, a in fields(x2):
  22. case i
  23. of 0: doAssert n == "Field0" and $a.kind == "akString"
  24. of 1: doAssert n == "Field1" and $a.kind == "akInt"
  25. else: doAssert false
  26. inc i
  27. var test3: TestObj
  28. test3.test = 42
  29. test3 = TestObj(test2: blah2)
  30. var x3 = toAny(test3)
  31. i = 0
  32. for n, a in fields(x3):
  33. case i
  34. of 0: doAssert n == "test" and $a.kind == "akInt"
  35. of 1: doAssert n == "asd" and $a.kind == "akInt"
  36. of 2: doAssert n == "test2" and $a.kind == "akEnum"
  37. else: doAssert false
  38. inc i
  39. var test4: ref string
  40. new(test4)
  41. test4[] = "test"
  42. var x4 = toAny(test4)
  43. doAssert($x4[].kind() == "akString")
  44. block:
  45. # gimme a new scope dammit
  46. var myArr: array[0..4, array[0..4, string]] = [
  47. ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
  48. ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
  49. ["test", "1", "2", "3", "4"]]
  50. var m = toAny(myArr)
  51. for i in 0 .. m.len-1:
  52. for j in 0 .. m[i].len-1:
  53. doAssert getString(m[i][j]) == myArr[i][j]
  54. block:
  55. type
  56. Test = enum
  57. Hello, he_llo
  58. var x = hello
  59. var y = x.toAny
  60. doAssert getEnumOrdinal(y, "Hello") == 0
  61. doAssert getEnumOrdinal(y, "hello") == 1