1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
// Copyright (C) 2018 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
#ifndef SEARCH_HPP
#define SEARCH_HPP
#include <unordered_set>
#include <unordered_map>
#include <node.hpp>
#include <util/algorithm.hpp>
#include <util/assert.hpp>
#include <util/func_ref.hpp>
namespace ade
{
namespace traverse
{
using traverse_func_type
= util::func_ref<void (const Node&,
util::func_ref<void (const NodeHandle&)>)>;
inline void forward(const Node& node,
util::func_ref<void (const NodeHandle&)> visitor)
{
for (auto&& next : node.outNodes())
{
visitor(next);
}
}
inline void backward(const Node& node,
util::func_ref<void (const NodeHandle&)> visitor)
{
for (auto&& next : node.inNodes())
{
visitor(next);
}
}
} // namespace ade::traverse
/// Depth first search through node output edges
///
/// @param node - Start node, must not be null
/// @param visitor - Functor called for each found node,
/// can return true to continue search though found node output edges
void dfs(const NodeHandle& node,
util::func_ref<bool (const NodeHandle&)> visitor,
traverse::traverse_func_type direction = traverse::forward);
namespace details
{
struct TransitiveClosureHelper
{
using CacheT =
std::unordered_map<NodeHandle,
std::unordered_set<NodeHandle, HandleHasher<Node>>,
HandleHasher<Node>>;
void operator()(CacheT& cache,
const NodeHandle& node,
traverse::traverse_func_type direction) const;
};
}
/// Enumerate all nodes reachable through outputs for each source node in
/// provided list
///
/// @param nodes - List of nodes to check
/// @param visitor - functor which will be called for pairs of nodes,
/// first parameted is source node from provided list and
/// second parameter is node reachable from this source node
template<typename Nodes, typename Visitor>
void transitiveClosure(
Nodes&& nodes,
Visitor&& visitor,
traverse::traverse_func_type direction = traverse::forward)
{
using Helper = details::TransitiveClosureHelper;
Helper::CacheT visited;
for (auto node : nodes)
{
ASSERT(nullptr != node);
if (!util::contains(visited, node))
{
Helper()(visited, node, direction);
}
ASSERT(util::contains(visited, node));
for (auto nextNode : visited[node])
{
visitor(node, nextNode);
}
}
}
}
#endif // SEARCH_HPP
|