assertions.nim 4.4 KB

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