summary refs log tree commit diff stats
path: root/lib/std/assertions.nim
blob: 0bc4653f21d7a8300d6cc446b06e3b43c3f2281c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#
#
#            Nim's Runtime Library
#        (c) Copyright 2022 Nim contributors
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This module implements assertion handling.

when not declared(sysFatal):
  include "system/fatal"

import std/private/miscdollars
# ---------------------------------------------------------------------------
# helpers

type InstantiationInfo = tuple[filename: string, line: int, column: int]

proc `$`(info: InstantiationInfo): string =
  # The +1 is needed here
  # instead of overriding `$` (and changing its meaning), consider explicit name.
  result = ""
  result.toLocation(info.filename, info.line, info.column + 1)

# ---------------------------------------------------------------------------

when not defined(nimHasSinkInference):
  {.pragma: nosinks.}

proc raiseAssert*(msg: string) {.noinline, noreturn, nosinks.} =
  ## Raises an `AssertionDefect` with `msg`.
  sysFatal(AssertionDefect, msg)

proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =
  ## Raises an `AssertionDefect` with `msg`, but this is hidden
  ## from the effect system. Called when an assertion failed.
  # trick the compiler to not list `AssertionDefect` when called
  # by `assert`.
  # xxx simplify this pending bootstrap >= 1.4.0, after which cast not needed
  # anymore since `Defect` can't be raised.
  type Hide = proc (msg: string) {.noinline, raises: [], noSideEffect, tags: [].}
  cast[Hide](raiseAssert)(msg)

template assertImpl(cond: bool, msg: string, expr: string, enabled: static[bool]) =
  when enabled:
    const
      loc = instantiationInfo(fullPaths = compileOption("excessiveStackTrace"))
      ploc = $loc
    bind instantiationInfo
    mixin failedAssertImpl
    {.line: loc.}:
      if not cond:
        failedAssertImpl(ploc & " `" & expr & "` " & msg)

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 <nimc.html#compiler-usage-commandminusline-switches>`_.
  runnableExamples: assert 1 == 1
  runnableExamples("--assertions:off"):
    assert 1 == 2 # no code generated, no failure here
  runnableExamples("-d:danger"): assert 1 == 2 # ditto
  assertImpl(cond, msg, astToStr(cond), compileOption("assertions"))

template doAssert*(cond: untyped, msg = "") =
  ## Similar to `assert <#assert.t,untyped,string>`_ but is always turned on regardless of `--assertions`.
  runnableExamples:
    doAssert 1 == 1 # generates code even when built with `-d:danger` or `--assertions:off`
  assertImpl(cond, msg, astToStr(cond), true)

template onFailedAssert*(msg, code: untyped): untyped {.dirty.} =
  ## Sets an assertion failure handler that will intercept any assert
  ## statements following `onFailedAssert` in the current scope.
  runnableExamples:
    type MyError = object of CatchableError
      lineinfo: tuple[filename: string, line: int, column: int]
    # block-wide policy to change the failed assert exception type in order to
    # include a lineinfo
    onFailedAssert(msg):
      raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
    doAssertRaises(MyError): doAssert false
  when not defined(nimHasTemplateRedefinitionPragma):
    {.pragma: redefine.}
  template failedAssertImpl(msgIMPL: string): untyped {.dirty, redefine.} =
    let msg = msgIMPL
    code

template doAssertRaises*(exception: typedesc, code: untyped) =
  ## Raises `AssertionDefect` if specified `code` does not raise `exception`.
  runnableExamples:
    doAssertRaises(ValueError): raise newException(ValueError, "Hello World")
    doAssertRaises(CatchableError): raise newException(ValueError, "Hello World")
    doAssertRaises(AssertionDefect): doAssert false
  var wrong = false
  const begin = "expected raising '" & astToStr(exception) & "', instead"
  const msgEnd = " by: " & astToStr(code)
  template raisedForeign {.gensym.} = raiseAssert(begin & " raised foreign exception" & msgEnd)
  when Exception is exception:
    try:
      if true:
        code
      wrong = true
    except Exception as e: discard
    except: raisedForeign()
  else:
    try:
      if true:
        code
      wrong = true
    except exception:
      discard
    except Exception as e:
      mixin `$` # alternatively, we could define $cstring in this module
      raiseAssert(begin & " raised '" & $e.name & "'" & msgEnd)
    except: raisedForeign()
  if wrong:
    raiseAssert(begin & " nothing was raised" & msgEnd)
