1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A graph module for use in dataflow, region resolution, and elsewhere.
13 //! # Interface details
15 //! You customize the graph by specifying a "node data" type `N` and an
16 //! "edge data" type `E`. You can then later gain access (mutable or
17 //! immutable) to these "user-data" bits. Currently, you can only add
18 //! nodes or edges to the graph. You cannot remove or modify them once
19 //! added. This could be changed if we have a need.
21 //! # Implementation details
23 //! The main tricky thing about this code is the way that edges are
24 //! stored. The edges are stored in a central array, but they are also
25 //! threaded onto two linked lists for each node, one for incoming edges
26 //! and one for outgoing edges. Note that every edge is a member of some
27 //! incoming list and some outgoing list. Basically you can load the
28 //! first index of the linked list from the node data structures (the
29 //! field `first_edge`) and then, for each edge, load the next index from
30 //! the field `next_edge`). Each of those fields is an array that should
31 //! be indexed by the direction (see the type `Direction`).
33 #![allow(dead_code)] // still WIP
35 use std::fmt::{Formatter, Error, Show};
38 pub struct Graph<N,E> {
44 first_edge: [EdgeIndex, ..2], // see module comment
49 next_edge: [EdgeIndex, ..2], // see module comment
55 impl<E: Show> Show for Edge<E> {
56 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
57 write!(f, "Edge {{ next_edge: [{}, {}], source: {}, target: {}, data: {} }}",
58 self.next_edge[0], self.next_edge[1], self.source,
59 self.target, self.data)
63 #[deriving(Clone, Copy, PartialEq, Show)]
64 pub struct NodeIndex(pub uint);
65 #[allow(non_upper_case_globals)]
66 pub const InvalidNodeIndex: NodeIndex = NodeIndex(uint::MAX);
68 #[deriving(Copy, PartialEq, Show)]
69 pub struct EdgeIndex(pub uint);
70 #[allow(non_upper_case_globals)]
71 pub const InvalidEdgeIndex: EdgeIndex = EdgeIndex(uint::MAX);
73 // Use a private field here to guarantee no more instances are created:
74 #[deriving(Copy, Show)]
75 pub struct Direction { repr: uint }
76 #[allow(non_upper_case_globals)]
77 pub const Outgoing: Direction = Direction { repr: 0 };
78 #[allow(non_upper_case_globals)]
79 pub const Incoming: Direction = Direction { repr: 1 };
82 fn get(&self) -> uint { let NodeIndex(v) = *self; v }
83 /// Returns unique id (unique with respect to the graph holding associated node).
84 pub fn node_id(&self) -> uint { self.get() }
88 fn get(&self) -> uint { let EdgeIndex(v) = *self; v }
89 /// Returns unique id (unique with respect to the graph holding associated edge).
90 pub fn edge_id(&self) -> uint { self.get() }
93 impl<N,E> Graph<N,E> {
94 pub fn new() -> Graph<N,E> {
101 pub fn with_capacity(num_nodes: uint,
102 num_edges: uint) -> Graph<N,E> {
104 nodes: Vec::with_capacity(num_nodes),
105 edges: Vec::with_capacity(num_edges),
109 ///////////////////////////////////////////////////////////////////////////
113 pub fn all_nodes<'a>(&'a self) -> &'a [Node<N>] {
114 let nodes: &'a [Node<N>] = self.nodes.as_slice();
119 pub fn all_edges<'a>(&'a self) -> &'a [Edge<E>] {
120 let edges: &'a [Edge<E>] = self.edges.as_slice();
124 ///////////////////////////////////////////////////////////////////////////
127 pub fn next_node_index(&self) -> NodeIndex {
128 NodeIndex(self.nodes.len())
131 pub fn add_node(&mut self, data: N) -> NodeIndex {
132 let idx = self.next_node_index();
133 self.nodes.push(Node {
134 first_edge: [InvalidEdgeIndex, InvalidEdgeIndex],
140 pub fn mut_node_data<'a>(&'a mut self, idx: NodeIndex) -> &'a mut N {
141 &mut self.nodes[idx.get()].data
144 pub fn node_data<'a>(&'a self, idx: NodeIndex) -> &'a N {
145 &self.nodes[idx.get()].data
148 pub fn node<'a>(&'a self, idx: NodeIndex) -> &'a Node<N> {
149 &self.nodes[idx.get()]
152 ///////////////////////////////////////////////////////////////////////////
153 // Edge construction and queries
155 pub fn next_edge_index(&self) -> EdgeIndex {
156 EdgeIndex(self.edges.len())
159 pub fn add_edge(&mut self,
162 data: E) -> EdgeIndex {
163 let idx = self.next_edge_index();
165 // read current first of the list of edges from each node
166 let source_first = self.nodes[source.get()]
167 .first_edge[Outgoing.repr];
168 let target_first = self.nodes[target.get()]
169 .first_edge[Incoming.repr];
171 // create the new edge, with the previous firsts from each node
172 // as the next pointers
173 self.edges.push(Edge {
174 next_edge: [source_first, target_first],
180 // adjust the firsts for each node target be the next object.
181 self.nodes[source.get()].first_edge[Outgoing.repr] = idx;
182 self.nodes[target.get()].first_edge[Incoming.repr] = idx;
187 pub fn mut_edge_data<'a>(&'a mut self, idx: EdgeIndex) -> &'a mut E {
188 &mut self.edges[idx.get()].data
191 pub fn edge_data<'a>(&'a self, idx: EdgeIndex) -> &'a E {
192 &self.edges[idx.get()].data
195 pub fn edge<'a>(&'a self, idx: EdgeIndex) -> &'a Edge<E> {
196 &self.edges[idx.get()]
199 pub fn first_adjacent(&self, node: NodeIndex, dir: Direction) -> EdgeIndex {
200 //! Accesses the index of the first edge adjacent to `node`.
201 //! This is useful if you wish to modify the graph while walking
202 //! the linked list of edges.
204 self.nodes[node.get()].first_edge[dir.repr]
207 pub fn next_adjacent(&self, edge: EdgeIndex, dir: Direction) -> EdgeIndex {
208 //! Accesses the next edge in a given direction.
209 //! This is useful if you wish to modify the graph while walking
210 //! the linked list of edges.
212 self.edges[edge.get()].next_edge[dir.repr]
215 ///////////////////////////////////////////////////////////////////////////
216 // Iterating over nodes, edges
218 pub fn each_node<'a, F>(&'a self, mut f: F) -> bool where
219 F: FnMut(NodeIndex, &'a Node<N>) -> bool,
221 //! Iterates over all edges defined in the graph.
222 self.nodes.iter().enumerate().all(|(i, node)| f(NodeIndex(i), node))
225 pub fn each_edge<'a, F>(&'a self, mut f: F) -> bool where
226 F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
228 //! Iterates over all edges defined in the graph
229 self.edges.iter().enumerate().all(|(i, edge)| f(EdgeIndex(i), edge))
232 pub fn each_outgoing_edge<'a, F>(&'a self, source: NodeIndex, f: F) -> bool where
233 F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
235 //! Iterates over all outgoing edges from the node `from`
237 self.each_adjacent_edge(source, Outgoing, f)
240 pub fn each_incoming_edge<'a, F>(&'a self, target: NodeIndex, f: F) -> bool where
241 F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
243 //! Iterates over all incoming edges to the node `target`
245 self.each_adjacent_edge(target, Incoming, f)
248 pub fn each_adjacent_edge<'a, F>(&'a self,
253 F: FnMut(EdgeIndex, &'a Edge<E>) -> bool,
255 //! Iterates over all edges adjacent to the node `node`
256 //! in the direction `dir` (either `Outgoing` or `Incoming)
258 let mut edge_idx = self.first_adjacent(node, dir);
259 while edge_idx != InvalidEdgeIndex {
260 let edge = &self.edges[edge_idx.get()];
261 if !f(edge_idx, edge) {
264 edge_idx = edge.next_edge[dir.repr];
269 ///////////////////////////////////////////////////////////////////////////
270 // Fixed-point iteration
272 // A common use for graphs in our compiler is to perform
273 // fixed-point iteration. In this case, each edge represents a
274 // constraint, and the nodes themselves are associated with
275 // variables or other bitsets. This method facilitates such a
278 pub fn iterate_until_fixed_point<'a, F>(&'a self, mut op: F) where
279 F: FnMut(uint, EdgeIndex, &'a Edge<E>) -> bool,
281 let mut iteration = 0;
282 let mut changed = true;
286 for (i, edge) in self.edges.iter().enumerate() {
287 changed |= op(iteration, EdgeIndex(i), edge);
293 pub fn each_edge_index<F>(max_edge_index: EdgeIndex, mut f: F) where
294 F: FnMut(EdgeIndex) -> bool,
297 let n = max_edge_index.get();
299 if !f(EdgeIndex(i)) {
307 pub fn source(&self) -> NodeIndex {
311 pub fn target(&self) -> NodeIndex {
318 use middle::graph::*;
321 type TestNode = Node<&'static str>;
322 type TestEdge = Edge<&'static str>;
323 type TestGraph = Graph<&'static str, &'static str>;
325 fn create_graph() -> TestGraph {
326 let mut graph = Graph::new();
328 // Create a simple graph
335 let a = graph.add_node("A");
336 let b = graph.add_node("B");
337 let c = graph.add_node("C");
338 let d = graph.add_node("D");
339 let e = graph.add_node("E");
340 let f = graph.add_node("F");
342 graph.add_edge(a, b, "AB");
343 graph.add_edge(b, c, "BC");
344 graph.add_edge(b, d, "BD");
345 graph.add_edge(d, e, "DE");
346 graph.add_edge(e, c, "EC");
347 graph.add_edge(f, b, "FB");
354 let graph = create_graph();
355 let expected = ["A", "B", "C", "D", "E", "F"];
356 graph.each_node(|idx, node| {
357 assert_eq!(&expected[idx.get()], graph.node_data(idx));
358 assert_eq!(expected[idx.get()], node.data);
365 let graph = create_graph();
366 let expected = ["AB", "BC", "BD", "DE", "EC", "FB"];
367 graph.each_edge(|idx, edge| {
368 assert_eq!(&expected[idx.get()], graph.edge_data(idx));
369 assert_eq!(expected[idx.get()], edge.data);
374 fn test_adjacent_edges<N:PartialEq+Show,E:PartialEq+Show>(graph: &Graph<N,E>,
375 start_index: NodeIndex,
377 expected_incoming: &[(E,N)],
378 expected_outgoing: &[(E,N)]) {
379 assert!(graph.node_data(start_index) == &start_data);
382 graph.each_incoming_edge(start_index, |edge_index, edge| {
383 assert!(graph.edge_data(edge_index) == &edge.data);
384 assert!(counter < expected_incoming.len());
385 debug!("counter={} expected={} edge_index={} edge={}",
386 counter, expected_incoming[counter], edge_index, edge);
387 match expected_incoming[counter] {
389 assert!(e == &edge.data);
390 assert!(n == graph.node_data(edge.source));
391 assert!(start_index == edge.target);
397 assert_eq!(counter, expected_incoming.len());
400 graph.each_outgoing_edge(start_index, |edge_index, edge| {
401 assert!(graph.edge_data(edge_index) == &edge.data);
402 assert!(counter < expected_outgoing.len());
403 debug!("counter={} expected={} edge_index={} edge={}",
404 counter, expected_outgoing[counter], edge_index, edge);
405 match expected_outgoing[counter] {
407 assert!(e == &edge.data);
408 assert!(start_index == edge.source);
409 assert!(n == graph.node_data(edge.target));
415 assert_eq!(counter, expected_outgoing.len());
419 fn each_adjacent_from_a() {
420 let graph = create_graph();
421 test_adjacent_edges(&graph, NodeIndex(0), "A",
427 fn each_adjacent_from_b() {
428 let graph = create_graph();
429 test_adjacent_edges(&graph, NodeIndex(1), "B",
430 &[("FB", "F"), ("AB", "A"),],
431 &[("BD", "D"), ("BC", "C"),]);
435 fn each_adjacent_from_c() {
436 let graph = create_graph();
437 test_adjacent_edges(&graph, NodeIndex(2), "C",
438 &[("EC", "E"), ("BC", "B")],
443 fn each_adjacent_from_d() {
444 let graph = create_graph();
445 test_adjacent_edges(&graph, NodeIndex(3), "D",