assertions.nim 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. ## This module provides various assertion utilities.
  2. ##
  3. ## **Note:** This module is reexported by `system` and thus does not need to be
  4. ## imported directly (with `system/assertions`).
  5. when not declared(sysFatal):
  6. include "system/fatal"
  7. import std/private/miscdollars
  8. # ---------------------------------------------------------------------------
  9. # helpers
  10. type InstantiationInfo = tuple[filename: string, line: int, column: int]
  11. proc `$`(info: InstantiationInfo): string =
  12. # The +1 is needed here
  13. # instead of overriding `$` (and changing its meaning), consider explicit name.
  14. result = ""
  15. result.toLocation(info.filename, info.line, info.column + 1)
  16. # ---------------------------------------------------------------------------
  17. when not defined(nimHasSinkInference):
  18. {.pragma: nosinks.}
  19. proc raiseAssert*(msg: string) {.noinline, noreturn, nosinks.} =
  20. ## Raises an `AssertionDefect` with `msg`.
  21. sysFatal(AssertionDefect, msg)
  22. proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =
  23. ## Raises an `AssertionDefect` with `msg`, but this is hidden
  24. ## from the effect system. Called when an assertion failed.
  25. # trick the compiler to not list `AssertionDefect` when called
  26. # by `assert`.
  27. # xxx simplify this pending bootstrap >= 1.4.0, after which cast not needed
  28. # anymore since `Defect` can't be raised.
  29. type Hide = proc (msg: string) {.noinline, raises: [], noSideEffect, tags: [].}
  30. cast[Hide](raiseAssert)(msg)
  31. template assertImpl(cond: bool, msg: string, expr: string, enabled: static[bool]) =
  32. when enabled:
  33. const
  34. loc = instantiationInfo(fullPaths = compileOption("excessiveStackTrace"))
  35. ploc = $loc
  36. bind instantiationInfo
  37. mixin failedAssertImpl
  38. {.line: loc.}:
  39. if not cond:
  40. failedAssertImpl(ploc & " `" & expr & "` " & msg)
  41. template assert*(cond: untyped, msg = "") =
  42. ## Raises `AssertionDefect` with `msg` if `cond` is false. Note
  43. ## that `AssertionDefect` is hidden from the effect system, so it doesn't
  44. ## produce `{.raises: [AssertionDefect].}`. This exception is only supposed
  45. ## to be caught by unit testing frameworks.
  46. ##
  47. ## No code will be generated for `assert` when passing `-d:danger` (implied by `--assertions:off`).
  48. ## See `command line switches <nimc.html#compiler-usage-commandminusline-switches>`_.
  49. runnableExamples: assert 1 == 1
  50. runnableExamples("--assertions:off"):
  51. assert 1 == 2 # no code generated, no failure here
  52. runnableExamples("-d:danger"): assert 1 == 2 # ditto
  53. assertImpl(cond, msg, astToStr(cond), compileOption("assertions"))
  54. template doAssert*(cond: untyped, msg = "") =
  55. ## Similar to `assert <#assert.t,untyped,string>`_ but is always turned on regardless of `--assertions`.
  56. runnableExamples:
  57. doAssert 1 == 1 # generates code even when built with `-d:danger` or `--assertions:off`
  58. assertImpl(cond, msg, astToStr(cond), true)
  59. template onFailedAssert*(msg, code: untyped): untyped {.dirty.} =
  60. ## Sets an assertion failure handler that will intercept any assert
  61. ## statements following `onFailedAssert` in the current scope.
  62. runnableExamples:
  63. type MyError = object of CatchableError
  64. lineinfo: tuple[filename: string, line: int, column: int]
  65. # block-wide policy to change the failed assert exception type in order to
  66. # include a lineinfo
  67. onFailedAssert(msg):
  68. raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
  69. doAssertRaises(MyError): doAssert false
  70. template failedAssertImpl(msgIMPL: string): untyped {.dirty.} =
  71. let msg = msgIMPL
  72. code
  73. template doAssertRaises*(exception: typedesc, code: untyped) =
  74. ## Raises `AssertionDefect` if specified `code` does not raise `exception`.
  75. runnableExamples:
  76. doAssertRaises(ValueError): raise newException(ValueError, "Hello World")
  77. doAssertRaises(CatchableError): raise newException(ValueError, "Hello World")
  78. doAssertRaises(AssertionDefect): doAssert false
  79. var wrong = false
  80. const begin = "expected raising '" & astToStr(exception) & "', instead"
  81. const msgEnd = " by: " & astToStr(code)
  82. template raisedForeign = raiseAssert(begin & " raised foreign exception" & msgEnd)
  83. when Exception is exception:
  84. try:
  85. if true:
  86. code
  87. wrong = true
  88. except Exception as e: discard
  89. except: raisedForeign()
  90. else:
  91. try:
  92. if true:
  93. code
  94. wrong = true
  95. except exception:
  96. discard
  97. except Exception as e:
  98. mixin `$` # alternatively, we could define $cstring in this module
  99. raiseAssert(begin & " raised '" & $e.name & "'" & msgEnd)
  100. except: raisedForeign()
  101. if wrong:
  102. raiseAssert(begin & " nothing was raised" & msgEnd)