Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib/attrsets.nix: add intersectPatterns #212186

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions lib/attrsets.nix
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,33 @@ rec {
) [pattern attrs]));


/* Pattern intersection. Specifically, the following is true
if it does not `throw`:

forall patternList,
forall arg,
matchAttrs (intersectPatterns patternList) arg
== all (matchAttrs patternList) arg

Type:
intersectPatterns :: [ AttrSet ] -> AttrSet
*/
intersectPatterns = let
inherit (lib) any unique isFunction elem;
inherit (lib.strings) concatStringsSep;
mergeLeaves = path: list:
let list' = unique list; in
# avoid introducing any new dependencies on function equality
assert any isFunction list -> throw "function found in pattern list at path '${concatStringsSep "." path}'";
assert length list == 0 -> throw "this should not happen; path '${concatStringsSep "." path}'";
assert length list' != 1 -> throw "disjoint patterns intersected at path '${concatStringsSep "." path}', values=${builtins.toString list'}";
elemAt list' 0;
intersectPatterns' = path: list:
if !(any isAttrs list) then mergeLeaves path list
else if all isAttrs list then mapAttrs (k: v: intersectPatterns' (path++[k]) v) (zipAttrs list)
else throw "mix of attrsets and non-attrsets at path '${concatStringsSep "." path}', values = ${concatStringsSep "\n" (map builtins.toJSON list)}";
in list: (intersectPatterns' [] list);

/* Override only the attributes that are already present in the old set
useful for deep-overriding.

Expand Down
8 changes: 7 additions & 1 deletion lib/lists.nix
Original file line number Diff line number Diff line change
Expand Up @@ -631,9 +631,15 @@ rec {
=> [ "13" "14" "23" "24" ]
*/
crossLists = builtins.trace
"lib.crossLists is deprecated, use lib.cartesianProductOfSets instead"
"lib.crossLists is deprecated, use lib.cartesianProductOfLists instead"
(f: foldl (fs: args: concatMap (f: map f args) fs) [f]);

cartesianProductOfLists = lists:
let
inherit (lib) cartesianProductOfSets toString nameValuePair genAttrs attrValues;
attrs = builtins.listToAttrs (imap0 (i: nameValuePair (builtins.toString i)) lists);
cross = cartesianProductOfSets attrs;
in map attrValues cross;

/* Remove duplicate elements from the list. O(n^2) complexity.

Expand Down