tconst.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. discard """
  2. targets: "c cpp js"
  3. """
  4. import std/strutils
  5. template forceConst(a: untyped): untyped =
  6. ## Force evaluation at CT, but `static(a)` is simpler
  7. const ret = a
  8. ret
  9. proc isNimVm(): bool =
  10. when nimvm: result = true
  11. else: result = false
  12. block:
  13. doAssert forceConst(isNimVm())
  14. doAssert not isNimVm()
  15. doAssert forceConst(isNimVm()) == static(isNimVm())
  16. doAssert forceConst(isNimVm()) == isNimVm().static
  17. template main() =
  18. # xxx merge more const related tests here
  19. const ct = CompileTime
  20. # refs https://github.com/timotheecour/Nim/issues/718, apparently `CompileTime`
  21. # isn't cached, which seems surprising.
  22. block:
  23. const
  24. a = """
  25. Version $1|
  26. Compiled at: $2, $3
  27. """ % [NimVersion & spaces(44-len(NimVersion)), CompileDate, ct]
  28. let b = $a
  29. doAssert ct in b, $(b, ct)
  30. doAssert NimVersion in b
  31. block: # Test for fix on broken const unpacking
  32. template mytemp() =
  33. const
  34. (x, increment) = (4, true)
  35. a = 100
  36. discard (x, increment, a)
  37. mytemp()
  38. block: # bug #12334
  39. block:
  40. const b: cstring = "foo"
  41. var c = b
  42. doAssert c == "foo"
  43. block:
  44. const a = "foo"
  45. const b: cstring = a
  46. var c = b
  47. doAssert c == "foo"
  48. when not defined(js):
  49. block: # bug #19698
  50. type
  51. FormatInfo = object
  52. readproc: ReadProc
  53. writeproc: WriteProc
  54. ReadProc = proc (s: pointer)
  55. WriteProc = proc (s: pointer)
  56. func initFormatInfo(readproc: ReadProc, writeproc: WriteProc = nil): FormatInfo {.compileTime.} =
  57. result = FormatInfo(readproc: readproc, writeproc: nil)
  58. proc readSampleImage(s: pointer) = discard
  59. const SampleFormatInfo = initFormatInfo(readproc = readSampleImage)
  60. const KnownFormats = [SampleFormatInfo]
  61. func sortedFormatInfos(): array[len KnownFormats, FormatInfo] {.compileTime.} =
  62. result = default(array[len KnownFormats, FormatInfo])
  63. for i, info in KnownFormats:
  64. result[i] = info
  65. const SortedFormats = sortedFormatInfos()
  66. discard SortedFormats
  67. static: main()
  68. main()