twhen1.nim 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const Z = 0
  2. type
  3. Foo[T] = object
  4. when true:
  5. u: int
  6. else:
  7. v: int
  8. Foo1[T] = object
  9. when T is int:
  10. x: T
  11. elif true:
  12. z: char
  13. Foo2[x:static[int]] = object
  14. when (x and 1) == 1:
  15. x: array[x+1,int]
  16. else:
  17. x: array[x,int]
  18. Foo3 = Foo2[128]
  19. # #8417
  20. Foo4[A: static[int]] = object
  21. when Z == 0:
  22. discard
  23. else:
  24. discard
  25. block:
  26. var x: Foo[int] = Foo[int](u: 42)
  27. doAssert x.u == 42
  28. # Don't evaluate `when` branches before the type is instantiated
  29. block:
  30. var x: Foo1[bool] = Foo1[bool](z: 'o')
  31. doAssert x.z == 'o'
  32. block:
  33. var x: Foo2[3]
  34. doAssert x.x.len == 4
  35. block:
  36. var x: Foo2[4]
  37. doAssert x.x.len == 4
  38. block:
  39. var x: Foo3
  40. doAssert x.x.len == 128
  41. block:
  42. var x: Foo4[0]
  43. type
  44. MyObject = object
  45. x: int
  46. when (NimMajor, NimMinor) >= (1, 1):
  47. y: int
  48. discard MyObject(x: 100, y: 200)
  49. block: # Ensure when evaluates properly in objects
  50. type X[bits: static int] = object #22474
  51. when bits >= 256:
  52. data32: byte
  53. else:
  54. data16: byte
  55. static:
  56. discard X[255]().data16
  57. discard X[256]().data32
  58. type ComplexExprObject[S: static string, I: static int, Y: static auto] = object
  59. when 'h' in S and I < 10 and Y isnot float:
  60. a: int
  61. elif I > 30:
  62. b: int
  63. elif typeof(Y) is float:
  64. c: int
  65. else:
  66. d: int
  67. static:
  68. discard ComplexExprObject["hello", 9, 300i32]().a
  69. discard ComplexExprObject["", 40, 30f]().b
  70. discard ComplexExprObject["", 20, float 30]().c
  71. discard ComplexExprObject["", 20, ""]().d