tstatictypes.nim 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. discard """
  2. nimout: '''
  3. staticAlialProc instantiated with 358
  4. staticAlialProc instantiated with 368
  5. '''
  6. output: '''
  7. 16
  8. 16
  9. b is 2 times a
  10. 17
  11. '''
  12. """
  13. import macros
  14. template ok(x) = assert(x)
  15. template no(x) = assert(not x)
  16. template accept(x) =
  17. static: assert(compiles(x))
  18. template reject(x) =
  19. static: assert(not compiles(x))
  20. proc plus(a, b: int): int = a + b
  21. template isStatic(x: static): bool = true
  22. template isStatic(x: auto): bool = false
  23. var v = 1
  24. when true:
  25. # test that `isStatic` works as expected
  26. const C = 2
  27. static:
  28. ok C.isStatic
  29. ok isStatic(plus(1, 2))
  30. ok plus(C, 2).isStatic
  31. no isStatic(v)
  32. no plus(1, v).isStatic
  33. when true:
  34. # test that proc instantiation works as expected
  35. type
  36. StaticTypeAlias = static[int]
  37. proc staticAliasProc(a: StaticTypeAlias,
  38. b: static[int],
  39. c: static int) =
  40. static:
  41. assert a.isStatic and b.isStatic and c.isStatic
  42. assert isStatic(a + plus(b, c))
  43. echo "staticAlialProc instantiated with ", a, b, c
  44. when b mod a == 0:
  45. echo "b is ", b div a, " times a"
  46. echo a + b + c
  47. staticAliasProc 1+2, 5, 8
  48. staticAliasProc 3, 2+3, 9-1
  49. staticAliasProc 3, 3+3, 4+4
  50. when true:
  51. # test static coercions. normal cases that should work:
  52. accept:
  53. var s1 = static[int] plus(1, 2)
  54. var s2 = static(plus(1,2))
  55. var s3 = static plus(1,2)
  56. var s4 = static[SomeInteger](1 + 2)
  57. # the sub-script operator can be used only with types:
  58. reject:
  59. var just_static3 = static[plus(1,2)]
  60. # static coercion takes into account the type:
  61. reject:
  62. var x = static[string](plus(1, 2))
  63. reject:
  64. var x = static[string] plus(1, 2)
  65. reject:
  66. var x = static[SomeFloat] plus(3, 4)
  67. # you cannot coerce a run-time variable
  68. reject:
  69. var x = static(v)
  70. when true:
  71. type
  72. ArrayWrapper1[S: static int] = object
  73. data: array[S + 1, int]
  74. ArrayWrapper2[S: static[int]] = object
  75. data: array[S.plus(2), int]
  76. ArrayWrapper3[S: static[(int, string)]] = object
  77. data: array[S[0], int]
  78. var aw1: ArrayWrapper1[5]
  79. var aw2: ArrayWrapper2[5]
  80. var aw3: ArrayWrapper3[(10, "str")]
  81. static:
  82. assert aw1.data.high == 5
  83. assert aw2.data.high == 6
  84. assert aw3.data.high == 9
  85. # #6077
  86. block:
  87. type
  88. Backend = enum
  89. Cpu
  90. Tensor[B: static[Backend]; T] = object
  91. BackProp[B: static[Backend],T] = proc (gradient: Tensor[B,T]): Tensor[B,T]