assertions.nim 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2022 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. when not defined(nimPreviewSlimSystem) and not declared(sysFatal):
  10. include "system/rawquits"
  11. include "system/fatal"
  12. ## This module implements assertion handling.
  13. import std/private/miscdollars
  14. # ---------------------------------------------------------------------------
  15. # helpers
  16. type InstantiationInfo = tuple[filename: string, line: int, column: int]
  17. proc `$`(info: InstantiationInfo): string =
  18. # The +1 is needed here
  19. # instead of overriding `$` (and changing its meaning), consider explicit name.
  20. result = ""
  21. result.toLocation(info.filename, info.line, info.column + 1)
  22. # ---------------------------------------------------------------------------
  23. proc raiseAssert*(msg: string) {.noinline, noreturn, nosinks.} =
  24. ## Raises an `AssertionDefect` with `msg`.
  25. when defined(nimPreviewSlimSystem):
  26. raise newException(AssertionDefect, msg)
  27. else:
  28. sysFatal(AssertionDefect, msg)
  29. proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =
  30. ## Raises an `AssertionDefect` with `msg`, but this is hidden
  31. ## from the effect system. Called when an assertion failed.
  32. raiseAssert(msg)
  33. template assertImpl(cond: bool, msg: string, expr: string, enabled: static[bool]) =
  34. when enabled:
  35. const
  36. loc = instantiationInfo(fullPaths = compileOption("excessiveStackTrace"))
  37. ploc = $loc
  38. bind instantiationInfo
  39. mixin failedAssertImpl
  40. {.line: loc.}:
  41. if not cond:
  42. failedAssertImpl(ploc & " `" & expr & "` " & msg)
  43. template assert*(cond: untyped, msg = "") =
  44. ## Raises `AssertionDefect` with `msg` if `cond` is false. Note
  45. ## that `AssertionDefect` is hidden from the effect system, so it doesn't
  46. ## produce `{.raises: [AssertionDefect].}`. This exception is only supposed
  47. ## to be caught by unit testing frameworks.
  48. ##
  49. ## No code will be generated for `assert` when passing `-d:danger` (implied by `--assertions:off`).
  50. ## See `command line switches <nimc.html#compiler-usage-commandminusline-switches>`_.
  51. runnableExamples: assert 1 == 1
  52. runnableExamples("--assertions:off"):
  53. assert 1 == 2 # no code generated, no failure here
  54. runnableExamples("-d:danger"): assert 1 == 2 # ditto
  55. assertImpl(cond, msg, astToStr(cond), compileOption("assertions"))
  56. template doAssert*(cond: untyped, msg = "") =
  57. ## Similar to `assert <#assert.t,untyped,string>`_ but is always turned on regardless of `--assertions`.
  58. runnableExamples:
  59. doAssert 1 == 1 # generates code even when built with `-d:danger` or `--assertions:off`
  60. assertImpl(cond, msg, astToStr(cond), true)
  61. template onFailedAssert*(msg, code: untyped): untyped {.dirty.} =
  62. ## Sets an assertion failure handler that will intercept any assert
  63. ## statements following `onFailedAssert` in the current scope.
  64. runnableExamples:
  65. type MyError = object of CatchableError
  66. lineinfo: tuple[filename: string, line: int, column: int]
  67. # block-wide policy to change the failed assert exception type in order to
  68. # include a lineinfo
  69. onFailedAssert(msg):
  70. raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
  71. doAssertRaises(MyError): doAssert false
  72. when not defined(nimHasTemplateRedefinitionPragma):
  73. {.pragma: redefine.}
  74. template failedAssertImpl(msgIMPL: string): untyped {.dirty, redefine.} =
  75. let msg = msgIMPL
  76. code
  77. template doAssertRaises*(exception: typedesc, code: untyped) =
  78. ## Raises `AssertionDefect` if specified `code` does not raise `exception`.
  79. runnableExamples:
  80. doAssertRaises(ValueError): raise newException(ValueError, "Hello World")
  81. doAssertRaises(CatchableError): raise newException(ValueError, "Hello World")
  82. doAssertRaises(AssertionDefect): doAssert false
  83. var wrong = false
  84. const begin = "expected raising '" & astToStr(exception) & "', instead"
  85. const msgEnd = " by: " & astToStr(code)
  86. template raisedForeign {.gensym.} = raiseAssert(begin & " raised foreign exception" & msgEnd)
  87. {.push warning[BareExcept]:off.}
  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:
  103. mixin `$` # alternatively, we could define $cstring in this module
  104. raiseAssert(begin & " raised '" & $e.name & "'" & msgEnd)
  105. except: raisedForeign()
  106. {.pop.}
  107. if wrong:
  108. raiseAssert(begin & " nothing was raised" & msgEnd)