summaryrefslogtreecommitdiffstats
path: root/lib/meta-types.nix
blob: a907d1676061f9397cc70493d2e0efc56d9a3c7c (plain)
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
{ lib }:
# Simple internal type checks for meta.
# This file is only intended for internal nixpkgs use.
# It is not a stable interface and may be changed arbitrarily.
#
# TODO: add a method to the module system types
#       see https://github.com/NixOS/nixpkgs/pull/273935#issuecomment-1854173100
let
  inherit (lib)
    isString
    isInt
    isAttrs
    isList
    isDerivation
    all
    any
    attrNames
    attrValues
    catAttrs
    concatMap
    isFunction
    isBool
    concatStringsSep
    concatMapStringsSep
    isFloat
    elem
    mapAttrs
    ;
  isTypeDef = t: isAttrs t && t ? name && isString t.name && t ? verify && isFunction t.verify;
in
lib.fix (self: {

  /*
    `errors type "<context>" value` gives a list of string error messages,
    each prefixed with "<context>: ", for why `value` is not of type `type`

    Only use this if `type.verify value` is false

    Types can override this by specifying their own `type.errors = ctx: value:` attribute

    This is intentionally not tied into `type.verify`,
    in order to keep the successful path as fast as possible with minimal allocations
  */
  errors =
    t:
    t.errors or (ctx: v: [
      "${ctx}: Invalid value; expected ${t.name}, got\n    ${
        lib.generators.toPretty { indent = "    "; } v
      }"
    ]);

  string = {
    name = "string";
    verify = isString;
  };
  str = self.string; # Type alias

  any = {
    name = "any";
    verify = _: true;
  };

  int = {
    name = "int";
    verify = isInt;
  };

  float = {
    name = "float";
    verify = isFloat;
  };

  bool = {
    name = "bool";
    verify = isBool;
  };

  attrs = {
    name = "attrs";
    verify = isAttrs;
  };

  list = {
    name = "list";
    verify = isList;
  };

  attrsOf =
    t:
    assert isTypeDef t;
    let
      inherit (t) verify;
    in
    {
      name = "attrsOf<${t.name}>";
      verify =
        # attrsOf<any> can be optimised to just isAttrs
        if t == self.any then isAttrs else attrs: isAttrs attrs && all verify (attrValues attrs);
      errors =
        ctx: attrs:
        if !isAttrs attrs then
          self.errors self.attrs ctx attrs
        else
          concatMap (
            name: lib.optionals (!verify attrs.${name}) (self.errors t "${ctx}.${name}" attrs.${name})
          ) (attrNames attrs);
    };

  derivation = {
    name = "derivation";
    verify = isDerivation;
  };

  listOf =
    t:
    assert isTypeDef t;
    let
      inherit (t) verify;
    in
    {
      name = "listOf<${t.name}>";
      verify =
        # listOf<any> can be optimised to just isList
        if t == self.any then isList else v: isList v && all verify v;
      errors =
        ctx: v:
        if !isList v then
          self.errors self.list ctx v
        else
          lib.concatMap ({ valid, errors }: errors) (
            lib.filter ({ valid, errors }: !valid) (
              lib.imap0 (i: el: {
                valid = verify el;
                errors = self.errors t "${ctx}.${toString i}" el;
              }) v
            )
          );
    };

  union =
    types:
    assert all isTypeDef types;
    let
      # Store a list of functions so we don't have to pay the cost of attrset lookups at runtime.
      funcs = catAttrs "verify" types;
    in
    {
      name = "union<${concatStringsSep "," (catAttrs "name" types)}>";
      verify = v: any (func: func v) funcs;
    };

  intersection =
    types:
    assert all isTypeDef types;
    let
      # Store a list of functions so we don't have to pay the cost of attrset lookups at runtime.
      funcs = catAttrs "verify" types;
    in
    {
      name = "intersection<${concatStringsSep "," (catAttrs "name" types)}>";
      verify = v: all (func: func v) funcs;
    };

  either =
    t1: t2:
    assert isTypeDef t1 && isTypeDef t2;
    let
      # Store the functions directly so we don't have to pay the cost of attrset lookups at runtime.
      v1 = t1.verify;
      v2 = t2.verify;
    in
    {
      name = "either<${t1.name},${t2.name}>";
      verify = v: v1 v || v2 v;
    };

  both =
    t1: t2:
    assert isTypeDef t1 && isTypeDef t2;
    let
      # Store the functions directly so we don't have to pay the cost of attrset lookups at runtime.
      v1 = t1.verify;
      v2 = t2.verify;
    in
    {
      name = "both<${t1.name},${t2.name}>";
      verify = v: v1 v && v2 v;
    };

  not =
    t:
    assert isTypeDef t;
    let
      inherit (t) verify;
    in
    {
      name = "not<${t.name}>";
      verify = v: !(verify v);
    };

  enum =
    values:
    assert isList values;
    {
      name = if all isString values then "enum<${concatStringsSep "," values}>" else "enum";
      verify = v: elem v values;
    };

  record =
    fields:
    assert isAttrs fields && all isTypeDef (attrValues fields);
    let
      # Map attrs directly to the verify function for performance
      fieldVerifiers = mapAttrs (_: t: t.verify) fields;
    in
    {
      name = "record";
      verify = v: isAttrs v && all (k: fieldVerifiers ? ${k} && fieldVerifiers.${k} v.${k}) (attrNames v);
      errors =
        ctx: v:
        if !isAttrs v then
          self.errors self.attrs ctx v
        else
          concatMap (
            k:
            if fieldVerifiers ? ${k} then
              lib.optionals (!fieldVerifiers.${k} v.${k}) (self.errors fields.${k} "${ctx}.${k}" v.${k})
            else
              [
                "${ctx}: key '${k}' is unrecognized; expected one of: \n  [${
                  concatMapStringsSep ", " (x: "'${x}'") (attrNames fields)
                }]"
              ]
          ) (attrNames v);
    };

})