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
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::graph::{Direction, INCOMING, Graph, NodeIndex, OUTGOING};
use std::fmt::Debug;
use std::hash::Hash;
use super::DepNode;
pub struct DepGraphQuery<D: Clone + Debug + Hash + Eq> {
pub graph: Graph<DepNode<D>, ()>,
pub indices: FxHashMap<DepNode<D>, NodeIndex>,
}
impl<D: Clone + Debug + Hash + Eq> DepGraphQuery<D> {
pub fn new(nodes: &[DepNode<D>],
edges: &[(DepNode<D>, DepNode<D>)])
-> DepGraphQuery<D> {
let mut graph = Graph::new();
let mut indices = FxHashMap();
for node in nodes {
indices.insert(node.clone(), graph.next_node_index());
graph.add_node(node.clone());
}
for &(ref source, ref target) in edges {
let source = indices[source];
let target = indices[target];
graph.add_edge(source, target, ());
}
DepGraphQuery {
graph: graph,
indices: indices
}
}
pub fn contains_node(&self, node: &DepNode<D>) -> bool {
self.indices.contains_key(&node)
}
pub fn nodes(&self) -> Vec<&DepNode<D>> {
self.graph.all_nodes()
.iter()
.map(|n| &n.data)
.collect()
}
pub fn edges(&self) -> Vec<(&DepNode<D>,&DepNode<D>)> {
self.graph.all_edges()
.iter()
.map(|edge| (edge.source(), edge.target()))
.map(|(s, t)| (self.graph.node_data(s),
self.graph.node_data(t)))
.collect()
}
fn reachable_nodes(&self, node: &DepNode<D>, direction: Direction) -> Vec<&DepNode<D>> {
if let Some(&index) = self.indices.get(node) {
self.graph.depth_traverse(index, direction)
.map(|s| self.graph.node_data(s))
.collect()
} else {
vec![]
}
}
pub fn transitive_successors(&self, node: &DepNode<D>) -> Vec<&DepNode<D>> {
self.reachable_nodes(node, OUTGOING)
}
pub fn transitive_predecessors(&self, node: &DepNode<D>) -> Vec<&DepNode<D>> {
self.reachable_nodes(node, INCOMING)
}
pub fn immediate_successors(&self, node: &DepNode<D>) -> Vec<&DepNode<D>> {
if let Some(&index) = self.indices.get(&node) {
self.graph.successor_nodes(index)
.map(|s| self.graph.node_data(s))
.collect()
} else {
vec![]
}
}
}