tcast.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. discard """
  2. output: '''
  3. Hello World
  4. Hello World'''
  5. joinable: false
  6. """
  7. type MyProc = proc() {.cdecl.}
  8. type MyProc2 = proc() {.nimcall.}
  9. type MyProc3 = proc() #{.closure.} is implicit
  10. proc testProc() = echo "Hello World"
  11. template reject(x) = doAssert(not compiles(x))
  12. proc callPointer(p: pointer) =
  13. # can cast to proc(){.cdecl.}
  14. let ffunc0 = cast[MyProc](p)
  15. # can cast to proc(){.nimcall.}
  16. let ffunc1 = cast[MyProc2](p)
  17. # cannot cast to proc(){.closure.}
  18. reject: cast[MyProc3](p)
  19. ffunc0()
  20. ffunc1()
  21. callPointer(cast[pointer](testProc))
  22. reject: discard cast[enum](0)
  23. proc a = echo "hi"
  24. reject: discard cast[ptr](a)
  25. # bug #15623
  26. block:
  27. if false:
  28. let x = cast[ptr int](nil)
  29. echo x[]
  30. block:
  31. if false:
  32. var x: ref int = nil
  33. echo cast[ptr int](x)[]
  34. block:
  35. doAssert cast[int](cast[ptr int](nil)) == 0
  36. block:
  37. var x: ref int = nil
  38. doAssert cast[int](cast[ptr int](x)) == 0
  39. block: # cast of nil
  40. block:
  41. static:
  42. let a = cast[pointer](nil)
  43. doAssert a.repr == "nil"
  44. block:
  45. static:
  46. doAssert cast[ptr int](nil).repr == "nil"
  47. block:
  48. const str = cast[ptr int](nil)
  49. static:
  50. doAssert str.repr == "nil"
  51. block:
  52. static:
  53. doAssert cast[ptr int](nil).repr == "nil"
  54. block:
  55. static:
  56. doAssert cast[RootRef](nil).repr == "nil"
  57. when false: # xxx bug #15730, not fixed yet
  58. block:
  59. static:
  60. doAssert cast[cstring](nil).repr == "nil"
  61. template main() =
  62. # xxx move all under here to get tested in VM
  63. block: # cast of enum
  64. type Koo = enum k1, k2
  65. type Goo = enum g1, g2
  66. type Boo = enum b1 = -1, b2, b3, b4
  67. type Coo = enum c1 = -1i8, c2, c3, c4
  68. when nimvm:
  69. # xxx: Error: VM does not support 'cast' from tyEnum to tyEnum
  70. discard
  71. else:
  72. doAssert cast[Koo](k2) == k2
  73. doAssert cast[Goo](k2) == g2
  74. doAssert cast[Goo](k2.ord) == g2
  75. doAssert b3.ord == 1
  76. doAssert cast[Koo](b3) == k2
  77. doAssert cast[Boo](k2) == b3
  78. doAssert c3.ord == 1
  79. doAssert cast[Koo](c3) == k2
  80. doAssert cast[Coo](k2) == c3
  81. static: main()
  82. main()