assertions.nim 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. when defined(nimQuirky):
  27. quit "[AssertionError] " & msg
  28. else:
  29. raise newException(AssertionDefect, msg)
  30. else:
  31. sysFatal(AssertionDefect, msg)
  32. proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =
  33. ## Raises an `AssertionDefect` with `msg`, but this is hidden
  34. ## from the effect system. Called when an assertion failed.
  35. raiseAssert(msg)
  36. template assertImpl(cond: bool, msg: string, expr: string, enabled: static[bool]) =
  37. when enabled:
  38. const
  39. loc = instantiationInfo(fullPaths = compileOption("excessiveStackTrace"))
  40. ploc = $loc
  41. bind instantiationInfo
  42. mixin failedAssertImpl
  43. {.line: loc.}:
  44. if not cond:
  45. failedAssertImpl(ploc & " `" & expr & "` " & msg)
  46. template assert*(cond: untyped, msg = "") =
  47. ## Raises `AssertionDefect` with `msg` if `cond` is false. Note
  48. ## that `AssertionDefect` is hidden from the effect system, so it doesn't
  49. ## produce `{.raises: [AssertionDefect].}`. This exception is only supposed
  50. ## to be caught by unit testing frameworks.
  51. ##
  52. ## No code will be generated for `assert` when passing `-d:danger` (implied by `--assertions:off`).
  53. ## See `command line switches <nimc.html#compiler-usage-commandminusline-switches>`_.
  54. runnableExamples: assert 1 == 1
  55. runnableExamples("--assertions:off"):
  56. assert 1 == 2 # no code generated, no failure here
  57. runnableExamples("-d:danger"): assert 1 == 2 # ditto
  58. assertImpl(cond, msg, astToStr(cond), compileOption("assertions"))
  59. template doAssert*(cond: untyped, msg = "") =
  60. ## Similar to `assert <#assert.t,untyped,string>`_ but is always turned on regardless of `--assertions`.
  61. runnableExamples:
  62. doAssert 1 == 1 # generates code even when built with `-d:danger` or `--assertions:off`
  63. assertImpl(cond, msg, astToStr(cond), true)
  64. template onFailedAssert*(msg, code: untyped): untyped {.dirty.} =
  65. ## Sets an assertion failure handler that will intercept any assert
  66. ## statements following `onFailedAssert` in the current scope.
  67. runnableExamples:
  68. type MyError = object of CatchableError
  69. lineinfo: tuple[filename: string, line: int, column: int]
  70. # block-wide policy to change the failed assert exception type in order to
  71. # include a lineinfo
  72. onFailedAssert(msg):
  73. raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
  74. doAssertRaises(MyError): doAssert false
  75. when not defined(nimHasTemplateRedefinitionPragma):
  76. {.pragma: redefine.}
  77. template failedAssertImpl(msgIMPL: string): untyped {.dirty, redefine.} =
  78. let msg = msgIMPL
  79. code
  80. template doAssertRaises*(exception: typedesc, code: untyped) =
  81. ## Raises `AssertionDefect` if specified `code` does not raise `exception`.
  82. runnableExamples:
  83. doAssertRaises(ValueError): raise newException(ValueError, "Hello World")
  84. doAssertRaises(CatchableError): raise newException(ValueError, "Hello World")
  85. doAssertRaises(AssertionDefect): doAssert false
  86. var wrong = false
  87. const begin = "expected raising '" & astToStr(exception) & "', instead"
  88. const msgEnd = " by: " & astToStr(code)
  89. template raisedForeign {.gensym.} = raiseAssert(begin & " raised foreign exception" & msgEnd)
  90. {.push warning[BareExcept]:off.}
  91. when Exception is exception:
  92. try:
  93. if true:
  94. code
  95. wrong = true
  96. except Exception as e: discard
  97. except: raisedForeign()
  98. else:
  99. try:
  100. if true:
  101. code
  102. wrong = true
  103. except exception:
  104. discard
  105. except Exception as e:
  106. mixin `$` # alternatively, we could define $cstring in this module
  107. raiseAssert(begin & " raised '" & $e.name & "'" & msgEnd)
  108. except: raisedForeign()
  109. {.pop.}
  110. if wrong:
  111. raiseAssert(begin & " nothing was raised" & msgEnd)