|
1 | 1 | import system/assertions
|
2 | 2 | import std/private/miscdollars
|
3 | 3 |
|
4 |
| -template enforce*(cond: untyped, msg: string, typ: typedesc = CatchableError) = |
5 |
| - ## similar to `doAssert` but defaults to raising `CatchableError` instead of |
6 |
| - ## `AssertionDefect`, and allows customizing the raised exception type. |
| 4 | +proc onEnforceFail[T](typ: typedesc, prefix: string, arg: T) {.noreturn, noinline.} = |
| 5 | + ## Making this a proc reduces size of binaries |
| 6 | + raise newException(typ, prefix & $arg) |
| 7 | + |
| 8 | +template enforce*[T](cond: untyped, arg: T, typ: typedesc = EnforceError) = |
| 9 | + ## similar to `doAssert` but defaults to raising catchable exception |
| 10 | + ## instead of `AssertionDefect`, and allows customizing the raised exception type. |
| 11 | + # `-d:nimLeanMessages` further reduces size of binaries at expense of not |
| 12 | + # showing location information; in future we can avoid generating un-necessary |
| 13 | + # strings and forward `TLineInfo` directly (or some equivalent compact type), |
| 14 | + # and then defer the string rendering until needed in `onEnforceFail`, |
| 15 | + # reducing binary size while preserving location information. stacktraces |
| 16 | + # can benefit from the same optimization. |
7 | 17 | runnableExamples:
|
8 | 18 | let a = 1
|
9 | 19 | enforce a == 1, $(a,)
|
10 |
| - doAssertRaises(CatchableError): enforce a == 2, $(a,) |
| 20 | + doAssertRaises(EnforceError): enforce a == 2, $(a,) |
11 | 21 | doAssertRaises(ValueError): enforce a == 2, $(a,), ValueError
|
12 |
| - |
13 |
| - const |
14 |
| - loc = instantiationInfo(fullPaths = compileOption("excessiveStackTrace")) |
15 |
| - ploc = $loc |
| 22 | + const loc = instantiationInfo(fullPaths = compileOption("excessiveStackTrace")) |
16 | 23 | {.line: loc.}:
|
17 | 24 | if not cond:
|
18 |
| - const expr = astToStr(cond) |
19 |
| - raise newException(typ, ploc & " `" & expr & "` " & msg) |
| 25 | + const prefix = |
| 26 | + when defined(nimLeanMessages): "" |
| 27 | + else: $loc & " `" & astToStr(cond) & "` " |
| 28 | + onEnforceFail(typ, prefix, arg) |
0 commit comments