about summary refs log tree commit diff
path: root/lib/asserts.nix
blob: 8a5f1fb3feb76a200ba2c9c016ab50d7e6e1a0c4 (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
{ lib }:

rec {

  /* Print a trace message if pred is false.
     Intended to be used to augment asserts with helpful error messages.

     Example:
       assertMsg false "nope"
       => false
       stderr> trace: nope

       assert (assertMsg ("foo" == "bar") "foo is not bar, silly"); ""
       stderr> trace: foo is not bar, silly
       stderr> assert failed at …

     Type:
       assertMsg :: Bool -> String -> Bool
  */
  # TODO(Profpatsch): add tests that check stderr
  assertMsg = pred: msg:
    if pred
    then true
    else builtins.trace msg false;

  /* Specialized `assertMsg` for checking if val is one of the elements
     of a list. Useful for checking enums.

     Example:
       let sslLibrary = "libressl"
       in assertOneOf "sslLibrary" sslLibrary [ "openssl" "bearssl" ]
       => false
       stderr> trace: sslLibrary must be one of "openssl", "bearssl", but is: "libressl"

     Type:
       assertOneOf :: String -> ComparableVal -> List ComparableVal -> Bool
  */
  assertOneOf = name: val: xs: assertMsg
    (lib.elem val xs)
    "${name} must be one of ${
      lib.generators.toPretty {} xs}, but is: ${
        lib.generators.toPretty {} val}";

}