tcast.nim 2.2 KB

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