an class="w"> w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16]) e += ror27(a) + w[t] + (d xor (b and (c xor d))) + 0x5A827999'u32 b = ror2(b) shaF11(e, a, b, c, d, t + 1) shaF11(d, e, a, b, c, t + 2) shaF11(c, d, e, a, b, t + 3) shaF11(b, c, d, e, a, t + 4) template shaF2(a, b, c, d, e, t: untyped) = w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16]) e += ror27(a) + w[t] + (b xor c xor d) + 0x6ED9EBA1'u32 b = ror2(b) t = 20 while t < 40: shaF2(a, b, c, d, e, t + 0) shaF2(e, a, b, c, d, t + 1) shaF2(d, e, a, b, c, t + 2) shaF2(c, d, e, a, b, t + 3) shaF2(b, c, d, e, a, t + 4) t += 5 template shaF3(a, b, c, d, e, t: untyped) = w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16]) e += ror27(a) + w[t] + ((b and c) or (d and (b or c))) + 0x8F1BBCDC'u32 b = ror2(b) while t < 60: shaF3(a, b, c, d, e, t + 0) shaF3(e, a, b, c, d, t + 1) shaF3(d, e, a, b, c, t + 2) shaF3(c, d, e, a, b, t + 3) shaF3(b, c, d, e, a, t + 4) t += 5 template shaF4(a, b, c, d, e, t: untyped) = w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16]) e += ror27(a) + w[t] + (b xor c xor d) + 0xCA62C1D6'u32 b = ror2(b) while t < 80: shaF4(a, b, c, d, e, t + 0) shaF4(e, a, b, c, d, t + 1) shaF4(d, e, a, b, c, t + 2) shaF4(c, d, e, a, b, t + 3) shaF4(b, c, d, e, a, t + 4) t += 5 ctx.state[0] += a ctx.state[1] += b ctx.state[2] += c ctx.state[3] += d ctx.state[4] += e proc update*(ctx: var Sha1State, data: openArray[char]) = ## Updates the `Sha1State` with `data`. ## ## If you use the `secureHash proc <#secureHash,openArray[char]>`_, ## there's no need to call this function explicitly. var i = ctx.count mod 64 var j = 0 var len = data.len # Gather 64-bytes worth of data in order to perform a round with the leftover # data we had stored (but not processed yet) if len > 64 - i: copyMem(addr ctx.buf[i], unsafeAddr data[j], 64 - i) len -= 64 - i j += 64 - i transform(ctx) # Update the index since it's used in the while loop below _and_ we want to # keep its value if this code path isn't executed i = 0 # Process the bulk of the payload while len >= 64: copyMem(addr ctx.buf[0], unsafeAddr data[j], 64) len -= 64 j += 64 transform(ctx) # Process the tail of the payload (len is < 64) while len > 0: dec len ctx.buf[i] = byte(data[j]) inc i inc j if i == 64: transform(ctx) i = 0 ctx.count += data.len proc finalize*(ctx: var Sha1State): Sha1Digest = ## Finalizes the `Sha1State` and returns a `Sha1Digest`. ## ## If you use the `secureHash proc <#secureHash,openArray[char]>`_, ## there's no need to call this function explicitly. var cnt = uint64(ctx.count * 8) # a 1 bit update(ctx, "\x80") # Add padding until we reach a complexive size of 64 - 8 bytes while (ctx.count mod 64) != (64 - 8): update(ctx, "\x00") # The message length as a 64bit BE number completes the block var tmp: array[8, char] bigEndian64(addr tmp[0], addr cnt) update(ctx, tmp) # Turn the result into a single 160-bit number for i in 0 ..< 5: bigEndian32(addr ctx.state[i], addr ctx.state[i]) copyMem(addr result[0], addr ctx.state[0], Sha1DigestSize) # Public API proc secureHash*(str: openArray[char]): SecureHash = ## Generates a `SecureHash` from `str`. ## ## **See also:** ## * `secureHashFile proc <#secureHashFile,string>`_ for generating a `SecureHash` from a file ## * `parseSecureHash proc <#parseSecureHash,string>`_ for converting a string `hash` to `SecureHash` runnableExamples: let hash = secureHash("Hello World") assert hash == parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0") var state = newSha1State() state.update(str) SecureHash(state.finalize()) proc secureHashFile*(filename: string): SecureHash = ## Generates a `SecureHash` from a file. ## ## **See also:** ## * `secureHash proc <#secureHash,openArray[char]>`_ for generating a `SecureHash` from a string ## * `parseSecureHash proc <#parseSecureHash,string>`_ for converting a string `hash` to `SecureHash` const BufferLength = 8192 let f = open(filename) var state = newSha1State() var buffer = newString(BufferLength) while true: let length = readChars(f, buffer) if length == 0: break buffer.setLen(length) state.update(buffer) if length != BufferLength: break close(f) SecureHash(state.finalize()) proc `$`*(self: SecureHash): string = ## Returns the string representation of a `SecureHash`. ## ## **See also:** ## * `secureHash proc <#secureHash,openArray[char]>`_ for generating a `SecureHash` from a string runnableExamples: let hash = secureHash("Hello World") assert $hash == "0A4D55A8D778E5022FAB701977C5D840BBC486D0" result = "" for v in Sha1Digest(self): result.add(toHex(int(v), 2)) proc parseSecureHash*(hash: string): SecureHash = ## Converts a string `hash` to a `SecureHash`. ## ## **See also:** ## * `secureHash proc <#secureHash,openArray[char]>`_ for generating a `SecureHash` from a string ## * `secureHashFile proc <#secureHashFile,string>`_ for generating a `SecureHash` from a file runnableExamples: let hashStr = "0A4D55A8D778E5022FAB701977C5D840BBC486D0" secureHash = secureHash("Hello World") assert secureHash == parseSecureHash(hashStr) for i in 0 ..< Sha1DigestSize: Sha1Digest(result)[i] = uint8(parseHexInt(hash[i*2] & hash[i*2 + 1])) proc `==`*(a, b: SecureHash): bool = ## Checks if two `SecureHash` values are identical. runnableExamples: let a = secureHash("Hello World") b = secureHash("Goodbye World") c = parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0") assert a != b assert a == c # Not a constant-time comparison, but that's acceptable in this context Sha1Digest(a) == Sha1Digest(b) proc isValidSha1Hash*(s: string): bool = ## Checks if a string is a valid sha1 hash sum. s.len == 40 and allCharsInSet(s, HexDigits)