lib.modules: document mkDefinition section

This commit is contained in:
Johannes Kirschbauer 2025-03-18 14:32:30 +00:00
parent b42b9e061b
commit c906064af1
No known key found for this signature in database
2 changed files with 47 additions and 0 deletions

View File

@ -123,3 +123,47 @@ they were declared in separate modules. This can be done using
];
}
```
## Free-floating definitions {#sec-option-definitions-definitions}
:::{.note}
The module system internally transforms module syntax into definitions. This always happens internally.
:::
It is possible to create first class definitions which are not transformed _again_ into definitions by the module system.
Usually the file location of a definition is implicit and equal to the file it came from.
However, when manipulating definitions, it may be useful for them to be completely self-contained (or "free-floating").
A free-floating definition is created with `mkDefinition { file = ...; value = ...; }`.
Preserving the file location creates better error messages, for example when copying definitions from one option to another.
Other properties like `mkOverride` `mkMerge` `mkAfter` can be used in the `value` attribute but not the other way around.
The following shows an example configuration that yields an error with the custom position information:
```nix
{
_file = "file.nix";
options.foo = mkOption {
default = 13;
};
config.foo = lib.mkDefinition {
file = "custom place";
# mkOptionDefault creates a conflict with the option foo's `default = 1` on purpose
# So we see the error message below contains the conflicting values and different positions
value = lib.mkOptionDefault 42;
};
}
```
evaluating the module yields the following error:
```
error: Cannot merge definitions of `foo'. Definition values:
- In `file.nix': 13
- In `custom place': 42
```
To set the file location for all definitions in a module, you may add the `_file` module syntax attribute, which has a similar effect to using `mkDefinition` on all definitions in the module, without the hassle.

View File

@ -1664,6 +1664,9 @@
"sec-option-definitions-merging": [
"index.html#sec-option-definitions-merging"
],
"sec-option-definitions-definitions": [
"index.html#sec-option-definitions-definitions"
],
"sec-assertions": [
"index.html#sec-assertions"
],