1 # Definitions related to run-time type checking. Used in particular
2 # to type-check NixOS configurations.
35 inherit (lib.attrsets)
70 inAttrPosSuffix = v: name:
71 let pos = builtins.unsafeGetAttrPos name v; in
72 if pos == null then "" else " at ${pos.file}:${toString pos.line}:${toString pos.column}";
76 isType = type: x: (x._type or "") == type;
78 setType = typeName: value: value // {
83 # Default type merging function
84 # takes two type functors and return the merged type
85 defaultTypeMerge = f: f':
86 let wrapped = f.wrapped.typeMerge f'.wrapped.functor;
87 payload = f.binOp f.payload f'.payload;
89 # cannot merge different types
93 else if (f.wrapped == null && f'.wrapped == null)
94 && (f.payload == null && f'.payload == null)
97 else if (f.wrapped != null && f'.wrapped != null) && (wrapped != null)
100 else if (f.payload != null && f'.payload != null) && (payload != null)
104 # Default type functor
105 defaultFunctor = name: {
107 type = types.${name} or null;
113 isOptionType = isType "option-type";
115 { # Human-readable representation of the type, should be equivalent to
116 # the type function name.
118 , # Description of the type, defined recursively by embedding the wrapped type if any.
120 # A hint for whether or not this description needs parentheses. Possible values:
121 # - "noun": a noun phrase
122 # Example description: "positive integer",
123 # - "conjunction": a phrase with a potentially ambiguous "or" connective
124 # Example description: "int or string"
125 # - "composite": a phrase with an "of" connective
126 # Example description: "list of string"
127 # - "nonRestrictiveClause": a noun followed by a comma and a clause
128 # Example description: "positive integer, meaning >0"
129 # See the `optionDescriptionPhrase` function.
130 , descriptionClass ? null
131 , # DO NOT USE WITHOUT KNOWING WHAT YOU ARE DOING!
132 # Function applied to each definition that must return false when a definition
133 # does not match the type. It should not check more than the root of the value,
134 # because checking nested values reduces laziness, leading to unnecessary
135 # infinite recursions in the module system.
136 # Further checks of nested values should be performed by throwing in
137 # the merge function.
138 # Strict and deep type checking can be performed by calling lib.deepSeq on
141 # See https://github.com/NixOS/nixpkgs/pull/6794 that introduced this change,
142 # https://github.com/NixOS/nixpkgs/pull/173568 and
143 # https://github.com/NixOS/nixpkgs/pull/168295 that attempted to revert this,
144 # https://github.com/NixOS/nixpkgs/issues/191124 and
145 # https://github.com/NixOS/nixos-search/issues/391 for what happens if you ignore
148 , # Merge a list of definitions together into a single value.
149 # This function is called with two arguments: the location of
150 # the option in the configuration as a list of strings
151 # (e.g. ["boot" "loader "grub" "enable"]), and a list of
152 # definition values and locations (e.g. [ { file = "/foo.nix";
153 # value = 1; } { file = "/bar.nix"; value = 2 } ]).
154 merge ? mergeDefaultOption
155 , # Whether this type has a value representing nothingness. If it does,
156 # this should be a value of the form { value = <the nothing value>; }
157 # If it doesn't, this should be {}
158 # This may be used when a value is required for `mkIf false`. This allows the extra laziness in e.g. `lazyAttrsOf`.
160 , # Return a flat attrset of sub-options. Used to generate
162 getSubOptions ? prefix: {}
163 , # List of modules if any, or null if none.
165 , # Function for building the same option type with a different list of
167 substSubModules ? m: null
168 , # Function that merge type declarations.
169 # internal, takes a functor as argument and returns the merged type.
170 # returning null means the type is not mergeable
171 typeMerge ? defaultTypeMerge functor
172 , # The type functor.
173 # internal, representation of the type as an attribute set.
174 # name: name of the type
175 # type: type function.
176 # wrapped: the type wrapped in case of compound types.
177 # payload: values of the type, two payloads of the same type must be
178 # combinable with the binOp binary operation.
179 # binOp: binary operation that merge two payloads of the same type.
180 functor ? defaultFunctor name
181 , # The deprecation message to display when this type is used by an option
182 # If null, the type isn't deprecated
183 deprecationMessage ? null
184 , # The types that occur in the definition of this type. This is used to
185 # issue deprecation warnings recursively. Can also be used to reuse
189 { _type = "option-type";
191 name check merge emptyValue getSubOptions getSubModules substSubModules
192 typeMerge functor deprecationMessage nestedTypes descriptionClass;
193 description = if description == null then name else description;
196 # optionDescriptionPhrase :: (str -> bool) -> optionType -> str
198 # Helper function for producing unambiguous but readable natural language
199 # descriptions of types.
203 # optionDescriptionPhase unparenthesize optionType
205 # `unparenthesize`: A function from descriptionClass string to boolean.
206 # It must return true when the class of phrase will fit unambiguously into
207 # the description of the caller.
209 # `optionType`: The option type to parenthesize or not.
210 # The option whose description we're returning.
214 # The description of the `optionType`, with parentheses if there may be an
216 optionDescriptionPhrase = unparenthesize: t:
217 if unparenthesize (t.descriptionClass or null)
219 else "(${t.description})";
221 # When adding new types don't forget to document them in
222 # nixos/doc/manual/development/option-types.section.md!
227 description = "raw value";
228 descriptionClass = "noun";
230 merge = mergeOneOption;
233 anything = mkOptionType {
235 description = "anything";
236 descriptionClass = "noun";
241 if isAttrs value && isStringLike value
242 then "stringCoercibleSet"
243 else builtins.typeOf value;
245 # Returns the common type of all definitions, throws an error if they
246 # don't have the same type
247 commonType = foldl' (type: def:
248 if getType def.value == type
250 else throw "The option `${showOption loc}' has conflicting option types in ${showFiles (getFiles defs)}"
251 ) (getType (head defs).value) defs;
254 # Recursively merge attribute sets
255 set = (attrsOf anything).merge;
256 # This is the type of packages, only accept a single definition
257 stringCoercibleSet = mergeOneOption;
258 lambda = loc: defs: arg: anything.merge
259 (loc ++ [ "<function body>" ])
262 value = def.value arg;
264 # Otherwise fall back to only allowing all equal definitions
265 }.${commonType} or mergeEqualOption;
266 in mergeFunction loc defs;
269 unspecified = mkOptionType {
270 name = "unspecified";
271 description = "unspecified value";
272 descriptionClass = "noun";
275 bool = mkOptionType {
277 description = "boolean";
278 descriptionClass = "noun";
280 merge = mergeEqualOption;
283 boolByOr = mkOptionType {
285 description = "boolean (merged using or)";
286 descriptionClass = "noun";
291 # Under the assumption that .check always runs before merge, we can assume that all defs.*.value
292 # have been forced, and therefore we assume we don't introduce order-dependent strictness here
301 description = "signed integer";
302 descriptionClass = "noun";
304 merge = mergeEqualOption;
307 # Specialized subdomains of int
310 betweenDesc = lowest: highest:
311 "${toString lowest} and ${toString highest} (both inclusive)";
312 between = lowest: highest:
313 assert lib.assertMsg (lowest <= highest)
314 "ints.between: lowest must be smaller than highest";
315 addCheck int (x: x >= lowest && x <= highest) // {
317 description = "integer between ${betweenDesc lowest highest}";
319 ign = lowest: highest: name: docStart:
320 between lowest highest // {
322 description = docStart + "; between ${betweenDesc lowest highest}";
324 unsign = bit: range: ign 0 (range - 1)
325 "unsignedInt${toString bit}" "${toString bit} bit unsigned integer";
326 sign = bit: range: ign (0 - (range / 2)) (range / 2 - 1)
327 "signedInt${toString bit}" "${toString bit} bit signed integer";
330 # TODO: Deduplicate with docs in nixos/doc/manual/development/option-types.section.md
332 An int with a fixed range.
336 ## `lib.types.ints.between` usage example
339 (ints.between 0 100).check (-1)
341 (ints.between 0 100).check (101)
343 (ints.between 0 0).check 0
351 unsigned = addCheck types.int (x: x >= 0) // {
352 name = "unsignedInt";
353 description = "unsigned integer, meaning >=0";
354 descriptionClass = "nonRestrictiveClause";
356 positive = addCheck types.int (x: x > 0) // {
357 name = "positiveInt";
358 description = "positive integer, meaning >0";
359 descriptionClass = "nonRestrictiveClause";
362 u16 = unsign 16 65536;
363 # the biggest int Nix accepts is 2^63 - 1 (9223372036854775808)
364 # the smallest int Nix accepts is -2^63 (-9223372036854775807)
365 u32 = unsign 32 4294967296;
366 # u64 = unsign 64 18446744073709551616;
370 s32 = sign 32 4294967296;
373 # Alias of u16 for a port number
376 float = mkOptionType {
378 description = "floating point number";
379 descriptionClass = "noun";
381 merge = mergeEqualOption;
384 number = either int float;
387 betweenDesc = lowest: highest:
388 "${builtins.toJSON lowest} and ${builtins.toJSON highest} (both inclusive)";
390 between = lowest: highest:
391 assert lib.assertMsg (lowest <= highest)
392 "numbers.between: lowest must be smaller than highest";
393 addCheck number (x: x >= lowest && x <= highest) // {
394 name = "numberBetween";
395 description = "integer or floating point number between ${betweenDesc lowest highest}";
398 nonnegative = addCheck number (x: x >= 0) // {
399 name = "numberNonnegative";
400 description = "nonnegative integer or floating point number, meaning >=0";
401 descriptionClass = "nonRestrictiveClause";
403 positive = addCheck number (x: x > 0) // {
404 name = "numberPositive";
405 description = "positive integer or floating point number, meaning >0";
406 descriptionClass = "nonRestrictiveClause";
412 description = "string";
413 descriptionClass = "noun";
415 merge = mergeEqualOption;
418 nonEmptyStr = mkOptionType {
419 name = "nonEmptyStr";
420 description = "non-empty string";
421 descriptionClass = "noun";
422 check = x: str.check x && builtins.match "[ \t\n]*" x == null;
426 # Allow a newline character at the end and trim it in the merge function.
429 inherit (strMatching "[^\n\r]*\n?") check merge;
432 name = "singleLineStr";
433 description = "(optionally newline-terminated) single-line string";
434 descriptionClass = "noun";
437 lib.removeSuffix "\n" (merge loc defs);
440 strMatching = pattern: mkOptionType {
441 name = "strMatching ${escapeNixString pattern}";
442 description = "string matching the pattern ${pattern}";
443 descriptionClass = "noun";
444 check = x: str.check x && builtins.match pattern x != null;
448 # Merge multiple definitions by concatenating them (with the given
449 # separator between the values).
450 separatedString = sep: mkOptionType rec {
451 name = "separatedString";
452 description = if sep == ""
453 then "Concatenated string" # for types.string.
454 else "strings concatenated with ${builtins.toJSON sep}"
456 descriptionClass = "noun";
458 merge = loc: defs: concatStringsSep sep (getValues defs);
459 functor = (defaultFunctor name) // {
461 binOp = sepLhs: sepRhs:
462 if sepLhs == sepRhs then sepLhs
467 lines = separatedString "\n";
468 commas = separatedString ",";
469 envVar = separatedString ":";
471 # Deprecated; should not be used because it quietly concatenates
472 # strings, which is usually not what you want.
473 # We use a lib.warn because `deprecationMessage` doesn't trigger in nested types such as `attrsOf string`
475 "The type `types.string` is deprecated. See https://github.com/NixOS/nixpkgs/pull/66346 for better alternative types."
476 (separatedString "" // {
480 passwdEntry = entryType: addCheck entryType (str: !(hasInfix ":" str || hasInfix "\n" str)) // {
481 name = "passwdEntry ${entryType.name}";
482 description = "${optionDescriptionPhrase (class: class == "noun") entryType}, not containing newlines or colons";
483 descriptionClass = "nonRestrictiveClause";
486 attrs = mkOptionType {
488 description = "attribute set";
490 merge = loc: foldl' (res: def: res // def.value) {};
491 emptyValue = { value = {}; };
494 # A package is a top-level store path (/nix/store/hash-name). This includes:
496 # - more generally, attribute sets with an `outPath` or `__toString` attribute
497 # pointing to a store path, e.g. flake inputs
498 # - strings with context, e.g. "${pkgs.foo}" or (toString pkgs.foo)
499 # - hardcoded store path literals (/nix/store/hash-foo) or strings without context
500 # ("/nix/store/hash-foo"). These get a context added to them using builtins.storePath.
501 # If you don't need a *top-level* store path, consider using pathInStore instead.
502 package = mkOptionType {
504 descriptionClass = "noun";
505 check = x: isDerivation x || isStorePath x;
507 let res = mergeOneOption loc defs;
508 in if builtins.isPath res || (builtins.isString res && ! builtins.hasContext res)
509 then toDerivation res
513 shellPackage = package // {
514 check = x: isDerivation x && hasAttr "shellPath" x;
518 (unique { message = "A Nixpkgs pkgs set can not be merged with another pkgs set."; } attrs // {
520 descriptionClass = "noun";
521 description = "Nixpkgs package set";
523 (x: (x._type or null) == "pkgs");
525 path = mkOptionType {
527 descriptionClass = "noun";
528 check = x: isStringLike x && builtins.substring 0 1 (toString x) == "/";
529 merge = mergeEqualOption;
532 pathInStore = mkOptionType {
533 name = "pathInStore";
534 description = "path in the Nix store";
535 descriptionClass = "noun";
536 check = x: isStringLike x && builtins.match "${builtins.storeDir}/[^.].*" (toString x) != null;
537 merge = mergeEqualOption;
540 listOf = elemType: mkOptionType rec {
542 description = "list of ${optionDescriptionPhrase (class: class == "noun" || class == "composite") elemType}";
543 descriptionClass = "composite";
546 map (x: x.value) (filter (x: x ? value) (concatLists (imap1 (n: def:
549 (loc ++ ["[definition ${toString n}-entry ${toString m}]"])
551 [{ inherit (def) file; value = def'; }]
555 emptyValue = { value = []; };
556 getSubOptions = prefix: elemType.getSubOptions (prefix ++ ["*"]);
557 getSubModules = elemType.getSubModules;
558 substSubModules = m: listOf (elemType.substSubModules m);
559 functor = (defaultFunctor name) // { wrapped = elemType; };
560 nestedTypes.elemType = elemType;
563 nonEmptyListOf = elemType:
564 let list = addCheck (types.listOf elemType) (l: l != []);
566 description = "non-empty ${optionDescriptionPhrase (class: class == "noun") list}";
567 emptyValue = { }; # no .value attr, meaning unset
568 substSubModules = m: nonEmptyListOf (elemType.substSubModules m);
571 attrsOf = elemType: mkOptionType rec {
573 description = "attribute set of ${optionDescriptionPhrase (class: class == "noun" || class == "composite") elemType}";
574 descriptionClass = "composite";
577 mapAttrs (n: v: v.value) (filterAttrs (n: v: v ? value) (zipAttrsWith (name: defs:
578 (mergeDefinitions (loc ++ [name]) elemType defs).optionalValue
580 # Push down position info.
581 (map (def: mapAttrs (n: v: { inherit (def) file; value = v; }) def.value) defs)));
582 emptyValue = { value = {}; };
583 getSubOptions = prefix: elemType.getSubOptions (prefix ++ ["<name>"]);
584 getSubModules = elemType.getSubModules;
585 substSubModules = m: attrsOf (elemType.substSubModules m);
586 functor = (defaultFunctor name) // { wrapped = elemType; };
587 nestedTypes.elemType = elemType;
590 # A version of attrsOf that's lazy in its values at the expense of
591 # conditional definitions not working properly. E.g. defining a value with
592 # `foo.attr = mkIf false 10`, then `foo ? attr == true`, whereas with
593 # attrsOf it would correctly be `false`. Accessing `foo.attr` would throw an
594 # error that it's not defined. Use only if conditional definitions don't make sense.
595 lazyAttrsOf = elemType: mkOptionType rec {
596 name = "lazyAttrsOf";
597 description = "lazy attribute set of ${optionDescriptionPhrase (class: class == "noun" || class == "composite") elemType}";
598 descriptionClass = "composite";
601 zipAttrsWith (name: defs:
602 let merged = mergeDefinitions (loc ++ [name]) elemType defs;
603 # mergedValue will trigger an appropriate error when accessed
604 in merged.optionalValue.value or elemType.emptyValue.value or merged.mergedValue
606 # Push down position info.
607 (map (def: mapAttrs (n: v: { inherit (def) file; value = v; }) def.value) defs);
608 emptyValue = { value = {}; };
609 getSubOptions = prefix: elemType.getSubOptions (prefix ++ ["<name>"]);
610 getSubModules = elemType.getSubModules;
611 substSubModules = m: lazyAttrsOf (elemType.substSubModules m);
612 functor = (defaultFunctor name) // { wrapped = elemType; };
613 nestedTypes.elemType = elemType;
616 # TODO: deprecate this in the future:
617 loaOf = elemType: types.attrsOf elemType // {
619 deprecationMessage = "Mixing lists with attribute values is no longer"
620 + " possible; please use `types.attrsOf` instead. See"
621 + " https://github.com/NixOS/nixpkgs/issues/1800 for the motivation.";
622 nestedTypes.elemType = elemType;
631 builtins.addErrorContext "while checking that attrTag tag ${lib.strings.escapeNixIdentifier n} is an option with a type${inAttrPosSuffix tags_ n}" (
632 throwIf (opt._type or null != "option")
633 "In attrTag, each tag value must be an option, but tag ${lib.strings.escapeNixIdentifier n} ${
635 if opt._type == "option-type"
636 then "was a bare type, not wrapped in mkOption."
637 else "was of type ${lib.strings.escapeNixString opt._type}."
640 declarations = opt.declarations or (
641 let pos = builtins.unsafeGetAttrPos n tags_;
642 in if pos == null then [] else [ pos.file ]
644 declarationPositions = opt.declarationPositions or (
645 let pos = builtins.unsafeGetAttrPos n tags_;
646 in if pos == null then [] else [ pos ]
651 choicesStr = concatMapStringsSep ", " lib.strings.escapeNixIdentifier (attrNames tags);
655 description = "attribute-tagged union";
656 descriptionClass = "noun";
657 getSubOptions = prefix:
659 (tagName: tagOption: {
660 "${lib.showOption prefix}" =
662 loc = prefix ++ [ tagName ];
666 check = v: isAttrs v && length (attrNames v) == 1 && tags?${head (attrNames v)};
669 choice = head (attrNames (head defs).value);
670 checkedValueDefs = map
672 assert (length (attrNames def.value)) == 1;
673 if (head (attrNames def.value)) != choice
674 then throw "The option `${showOption loc}` is defined both as `${choice}` and `${head (attrNames def.value)}`, in ${showFiles (getFiles defs)}."
675 else { inherit (def) file; value = def.value.${choice}; })
681 (lib.modules.evalOptionValue
687 else throw "The option `${showOption loc}` is defined as ${lib.strings.escapeNixIdentifier choice}, but ${lib.strings.escapeNixIdentifier choice} is not among the valid choices (${choicesStr}). Value ${choice} was defined in ${showFiles (getFiles defs)}.";
689 functor = defaultFunctor "attrTag" // {
690 type = { tags, ... }: types.attrTag tags;
691 payload = { inherit tags; };
694 # Add metadata in the format that submodules work with
696 option: { options = option; _file = "<attrTag {...}>"; pos = null; };
699 tags = a.tags // b.tags //
703 # FIXME: loc is not accurate; should include prefix
704 # Fortunately, it's only used for error messages, where a "relative" location is kinda ok.
705 # It is also returned though, but use of the attribute seems rare?
707 [ (wrapOptionDecl a.tags.${tagName}) (wrapOptionDecl bOpt) ]
709 # mergeOptionDecls is not idempotent in these attrs:
710 declarations = a.tags.${tagName}.declarations ++ bOpt.declarations;
711 declarationPositions = a.tags.${tagName}.declarationPositions ++ bOpt.declarationPositions;
714 (builtins.intersectAttrs a.tags b.tags);
719 uniq = unique { message = ""; };
721 unique = { message }: type: mkOptionType rec {
723 inherit (type) description descriptionClass check;
724 merge = mergeUniqueOption { inherit message; inherit (type) merge; };
725 emptyValue = type.emptyValue;
726 getSubOptions = type.getSubOptions;
727 getSubModules = type.getSubModules;
728 substSubModules = m: uniq (type.substSubModules m);
729 functor = (defaultFunctor name) // { wrapped = type; };
730 nestedTypes.elemType = type;
733 # Null or value of ...
734 nullOr = elemType: mkOptionType rec {
736 description = "null or ${optionDescriptionPhrase (class: class == "noun" || class == "conjunction") elemType}";
737 descriptionClass = "conjunction";
738 check = x: x == null || elemType.check x;
740 let nrNulls = count (def: def.value == null) defs; in
741 if nrNulls == length defs then null
742 else if nrNulls != 0 then
743 throw "The option `${showOption loc}` is defined both null and not null, in ${showFiles (getFiles defs)}."
744 else elemType.merge loc defs;
745 emptyValue = { value = null; };
746 getSubOptions = elemType.getSubOptions;
747 getSubModules = elemType.getSubModules;
748 substSubModules = m: nullOr (elemType.substSubModules m);
749 functor = (defaultFunctor name) // { wrapped = elemType; };
750 nestedTypes.elemType = elemType;
753 functionTo = elemType: mkOptionType {
755 description = "function that evaluates to a(n) ${optionDescriptionPhrase (class: class == "noun" || class == "composite") elemType}";
756 descriptionClass = "composite";
759 fnArgs: (mergeDefinitions (loc ++ [ "<function body>" ]) elemType (map (fn: { inherit (fn) file; value = fn.value fnArgs; }) defs)).mergedValue;
760 getSubOptions = prefix: elemType.getSubOptions (prefix ++ [ "<function body>" ]);
761 getSubModules = elemType.getSubModules;
762 substSubModules = m: functionTo (elemType.substSubModules m);
763 functor = (defaultFunctor "functionTo") // { wrapped = elemType; };
764 nestedTypes.elemType = elemType;
767 # A submodule (like typed attribute set). See NixOS manual.
768 submodule = modules: submoduleWith {
769 shorthandOnlyDefinesConfig = true;
770 modules = toList modules;
773 # A module to be imported in some other part of the configuration.
774 deferredModule = deferredModuleWith { };
776 # A module to be imported in some other part of the configuration.
777 # `staticModules`' options will be added to the documentation, unlike
778 # options declared via `config`.
779 deferredModuleWith = attrs@{ staticModules ? [] }: mkOptionType {
780 name = "deferredModule";
781 description = "module";
782 descriptionClass = "noun";
783 check = x: isAttrs x || isFunction x || path.check x;
785 imports = staticModules ++ map (def: lib.setDefaultModuleLocation "${def.file}, via option ${showOption loc}" def.value) defs;
787 inherit (submoduleWith { modules = staticModules; })
790 substSubModules = m: deferredModuleWith (attrs // {
793 functor = defaultFunctor "deferredModuleWith" // {
794 type = types.deferredModuleWith;
796 inherit staticModules;
799 staticModules = lhs.staticModules ++ rhs.staticModules;
804 # The type of a type!
805 optionType = mkOptionType {
807 description = "optionType";
808 descriptionClass = "noun";
809 check = value: value._type or null == "option-type";
812 then (head defs).value
814 # Prepares the type definitions for mergeOptionDecls, which
815 # annotates submodules types with file locations
816 optionModules = map ({ value, file }:
819 # There's no way to merge types directly from the module system,
820 # but we can cheat a bit by just declaring an option with the type
821 options = lib.mkOption {
826 # Merges all the types into a single one, including submodule merging.
827 # This also propagates file information to all submodules
828 mergedOption = fixupOptionType loc (mergeOptionDecls loc optionModules);
829 in mergedOption.type;
835 , shorthandOnlyDefinesConfig ? false
840 inherit (lib.modules) evalModules;
842 allModules = defs: map ({ value, file }:
843 if isAttrs value && shorthandOnlyDefinesConfig
844 then { _file = file; config = value; }
845 else { _file = file; imports = [ value ]; }
849 inherit class specialArgs;
851 # This is a work-around for the fact that some sub-modules,
852 # such as the one included in an attribute set, expects an "args"
853 # attribute to be given to the sub-module. As the option
854 # evaluation does not have any specific attribute name yet, we
855 # provide a default for the documentation and the freeform type.
857 # This is necessary as some option declaration might use the
858 # "name" attribute given as argument of the submodule and use it
859 # as the default of option declarations.
861 # We use lookalike unicode single angle quotation marks because
862 # of the docbook transformation the options receive. In all uses
863 # > and < wouldn't be encoded correctly so the encoded values
864 # would be used, and use of `<` and `>` would break the XML document.
865 # It shouldn't cause an issue since this is cosmetic for the manual.
866 _module.args.name = lib.mkOptionDefault "‹name›";
870 freeformType = base._module.freeformType;
878 if description != null then description
879 else freeformType.description or name;
880 check = x: isAttrs x || isFunction x || path.check x;
882 (base.extendModules {
883 modules = [ { _module.args.name = last loc; } ] ++ allModules defs;
886 emptyValue = { value = {}; };
887 getSubOptions = prefix: (base.extendModules
888 { inherit prefix; }).options // optionalAttrs (freeformType != null) {
889 # Expose the sub options of the freeform type. Note that the option
890 # discovery doesn't care about the attribute name used here, so this
891 # is just to avoid conflicts with potential options from the submodule
892 _freeformOptions = freeformType.getSubOptions prefix;
894 getSubModules = modules;
895 substSubModules = m: submoduleWith (attrs // {
898 nestedTypes = lib.optionalAttrs (freeformType != null) {
899 freeformType = freeformType;
901 functor = defaultFunctor name // {
902 type = types.submoduleWith;
904 inherit modules class specialArgs shorthandOnlyDefinesConfig description;
908 # `or null` was added for backwards compatibility only. `class` is
909 # always set in the current version of the module system.
910 if lhs.class or null == null then rhs.class or null
911 else if rhs.class or null == null then lhs.class or null
912 else if lhs.class or null == rhs.class then lhs.class or null
913 else throw "A submoduleWith option is declared multiple times with conflicting class values \"${toString lhs.class}\" and \"${toString rhs.class}\".";
914 modules = lhs.modules ++ rhs.modules;
916 let intersecting = builtins.intersectAttrs lhs.specialArgs rhs.specialArgs;
917 in if intersecting == {}
918 then lhs.specialArgs // rhs.specialArgs
919 else throw "A submoduleWith option is declared multiple times with the same specialArgs \"${toString (attrNames intersecting)}\"";
920 shorthandOnlyDefinesConfig =
921 if lhs.shorthandOnlyDefinesConfig == null
922 then rhs.shorthandOnlyDefinesConfig
923 else if rhs.shorthandOnlyDefinesConfig == null
924 then lhs.shorthandOnlyDefinesConfig
925 else if lhs.shorthandOnlyDefinesConfig == rhs.shorthandOnlyDefinesConfig
926 then lhs.shorthandOnlyDefinesConfig
927 else throw "A submoduleWith option is declared multiple times with conflicting shorthandOnlyDefinesConfig values";
929 if lhs.description == null
931 else if rhs.description == null
933 else if lhs.description == rhs.description
935 else throw "A submoduleWith option is declared multiple times with conflicting descriptions";
940 # A value from a set of allowed ones.
943 inherit (lib.lists) unique;
945 if builtins.isString v then ''"${v}"''
946 else if builtins.isInt v then builtins.toString v
947 else if builtins.isBool v then boolToString v
948 else ''<${builtins.typeOf v}>'';
953 # Length 0 or 1 enums may occur in a design pattern with type merging
954 # where an "interface" module declares an empty enum and other modules
955 # provide implementations, each extending the enum with their own
958 "impossible (empty enum)"
959 else if builtins.length values == 1 then
960 "value ${show (builtins.head values)} (singular enum)"
962 "one of ${concatMapStringsSep ", " show values}";
964 if builtins.length values < 2
967 check = flip elem values;
968 merge = mergeEqualOption;
969 functor = (defaultFunctor name) // { payload = values; binOp = a: b: unique (a ++ b); };
972 # Either value of type `t1` or `t2`.
973 either = t1: t2: mkOptionType rec {
976 if t1.descriptionClass or null == "nonRestrictiveClause"
978 # Plain, but add comma
979 "${t1.description}, or ${optionDescriptionPhrase (class: class == "noun" || class == "conjunction") t2}"
981 "${optionDescriptionPhrase (class: class == "noun" || class == "conjunction") t1} or ${optionDescriptionPhrase (class: class == "noun" || class == "conjunction" || class == "composite") t2}";
982 descriptionClass = "conjunction";
983 check = x: t1.check x || t2.check x;
986 defList = map (d: d.value) defs;
988 if all (x: t1.check x) defList
989 then t1.merge loc defs
990 else if all (x: t2.check x) defList
991 then t2.merge loc defs
992 else mergeOneOption loc defs;
994 let mt1 = t1.typeMerge (elemAt f'.wrapped 0).functor;
995 mt2 = t2.typeMerge (elemAt f'.wrapped 1).functor;
997 if (name == f'.name) && (mt1 != null) && (mt2 != null)
998 then functor.type mt1 mt2
1000 functor = (defaultFunctor name) // { wrapped = [ t1 t2 ]; };
1001 nestedTypes.left = t1;
1002 nestedTypes.right = t2;
1005 # Any of the types in the given list
1008 head' = if ts == [] then throw "types.oneOf needs to get at least one type in its argument" else head ts;
1010 in foldl' either head' tail';
1012 # Either value of type `coercedType` or `finalType`, the former is
1013 # converted to `finalType` using `coerceFunc`.
1014 coercedTo = coercedType: coerceFunc: finalType:
1015 assert lib.assertMsg (coercedType.getSubModules == null)
1016 "coercedTo: coercedType must not have submodules (it’s a ${
1017 coercedType.description})";
1020 description = "${optionDescriptionPhrase (class: class == "noun") finalType} or ${optionDescriptionPhrase (class: class == "noun") coercedType} convertible to it";
1021 check = x: (coercedType.check x && finalType.check (coerceFunc x)) || finalType.check x;
1025 if coercedType.check val then coerceFunc val
1027 in finalType.merge loc (map (def: def // { value = coerceVal def.value; }) defs);
1028 emptyValue = finalType.emptyValue;
1029 getSubOptions = finalType.getSubOptions;
1030 getSubModules = finalType.getSubModules;
1031 substSubModules = m: coercedTo coercedType coerceFunc (finalType.substSubModules m);
1032 typeMerge = t: null;
1033 functor = (defaultFunctor name) // { wrapped = finalType; };
1034 nestedTypes.coercedType = coercedType;
1035 nestedTypes.finalType = finalType;
1038 # Augment the given type with an additional type check function.
1039 addCheck = elemType: check: elemType // { check = x: elemType.check x && check x; };
1044 in outer_types // outer_types.types