2016-11-08 14:02:55 +11:00
|
|
|
use rustc_data_structures::fx::FxHashMap;
|
2020-10-09 11:22:54 +02:00
|
|
|
use rustc_data_structures::graph::implementation::{Direction, Graph, NodeIndex, INCOMING};
|
2016-01-05 13:02:57 -05:00
|
|
|
|
2020-03-18 10:25:22 +01:00
|
|
|
use super::{DepKind, DepNode};
|
2016-01-05 13:02:57 -05:00
|
|
|
|
2020-03-18 10:25:22 +01:00
|
|
|
pub struct DepGraphQuery<K> {
|
|
|
|
pub graph: Graph<DepNode<K>, ()>,
|
|
|
|
pub indices: FxHashMap<DepNode<K>, NodeIndex>,
|
2016-01-05 13:02:57 -05:00
|
|
|
}
|
|
|
|
|
2020-03-18 10:25:22 +01:00
|
|
|
impl<K: DepKind> DepGraphQuery<K> {
|
|
|
|
pub fn new(nodes: &[DepNode<K>], edges: &[(DepNode<K>, DepNode<K>)]) -> DepGraphQuery<K> {
|
2017-09-14 21:28:55 -07:00
|
|
|
let mut graph = Graph::with_capacity(nodes.len(), edges.len());
|
2018-10-16 10:44:26 +02:00
|
|
|
let mut indices = FxHashMap::default();
|
2016-01-05 13:02:57 -05:00
|
|
|
for node in nodes {
|
2020-04-16 00:00:22 +02:00
|
|
|
indices.insert(*node, graph.add_node(*node));
|
2016-01-05 13:02:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
for &(ref source, ref target) in edges {
|
|
|
|
let source = indices[source];
|
|
|
|
let target = indices[target];
|
|
|
|
graph.add_edge(source, target, ());
|
|
|
|
}
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
DepGraphQuery { graph, indices }
|
2016-01-05 13:02:57 -05:00
|
|
|
}
|
|
|
|
|
2020-03-18 10:25:22 +01:00
|
|
|
pub fn contains_node(&self, node: &DepNode<K>) -> bool {
|
2016-03-28 17:37:34 -04:00
|
|
|
self.indices.contains_key(&node)
|
|
|
|
}
|
|
|
|
|
2020-03-18 10:25:22 +01:00
|
|
|
pub fn nodes(&self) -> Vec<&DepNode<K>> {
|
2019-12-22 17:42:04 -05:00
|
|
|
self.graph.all_nodes().iter().map(|n| &n.data).collect()
|
2016-01-05 13:02:57 -05:00
|
|
|
}
|
|
|
|
|
2020-03-18 10:25:22 +01:00
|
|
|
pub fn edges(&self) -> Vec<(&DepNode<K>, &DepNode<K>)> {
|
2019-12-22 17:42:04 -05:00
|
|
|
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()
|
2016-01-05 13:02:57 -05:00
|
|
|
}
|
|
|
|
|
2020-03-18 10:25:22 +01:00
|
|
|
fn reachable_nodes(&self, node: &DepNode<K>, direction: Direction) -> Vec<&DepNode<K>> {
|
2016-05-26 06:11:16 -04:00
|
|
|
if let Some(&index) = self.indices.get(node) {
|
2019-12-22 17:42:04 -05:00
|
|
|
self.graph.depth_traverse(index, direction).map(|s| self.graph.node_data(s)).collect()
|
2016-03-28 17:37:34 -04:00
|
|
|
} else {
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-06 17:28:59 -04:00
|
|
|
/// All nodes that can reach `node`.
|
2020-03-18 10:25:22 +01:00
|
|
|
pub fn transitive_predecessors(&self, node: &DepNode<K>) -> Vec<&DepNode<K>> {
|
2016-04-06 17:28:59 -04:00
|
|
|
self.reachable_nodes(node, INCOMING)
|
|
|
|
}
|
2016-01-05 13:02:57 -05:00
|
|
|
}
|