Nix
2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Toggle main menu visibility
Loading...
Searching...
No Matches
topo-sort.hh
Go to the documentation of this file.
1
#pragma once
3
4
#include "
nix/util/error.hh
"
5
#include "
nix/util/fun.hh
"
6
#include <variant>
7
#include <concepts>
8
9
namespace
nix {
10
11
template
<
typename
T>
12
struct
Cycle
13
{
14
T path;
15
T parent;
16
};
17
18
template
<
typename
T>
19
using
TopoSortResult = std::variant<std::vector<T>,
Cycle<T>
>;
20
21
template
<
typename
T,
typename
Compare, std::invocable<const T &> F>
22
requires
std::same_as<std::remove_cvref_t<std::invoke_result_t<F, const T &>>, std::set<T, Compare>>
23
TopoSortResult<T> topoSort(std::set<T, Compare> items,
const
F & getChildren)
24
{
25
std::vector<T> sorted;
26
decltype
(items) visited, parents;
27
28
fun<std::optional<Cycle<T>
>(
const
T & path,
const
T * parent)> dfsVisit =
29
[&](
const
T & path,
const
T * parent) -> std::optional<Cycle<T>> {
30
if
(parents.count(path)) {
31
return
Cycle
{path, *parent};
32
}
33
34
if
(!visited.insert(path).second) {
35
return
std::nullopt;
36
}
37
parents.insert(path);
38
39
auto
&& references = std::invoke(getChildren, path);
40
41
for
(
auto
& i : references)
42
/* Don't traverse into items that don't exist in our starting set. */
43
if
(i != path && items.count(i)) {
44
auto
result = dfsVisit(i, &path);
45
if
(result.has_value()) {
46
return
result;
47
}
48
}
49
50
sorted.push_back(path);
51
parents.erase(path);
52
53
return
std::nullopt;
54
};
55
56
for
(
auto
& i : items) {
57
auto
cycle = dfsVisit(i,
nullptr
);
58
if
(cycle.has_value()) {
59
return
*cycle;
60
}
61
}
62
63
std::reverse(sorted.begin(), sorted.end());
64
65
return
sorted;
66
}
67
68
}
// namespace nix
nix::fun
Definition
fun.hh:19
error.hh
This file defines two main structs/classes used in nix error handling.
fun.hh
nix::Cycle
Definition
topo-sort.hh:13
libutil
include
nix
util
topo-sort.hh
Generated by
1.18.0