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