summary refs log tree commit diff
path: root/pkgs/lib/modules.nix
blob: 25cb956a0ea415469c0e540f2a264930716ea4bc (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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# NixOS module handling.

let lib = import ./default.nix; in

with { inherit (builtins) head; };
with import ./trivial.nix;
with import ./lists.nix;
with import ./misc.nix;
with import ./attrsets.nix;
with import ./options.nix;
with import ./properties.nix;

rec {

  # Unfortunately this can also be a string.
  isPath = x: !(
     builtins.isFunction x
  || builtins.isAttrs x
  || builtins.isInt x
  || builtins.isBool x
  || builtins.isList x
  );

  importIfPath = path:
    if isPath path then
      import path
    else
      path;

  applyIfFunction = f: arg:
    if builtins.isFunction f then
      f arg
    else
      f;

  isModule = m:
       (m ? config && isAttrs m.config && ! isOption m.config)
    || (m ? options && isAttrs m.options && ! isOption m.options);

  # Convert module to a set which has imports / options and config
  # attributes.
  unifyModuleSyntax = m:
    let
      delayedModule = delayProperties m;
      getImports =
        if m ? config || m ? options then
          m.imports or []
        else
          toList (rmProperties (delayedModule.require or []));

      getImportedPaths = filter isPath getImports;
      getImportedSets = filter (x: !isPath x) getImports;

      getConfig =
        removeAttrs delayedModule ["require" "key"];

    in
      if isModule m then
        { key = "<unknown location>"; } // m
      else
        {
          key = "<unknown location>";
          imports = getImportedPaths;
          config = getConfig;
        } // (
          if getImportedSets != [] then
            assert length getImportedSets == 1;
            { options = head getImportedSets; }
          else
            {}
        );


  unifyOptionModule = {key ? "<unknown location>"}: m: (args:
    let module = lib.applyIfFunction m args; in
    if lib.isModule module then
      { inherit key; } // module
    else
      { inherit key; options = module; }
  );


  moduleClosure = initModules: args:
    let
      moduleImport = origin: index: m:
        let m' = applyIfFunction (importIfPath m) args;
        in (unifyModuleSyntax m') // {
          # used by generic closure to avoid duplicated imports.
          key =
            if isPath m then m
            else if m' ? key then m'.key
            else newModuleName origin index;
        };

      getImports = m: m.imports or [];

      newModuleName = origin: index:
        "${origin.key}:<import-${toString index}>";

      topLevel = {
        key = "<top-level>";
      };

    in
      (lazyGenericClosure {
        startSet = imap (moduleImport topLevel) initModules;
        operator = m: imap (moduleImport m) (getImports m);
      });

  selectDeclsAndDefs = modules:
    lib.concatMap (m:
      if m ? config || m ? options then
         [ (m.options or {}) ]
      ++ [ (m.config or {}) ]
      else
        [ m ]
    ) modules;


  moduleApply = funs: module:
    lib.mapAttrs (name: value:
      if builtins.hasAttr name funs then
        let fun = lib.getAttr name funs; in
        fun value
      else
        value
    ) module;

  # Handle mkMerge function left behind after a delay property.
  moduleFlattenMerge = module:
    if module ? config &&
       isProperty module.config &&
       isMerge module.config.property
    then
      (map (cfg: { key = module.key; config = cfg; }) module.config.content)
      ++ [ (module // { config = {}; }) ]
    else
      [ module ];

  # Handle mkMerge attributes which are left behind by previous delay
  # properties and convert them into a list of modules. Delay properties
  # inside the config attribute of a module and create a second module if a
  # mkMerge attribute was left behind.
  #
  # Module -> [ Module ]
  delayModule = module:
    map (moduleApply { config = delayProperties; }) (moduleFlattenMerge module);

  evalDefinitions = opt: values:
    if opt ? type && opt.type.delayOnGlobalEval then
      map (delayPropertiesWithIter opt.type.iter opt.name)
        (evalLocalProperties values)
    else
      evalProperties values;


  selectModule = name: m:
    { inherit (m) key;
    } // (
      if m ? options && builtins.hasAttr name m.options then
        { options = lib.getAttr name m.options; }
      else {}
    ) // (
      if m ? config && builtins.hasAttr name m.config then
        { config = lib.getAttr name m.config; }
      else {}
    );

  filterModules = name: modules:
    filter (m: m ? config || m ? options) (
      map (selectModule name) modules
    );

  modulesNames = modules:
    lib.concatMap (m: []
    ++ optionals (m ? options) (lib.attrNames m.options)
    ++ optionals (m ? config) (lib.attrNames m.config)
    ) modules;

  moduleZip = funs: modules:
    lib.mapAttrs (name: fun:
      fun (catAttrs name modules)
    ) funs;

  moduleMerge = path: modules:
    let modules_ = modules; in
    let
      addName = name:
        if path == "" then name else path + "." + name;

      modules = concatLists (map delayModule modules_);

      modulesOf = name: filterModules name modules;
      declarationsOf = name: filter (m: m ? options) (modulesOf name);
      definitionsOf  = name: filter (m: m ? config ) (modulesOf name);

      recurseInto = name:
        moduleMerge (addName name) (modulesOf name);

      recurseForOption = name: modules:
        moduleMerge name (
          map unifyModuleSyntax modules
        );

      errorSource = modules:
        "The error may come from the following files:\n" + (
          lib.concatStringsSep "\n" (
            map (m:
              if m ? key then toString m.key else "<unknown location>"
            ) modules
          )
        );

      eol = "\n";

      allNames = modulesNames modules;

      getResults = m:
        let fetchResult = s: mapAttrs (n: v: v.result) s; in {
          options = fetchResult m.options;
          config = fetchResult m.config;
        };

      endRecursion =  { options = {}; config = {}; };

    in if modules == [] then endRecursion else
      getResults (fix (crossResults: moduleZip {
        options = lib.zipWithNames allNames (name: values: rec {
          config = lib.getAttr name crossResults.config;

          declarations = declarationsOf name;
          declarationSources =
            map (m: {
              source = m.key;
            }) declarations;


          hasOptions = values != [];
          isOption = any lib.isOption values;

          decls = # add location to sub-module options.
            map (m:
              mapSubOptions
                (unifyOptionModule {inherit (m) key;})
                m.options
            ) declarations;

          decl =
            lib.addErrorContext "${eol
              }while enhancing option `${addName name}':${eol
              }${errorSource declarations}${eol
            }" (
              addOptionMakeUp
                { name = addName name; recurseInto = recurseForOption; }
                (mergeOptionDecls decls)
            );

          value = decl // (with config; {
            inherit (config) isNotDefined;
            isDefined = ! isNotDefined;
            declarations = declarationSources;
            definitions = definitionSources;
            config = strictResult;
          });

          recurse = (recurseInto name).options;

          result =
            if isOption then value
            else if !hasOptions then {}
            else if all isAttrs values then recurse
            else
              throw "${eol
                }Unexpected type where option declarations are expected.${eol
                }${errorSource declarations}${eol
              }";

        });

        config = lib.zipWithNames allNames (name: values_: rec {
          option = lib.getAttr name crossResults.options;

          definitions = definitionsOf name;
          definitionSources =
            map (m: {
              source = m.key;
              value = m.config;
            }) definitions;

          values = values_ ++
            optionals (option.isOption && option.decl ? extraConfigs)
              option.decl.extraConfigs;

          defs = evalDefinitions option.decl values;

          isNotDefined = defs == [];

          value =
            lib.addErrorContext "${eol
              }while evaluating the option `${addName name}':${eol
              }${errorSource (modulesOf name)}${eol
            }" (
              let opt = option.decl; in
              opt.apply (
                if isNotDefined then
                  if opt ? default then opt.default
                  else throw "Not defined."
                else opt.merge defs
              )
            );

          strictResult = builtins.tryEval (builtins.toXML value);

          recurse = (recurseInto name).config;

          configIsAnOption = v: isOption (rmProperties v);
          errConfigIsAnOption =
            let badModules = filter (m: configIsAnOption m.config) definitions; in
            "${eol
              }Option ${addName name} is defined in the configuration section.${eol
              }${errorSource badModules}${eol
            }";

          errDefinedWithoutDeclaration =
            let badModules = definitions; in
            "${eol
              }Option '${addName name}' defined without option declaration.${eol
              }${errorSource badModules}${eol
            }";

          result =
            if option.isOption then value
            else if !option.hasOptions then throw errDefinedWithoutDeclaration
            else if any configIsAnOption values then throw errConfigIsAnOption
            else if all isAttrs values then recurse
            # plain value during the traversal
            else throw errDefinedWithoutDeclaration;

        });
      } modules));


  fixMergeModules = initModules: {...}@args:
    lib.fix (result:
      # This trick avoid an infinite loop because names of attribute are
      # know and it is not require to evaluate the result of moduleMerge to
      # know which attribute are present as argument.
      let module = { inherit (result) options config; }; in

      moduleMerge "" (
        moduleClosure initModules (module // args)
      )
    );

  # Visit all definitions to raise errors related to undeclared options.
  checkModule = path: {config, options, ...}@m:
    let
      eol = "\n";
      addName = name:
        if path == "" then name else path + "." + name;
    in
    if lib.isOption options then
      if options ? options then
        options.type.fold
          (cfg: res: res && checkModule (options.type.docPath path) cfg._args)
          true config
      else
        true
    else if isAttrs options && lib.attrNames m.options != [] then
      all (name:
        lib.addErrorContext "${eol
          }while checking the attribute `${addName name}':${eol
        }" (checkModule (addName name) (selectModule name m))
      ) (lib.attrNames m.config)
    else
      builtins.trace "try to evaluate config ${lib.showVal config}."
      false;

}