Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
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
9namespace nix {
10
11template<typename T>
12struct Cycle
13{
14 T path;
15 T parent;
16};
17
18template<typename T>
19using TopoSortResult = std::variant<std::vector<T>, Cycle<T>>;
20
21template<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>>
23TopoSortResult<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
Definition fun.hh:19
This file defines two main structs/classes used in nix error handling.
Definition topo-sort.hh:13