assertions.nim 4.7 KB

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