1 //! A graph module for use in dataflow, region resolution, and elsewhere.
3 //! # Interface details
5 //! You customize the graph by specifying a "node data" type `N` and an
6 //! "edge data" type `E`. You can then later gain access (mutable or
7 //! immutable) to these "user-data" bits. Currently, you can only add
8 //! nodes or edges to the graph. You cannot remove or modify them once
9 //! added. This could be changed if we have a need.
11 //! # Implementation details
13 //! The main tricky thing about this code is the way that edges are
14 //! stored. The edges are stored in a central array, but they are also
15 //! threaded onto two linked lists for each node, one for incoming edges
16 //! and one for outgoing edges. Note that every edge is a member of some
17 //! incoming list and some outgoing list. Basically you can load the
18 //! first index of the linked list from the node data structures (the
19 //! field `first_edge`) and then, for each edge, load the next index from
20 //! the field `next_edge`). Each of those fields is an array that should
21 //! be indexed by the direction (see the type `Direction`).
23 use crate::snapshot_vec::{SnapshotVec, SnapshotVecDelegate};
24 use rustc_index::bit_set::BitSet;
30 pub struct Graph<N, E> {
31 nodes: SnapshotVec<Node<N>>,
32 edges: SnapshotVec<Edge<E>>,
36 first_edge: [EdgeIndex; 2], // see module comment
42 next_edge: [EdgeIndex; 2], // see module comment
48 impl<N> SnapshotVecDelegate for Node<N> {
52 fn reverse(_: &mut Vec<Node<N>>, _: ()) {}
55 impl<N> SnapshotVecDelegate for Edge<N> {
59 fn reverse(_: &mut Vec<Edge<N>>, _: ()) {}
62 #[derive(Copy, Clone, PartialEq, Debug)]
63 pub struct NodeIndex(pub usize);
65 #[derive(Copy, Clone, PartialEq, Debug)]
66 pub struct EdgeIndex(pub usize);
68 pub const INVALID_EDGE_INDEX: EdgeIndex = EdgeIndex(usize::MAX);
70 // Use a private field here to guarantee no more instances are created:
71 #[derive(Copy, Clone, Debug, PartialEq)]
72 pub struct Direction {
76 pub const OUTGOING: Direction = Direction { repr: 0 };
78 pub const INCOMING: Direction = Direction { repr: 1 };
81 /// Returns unique ID (unique with respect to the graph holding associated node).
82 pub fn node_id(self) -> usize {
87 impl<N: Debug, E: Debug> Graph<N, E> {
88 pub fn new() -> Graph<N, E> {
89 Graph { nodes: SnapshotVec::new(), edges: SnapshotVec::new() }
92 pub fn with_capacity(nodes: usize, edges: usize) -> Graph<N, E> {
93 Graph { nodes: SnapshotVec::with_capacity(nodes), edges: SnapshotVec::with_capacity(edges) }
99 pub fn all_nodes(&self) -> &[Node<N>] {
104 pub fn len_nodes(&self) -> usize {
109 pub fn all_edges(&self) -> &[Edge<E>] {
114 pub fn len_edges(&self) -> usize {
118 // # Node construction
120 pub fn next_node_index(&self) -> NodeIndex {
121 NodeIndex(self.nodes.len())
124 pub fn add_node(&mut self, data: N) -> NodeIndex {
125 let idx = self.next_node_index();
126 self.nodes.push(Node { first_edge: [INVALID_EDGE_INDEX, INVALID_EDGE_INDEX], data });
130 pub fn mut_node_data(&mut self, idx: NodeIndex) -> &mut N {
131 &mut self.nodes[idx.0].data
134 pub fn node_data(&self, idx: NodeIndex) -> &N {
135 &self.nodes[idx.0].data
138 pub fn node(&self, idx: NodeIndex) -> &Node<N> {
142 // # Edge construction and queries
144 pub fn next_edge_index(&self) -> EdgeIndex {
145 EdgeIndex(self.edges.len())
148 pub fn add_edge(&mut self, source: NodeIndex, target: NodeIndex, data: E) -> EdgeIndex {
149 debug!("graph: add_edge({:?}, {:?}, {:?})", source, target, data);
151 let idx = self.next_edge_index();
153 // read current first of the list of edges from each node
154 let source_first = self.nodes[source.0].first_edge[OUTGOING.repr];
155 let target_first = self.nodes[target.0].first_edge[INCOMING.repr];
157 // create the new edge, with the previous firsts from each node
158 // as the next pointers
159 self.edges.push(Edge { next_edge: [source_first, target_first], source, target, data });
161 // adjust the firsts for each node target be the next object.
162 self.nodes[source.0].first_edge[OUTGOING.repr] = idx;
163 self.nodes[target.0].first_edge[INCOMING.repr] = idx;
168 pub fn edge(&self, idx: EdgeIndex) -> &Edge<E> {
172 // # Iterating over nodes, edges
174 pub fn enumerated_nodes(&self) -> impl Iterator<Item = (NodeIndex, &Node<N>)> {
175 self.nodes.iter().enumerate().map(|(idx, n)| (NodeIndex(idx), n))
178 pub fn enumerated_edges(&self) -> impl Iterator<Item = (EdgeIndex, &Edge<E>)> {
179 self.edges.iter().enumerate().map(|(idx, e)| (EdgeIndex(idx), e))
182 pub fn each_node<'a>(&'a self, mut f: impl FnMut(NodeIndex, &'a Node<N>) -> bool) -> bool {
183 //! Iterates over all edges defined in the graph.
184 self.enumerated_nodes().all(|(node_idx, node)| f(node_idx, node))
187 pub fn each_edge<'a>(&'a self, mut f: impl FnMut(EdgeIndex, &'a Edge<E>) -> bool) -> bool {
188 //! Iterates over all edges defined in the graph
189 self.enumerated_edges().all(|(edge_idx, edge)| f(edge_idx, edge))
192 pub fn outgoing_edges(&self, source: NodeIndex) -> AdjacentEdges<'_, N, E> {
193 self.adjacent_edges(source, OUTGOING)
196 pub fn incoming_edges(&self, source: NodeIndex) -> AdjacentEdges<'_, N, E> {
197 self.adjacent_edges(source, INCOMING)
200 pub fn adjacent_edges(
203 direction: Direction,
204 ) -> AdjacentEdges<'_, N, E> {
205 let first_edge = self.node(source).first_edge[direction.repr];
206 AdjacentEdges { graph: self, direction, next: first_edge }
209 pub fn successor_nodes<'a>(
212 ) -> impl Iterator<Item = NodeIndex> + 'a {
213 self.outgoing_edges(source).targets()
216 pub fn predecessor_nodes<'a>(
219 ) -> impl Iterator<Item = NodeIndex> + 'a {
220 self.incoming_edges(target).sources()
223 pub fn depth_traverse(
226 direction: Direction,
227 ) -> DepthFirstTraversal<'_, N, E> {
228 DepthFirstTraversal::with_start_node(self, start, direction)
231 pub fn nodes_in_postorder(
233 direction: Direction,
234 entry_node: NodeIndex,
235 ) -> Vec<NodeIndex> {
236 let mut visited = BitSet::new_empty(self.len_nodes());
237 let mut stack = vec![];
238 let mut result = Vec::with_capacity(self.len_nodes());
239 let mut push_node = |stack: &mut Vec<_>, node: NodeIndex| {
240 if visited.insert(node.0) {
241 stack.push((node, self.adjacent_edges(node, direction)));
246 Some(entry_node).into_iter().chain(self.enumerated_nodes().map(|(node, _)| node))
248 push_node(&mut stack, node);
249 while let Some((node, mut iter)) = stack.pop() {
250 if let Some((_, child)) = iter.next() {
251 let target = child.source_or_target(direction);
252 // the current node needs more processing, so
253 // add it back to the stack
254 stack.push((node, iter));
255 // and then push the new node
256 push_node(&mut stack, target);
263 assert_eq!(result.len(), self.len_nodes());
270 pub struct AdjacentEdges<'g, N, E> {
271 graph: &'g Graph<N, E>,
272 direction: Direction,
276 impl<'g, N: Debug, E: Debug> AdjacentEdges<'g, N, E> {
277 fn targets(self) -> impl Iterator<Item = NodeIndex> + 'g {
278 self.map(|(_, edge)| edge.target)
281 fn sources(self) -> impl Iterator<Item = NodeIndex> + 'g {
282 self.map(|(_, edge)| edge.source)
286 impl<'g, N: Debug, E: Debug> Iterator for AdjacentEdges<'g, N, E> {
287 type Item = (EdgeIndex, &'g Edge<E>);
289 fn next(&mut self) -> Option<(EdgeIndex, &'g Edge<E>)> {
290 let edge_index = self.next;
291 if edge_index == INVALID_EDGE_INDEX {
295 let edge = self.graph.edge(edge_index);
296 self.next = edge.next_edge[self.direction.repr];
297 Some((edge_index, edge))
300 fn size_hint(&self) -> (usize, Option<usize>) {
301 // At most, all the edges in the graph.
302 (0, Some(self.graph.len_edges()))
306 pub struct DepthFirstTraversal<'g, N, E> {
307 graph: &'g Graph<N, E>,
308 stack: Vec<NodeIndex>,
309 visited: BitSet<usize>,
310 direction: Direction,
313 impl<'g, N: Debug, E: Debug> DepthFirstTraversal<'g, N, E> {
314 pub fn with_start_node(
315 graph: &'g Graph<N, E>,
316 start_node: NodeIndex,
317 direction: Direction,
319 let mut visited = BitSet::new_empty(graph.len_nodes());
320 visited.insert(start_node.node_id());
321 DepthFirstTraversal { graph, stack: vec![start_node], visited, direction }
324 fn visit(&mut self, node: NodeIndex) {
325 if self.visited.insert(node.node_id()) {
326 self.stack.push(node);
331 impl<'g, N: Debug, E: Debug> Iterator for DepthFirstTraversal<'g, N, E> {
332 type Item = NodeIndex;
334 fn next(&mut self) -> Option<NodeIndex> {
335 let next = self.stack.pop();
336 if let Some(idx) = next {
337 for (_, edge) in self.graph.adjacent_edges(idx, self.direction) {
338 let target = edge.source_or_target(self.direction);
345 fn size_hint(&self) -> (usize, Option<usize>) {
346 // We will visit every node in the graph exactly once.
347 let remaining = self.graph.len_nodes() - self.visited.count();
348 (remaining, Some(remaining))
352 impl<'g, N: Debug, E: Debug> ExactSizeIterator for DepthFirstTraversal<'g, N, E> {}
355 pub fn source(&self) -> NodeIndex {
359 pub fn target(&self) -> NodeIndex {
363 pub fn source_or_target(&self, direction: Direction) -> NodeIndex {
364 if direction == OUTGOING { self.target } else { self.source }