1 // Copyright 2015 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 use bitvec::BitMatrix;
12 use std::cell::RefCell;
17 pub struct TransitiveRelation<T:Debug+PartialEq> {
18 // List of elements. This is used to map from a T to a usize. We
19 // expect domain to be small so just use a linear list versus a
20 // hashmap or something.
23 // List of base edges in the graph. Require to compute transitive
27 // This is a cached transitive closure derived from the edges.
28 // Currently, we build it lazilly and just throw out any existing
29 // copy whenever a new edge is added. (The RefCell is to permit
30 // the lazy computation.) This is kind of silly, except for the
31 // fact its size is tied to `self.elements.len()`, so I wanted to
32 // wait before building it up to avoid reallocating as new edges
33 // are added with new elements. Perhaps better would be to ask the
34 // user for a batch of edges to minimize this effect, but I
35 // already wrote the code this way. :P -nmatsakis
36 closure: RefCell<Option<BitMatrix>>
39 #[derive(Clone, PartialEq, PartialOrd)]
42 #[derive(Clone, PartialEq)]
48 impl<T:Debug+PartialEq> TransitiveRelation<T> {
49 pub fn new() -> TransitiveRelation<T> {
50 TransitiveRelation { elements: vec![],
52 closure: RefCell::new(None) }
55 fn index(&self, a: &T) -> Option<Index> {
56 self.elements.iter().position(|e| *e == *a).map(Index)
59 fn add_index(&mut self, a: T) -> Index {
60 match self.index(&a) {
63 self.elements.push(a);
65 // if we changed the dimensions, clear the cache
66 *self.closure.borrow_mut() = None;
68 Index(self.elements.len() - 1)
73 /// Indicate that `a < b` (where `<` is this relation)
74 pub fn add(&mut self, a: T, b: T) {
75 let a = self.add_index(a);
76 let b = self.add_index(b);
77 let edge = Edge { source: a, target: b };
78 if !self.edges.contains(&edge) {
79 self.edges.push(edge);
81 // added an edge, clear the cache
82 *self.closure.borrow_mut() = None;
86 /// Check whether `a < target` (transitively)
87 pub fn contains(&self, a: &T, b: &T) -> bool {
88 match (self.index(a), self.index(b)) {
90 self.with_closure(|closure| closure.contains(a.0, b.0)),
91 (None, _) | (_, None) =>
96 /// Picks what I am referring to as the "postdominating"
97 /// upper-bound for `a` and `b`. This is usually the least upper
98 /// bound, but in cases where there is no single least upper
99 /// bound, it is the "mutual immediate postdominator", if you
100 /// imagine a graph where `a < b` means `a -> b`.
102 /// This function is needed because region inference currently
103 /// requires that we produce a single "UB", and there is no best
104 /// choice for the LUB. Rather than pick arbitrarily, I pick a
105 /// less good, but predictable choice. This should help ensure
106 /// that region inference yields predictable results (though it
107 /// itself is not fully sufficient).
109 /// Examples are probably clearer than any prose I could write
110 /// (there are corresponding tests below, btw). In each case,
111 /// the query is `postdom_upper_bound(a, b)`:
114 /// // returns Some(x), which is also LUB
120 /// // returns Some(x), which is not LUB (there is none)
121 /// // diagonal edges run left-to-right
131 pub fn postdom_upper_bound(&self, a: &T, b: &T) -> Option<&T> {
132 let mut mubs = self.minimal_upper_bounds(a, b);
136 1 => return Some(mubs[0]),
138 let m = mubs.pop().unwrap();
139 let n = mubs.pop().unwrap();
140 mubs.extend(self.minimal_upper_bounds(n, m));
146 /// Returns the set of bounds `X` such that:
148 /// - `a < X` and `b < X`
149 /// - there is no `Y != X` such that `a < Y` and `Y < X`
150 /// - except for the case where `X < a` (i.e., a strongly connected
151 /// component in the graph). In that case, the smallest
152 /// representative of the SCC is returned (as determined by the
153 /// internal indices).
155 /// Note that this set can, in principle, have any size.
156 pub fn minimal_upper_bounds(&self, a: &T, b: &T) -> Vec<&T> {
157 let (mut a, mut b) = match (self.index(a), self.index(b)) {
158 (Some(a), Some(b)) => (a, b),
159 (None, _) | (_, None) => { return vec![]; }
162 // in some cases, there are some arbitrary choices to be made;
163 // it doesn't really matter what we pick, as long as we pick
164 // the same thing consistently when queried, so ensure that
165 // (a, b) are in a consistent relative order
167 mem::swap(&mut a, &mut b);
170 let lub_indices = self.with_closure(|closure| {
171 // Easy case is when either a < b or b < a:
172 if closure.contains(a.0, b.0) {
175 if closure.contains(b.0, a.0) {
179 // Otherwise, the tricky part is that there may be some c
180 // where a < c and b < c. In fact, there may be many such
181 // values. So here is what we do:
183 // 1. Find the vector `[X | a < X && b < X]` of all values
184 // `X` where `a < X` and `b < X`. In terms of the
185 // graph, this means all values reachable from both `a`
186 // and `b`. Note that this vector is also a set, but we
187 // use the term vector because the order matters
188 // to the steps below.
189 // - This vector contains upper bounds, but they are
190 // not minimal upper bounds. So you may have e.g.
191 // `[x, y, tcx, z]` where `x < tcx` and `y < tcx` and
192 // `z < x` and `z < y`:
194 // z --+---> x ----+----> tcx
199 // In this case, we really want to return just `[z]`.
200 // The following steps below achieve this by gradually
201 // reducing the list.
202 // 2. Pare down the vector using `pare_down`. This will
203 // remove elements from the vector that can be reached
204 // by an earlier element.
205 // - In the example above, this would convert `[x, y,
206 // tcx, z]` to `[x, y, z]`. Note that `x` and `y` are
207 // still in the vector; this is because while `z < x`
208 // (and `z < y`) holds, `z` comes after them in the
210 // 3. Reverse the vector and repeat the pare down process.
211 // - In the example above, we would reverse to
212 // `[z, y, x]` and then pare down to `[z]`.
213 // 4. Reverse once more just so that we yield a vector in
214 // increasing order of index. Not necessary, but why not.
216 // I believe this algorithm yields a minimal set. The
217 // argument is that, after step 2, we know that no element
218 // can reach its successors (in the vector, not the graph).
219 // After step 3, we know that no element can reach any of
220 // its predecesssors (because of step 2) nor successors
221 // (because we just called `pare_down`)
223 let mut candidates = closure.intersection(a.0, b.0); // (1)
224 pare_down(&mut candidates, closure); // (2)
225 candidates.reverse(); // (3a)
226 pare_down(&mut candidates, closure); // (3b)
230 lub_indices.into_iter()
232 .map(|i| &self.elements[i])
236 fn with_closure<OP,R>(&self, op: OP) -> R
237 where OP: FnOnce(&BitMatrix) -> R
239 let mut closure_cell = self.closure.borrow_mut();
240 let mut closure = closure_cell.take();
241 if closure.is_none() {
242 closure = Some(self.compute_closure());
244 let result = op(closure.as_ref().unwrap());
245 *closure_cell = closure;
249 fn compute_closure(&self) -> BitMatrix {
250 let mut matrix = BitMatrix::new(self.elements.len());
251 let mut changed = true;
254 for edge in self.edges.iter() {
255 // add an edge from S -> T
256 changed |= matrix.add(edge.source.0, edge.target.0);
258 // add all outgoing edges from T into S
259 changed |= matrix.merge(edge.target.0, edge.source.0);
266 /// Pare down is used as a step in the LUB computation. It edits the
267 /// candidates array in place by removing any element j for which
268 /// there exists an earlier element i<j such that i -> j. That is,
269 /// after you run `pare_down`, you know that for all elements that
270 /// remain in candidates, they cannot reach any of the elements that
273 /// Examples follow. Assume that a -> b -> c and x -> y -> z.
275 /// - Input: `[a, b, x]`. Output: `[a, x]`.
276 /// - Input: `[b, a, x]`. Output: `[b, a, x]`.
277 /// - Input: `[a, x, b, y]`. Output: `[a, x]`.
278 fn pare_down(candidates: &mut Vec<usize>, closure: &BitMatrix) {
280 while i < candidates.len() {
281 let candidate_i = candidates[i];
286 while j < candidates.len() {
287 let candidate_j = candidates[j];
288 if closure.contains(candidate_i, candidate_j) {
289 // If `i` can reach `j`, then we can remove `j`. So just
290 // mark it as dead and move on; subsequent indices will be
291 // shifted into its place.
294 candidates[j - dead] = candidate_j;
298 candidates.truncate(j - dead);
304 let mut relation = TransitiveRelation::new();
305 relation.add("a", "b");
306 relation.add("a", "c");
307 assert!(relation.contains(&"a", &"c"));
308 assert!(relation.contains(&"a", &"b"));
309 assert!(!relation.contains(&"b", &"a"));
310 assert!(!relation.contains(&"a", &"d"));
314 fn test_many_steps() {
315 let mut relation = TransitiveRelation::new();
316 relation.add("a", "b");
317 relation.add("a", "c");
318 relation.add("a", "f");
320 relation.add("b", "c");
321 relation.add("b", "d");
322 relation.add("b", "e");
324 relation.add("e", "g");
326 assert!(relation.contains(&"a", &"b"));
327 assert!(relation.contains(&"a", &"c"));
328 assert!(relation.contains(&"a", &"d"));
329 assert!(relation.contains(&"a", &"e"));
330 assert!(relation.contains(&"a", &"f"));
331 assert!(relation.contains(&"a", &"g"));
333 assert!(relation.contains(&"b", &"g"));
335 assert!(!relation.contains(&"a", &"x"));
336 assert!(!relation.contains(&"b", &"f"));
341 let mut relation = TransitiveRelation::new();
342 relation.add("a", "tcx");
343 relation.add("b", "tcx");
344 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"tcx"]);
348 fn mubs_best_choice1() {
356 // This tests a particular state in the algorithm, in which we
357 // need the second pare down call to get the right result (after
358 // intersection, we have [1, 2], but 2 -> 1).
360 let mut relation = TransitiveRelation::new();
361 relation.add("0", "1");
362 relation.add("0", "2");
364 relation.add("2", "1");
366 relation.add("3", "1");
367 relation.add("3", "2");
369 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"2"]);
373 fn mubs_best_choice2() {
381 // Like the precedecing test, but in this case intersection is [2,
382 // 1], and hence we rely on the first pare down call.
384 let mut relation = TransitiveRelation::new();
385 relation.add("0", "1");
386 relation.add("0", "2");
388 relation.add("1", "2");
390 relation.add("3", "1");
391 relation.add("3", "2");
393 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1"]);
397 fn mubs_no_best_choice() {
398 // in this case, the intersection yields [1, 2], and the "pare
399 // down" calls find nothing to remove.
400 let mut relation = TransitiveRelation::new();
401 relation.add("0", "1");
402 relation.add("0", "2");
404 relation.add("3", "1");
405 relation.add("3", "2");
407 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1", &"2"]);
411 fn mubs_best_choice_scc() {
412 let mut relation = TransitiveRelation::new();
413 relation.add("0", "1");
414 relation.add("0", "2");
416 relation.add("1", "2");
417 relation.add("2", "1");
419 relation.add("3", "1");
420 relation.add("3", "2");
422 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1"]);
426 fn pdub_crisscross() {
427 // diagonal edges run left-to-right
433 let mut relation = TransitiveRelation::new();
434 relation.add("a", "a1");
435 relation.add("a", "b1");
436 relation.add("b", "a1");
437 relation.add("b", "b1");
438 relation.add("a1", "x");
439 relation.add("b1", "x");
441 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"a1", &"b1"]);
442 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
446 fn pdub_crisscross_more() {
447 // diagonal edges run left-to-right
448 // a -> a1 -> a2 -> a3 -> x
451 // b -> b1 -> b2 ---------+
453 let mut relation = TransitiveRelation::new();
454 relation.add("a", "a1");
455 relation.add("a", "b1");
456 relation.add("b", "a1");
457 relation.add("b", "b1");
459 relation.add("a1", "a2");
460 relation.add("a1", "b2");
461 relation.add("b1", "a2");
462 relation.add("b1", "b2");
464 relation.add("a2", "a3");
466 relation.add("a3", "x");
467 relation.add("b2", "x");
469 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"a1", &"b1"]);
470 assert_eq!(relation.minimal_upper_bounds(&"a1", &"b1"), vec![&"a2", &"b2"]);
471 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
481 let mut relation = TransitiveRelation::new();
482 relation.add("a", "a1");
483 relation.add("b", "b1");
484 relation.add("a1", "x");
485 relation.add("b1", "x");
487 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"x"]);
488 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
492 fn mubs_intermediate_node_on_one_side_only() {
498 // "digraph { a -> c -> d; b -> d; }",
499 let mut relation = TransitiveRelation::new();
500 relation.add("a", "c");
501 relation.add("c", "d");
502 relation.add("b", "d");
504 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"d"]);
517 // "digraph { a -> c -> d; d -> c; a -> d; b -> d; }",
518 let mut relation = TransitiveRelation::new();
519 relation.add("a", "c");
520 relation.add("c", "d");
521 relation.add("d", "c");
522 relation.add("a", "d");
523 relation.add("b", "d");
525 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
537 // "digraph { a -> c -> d; d -> c; b -> d; b -> c; }",
538 let mut relation = TransitiveRelation::new();
539 relation.add("a", "c");
540 relation.add("c", "d");
541 relation.add("d", "c");
542 relation.add("b", "d");
543 relation.add("b", "c");
545 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
557 // "digraph { a -> c -> d -> e -> c; b -> d; b -> e; }",
558 let mut relation = TransitiveRelation::new();
559 relation.add("a", "c");
560 relation.add("c", "d");
561 relation.add("d", "e");
562 relation.add("e", "c");
563 relation.add("b", "d");
564 relation.add("b", "e");
566 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
579 // "digraph { a -> c -> d -> e -> c; a -> d; b -> e; }"
580 let mut relation = TransitiveRelation::new();
581 relation.add("a", "c");
582 relation.add("c", "d");
583 relation.add("d", "e");
584 relation.add("e", "c");
585 relation.add("a", "d");
586 relation.add("b", "e");
588 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);