Source Edit

This module implements assertion handling.

Imports

ctypes, miscdollars

Procs

  1. proc failedAssertImpl(msg: string) {....raises: [], tags: [], forbids: [].}

Raises an AssertionDefect with msg, but this is hidden from the effect system. Called when an assertion failed. Source Edit

  1. proc raiseAssert(msg: string) {.noinline, noreturn, nosinks, ...raises: [],
  2. tags: [], forbids: [].}

Raises an AssertionDefect with msg. Source Edit

Templates

  1. template assert(cond: untyped; msg = "")

Raises AssertionDefect with msg if cond is false. Note that AssertionDefect is hidden from the effect system, so it doesn’t produce {.raises: [AssertionDefect].}. This exception is only supposed to be caught by unit testing frameworks.

No code will be generated for assert when passing -d:danger (implied by --assertions:off). See command line switches.

Example:

  1. assert 1 == 1

Example: cmd: —assertions:off

  1. assert 1 == 2 # no code generated, no failure here

Example: cmd: -d:danger

  1. assert 1 == 2 # ditto

Source Edit

  1. template doAssert(cond: untyped; msg = "")

Similar to assert but is always turned on regardless of --assertions.

Example:

  1. doAssert 1 == 1 # generates code even when built with `-d:danger` or `--assertions:off`

Source Edit

  1. template doAssertRaises(exception: typedesc; code: untyped)

Raises AssertionDefect if specified code does not raise exception.

Example:

  1. doAssertRaises(ValueError): raise newException(ValueError, "Hello World")
  2. doAssertRaises(CatchableError): raise newException(ValueError, "Hello World")
  3. doAssertRaises(AssertionDefect): doAssert false

Source Edit

  1. template onFailedAssert(msg, code: untyped): untyped {.dirty.}

Sets an assertion failure handler that will intercept any assert statements following onFailedAssert in the current scope.

Example:

  1. type MyError = object of CatchableError
  2. lineinfo: tuple[filename: string, line: int, column: int]
  3. # block-wide policy to change the failed assert exception type in order to
  4. # include a lineinfo
  5. onFailedAssert(msg):
  6. raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
  7. doAssertRaises(MyError): doAssert false

Source Edit