]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/transitive_relation.rs
add `#[rustc_pass_by_value]` to more types
[rust.git] / compiler / rustc_data_structures / src / transitive_relation.rs
1 use crate::fx::FxIndexSet;
2 use crate::sync::Lock;
3 use rustc_index::bit_set::BitMatrix;
4 use std::fmt::Debug;
5 use std::hash::Hash;
6 use std::mem;
7
8 #[cfg(test)]
9 mod tests;
10
11 #[derive(Clone, Debug)]
12 pub struct TransitiveRelation<T> {
13     // List of elements. This is used to map from a T to a usize.
14     elements: FxIndexSet<T>,
15
16     // List of base edges in the graph. Require to compute transitive
17     // closure.
18     edges: Vec<Edge>,
19
20     // This is a cached transitive closure derived from the edges.
21     // Currently, we build it lazily and just throw out any existing
22     // copy whenever a new edge is added. (The Lock is to permit
23     // the lazy computation.) This is kind of silly, except for the
24     // fact its size is tied to `self.elements.len()`, so I wanted to
25     // wait before building it up to avoid reallocating as new edges
26     // are added with new elements. Perhaps better would be to ask the
27     // user for a batch of edges to minimize this effect, but I
28     // already wrote the code this way. :P -nmatsakis
29     closure: Lock<Option<BitMatrix<usize, usize>>>,
30 }
31
32 // HACK(eddyb) manual impl avoids `Default` bound on `T`.
33 impl<T: Eq + Hash> Default for TransitiveRelation<T> {
34     fn default() -> Self {
35         TransitiveRelation {
36             elements: Default::default(),
37             edges: Default::default(),
38             closure: Default::default(),
39         }
40     }
41 }
42
43 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Debug)]
44 struct Index(usize);
45
46 #[derive(Clone, PartialEq, Eq, Debug)]
47 struct Edge {
48     source: Index,
49     target: Index,
50 }
51
52 impl<T: Eq + Hash + Copy> TransitiveRelation<T> {
53     pub fn is_empty(&self) -> bool {
54         self.edges.is_empty()
55     }
56
57     pub fn elements(&self) -> impl Iterator<Item = &T> {
58         self.elements.iter()
59     }
60
61     fn index(&self, a: T) -> Option<Index> {
62         self.elements.get_index_of(&a).map(Index)
63     }
64
65     fn add_index(&mut self, a: T) -> Index {
66         let (index, added) = self.elements.insert_full(a);
67         if added {
68             // if we changed the dimensions, clear the cache
69             *self.closure.get_mut() = None;
70         }
71         Index(index)
72     }
73
74     /// Applies the (partial) function to each edge and returns a new
75     /// relation. If `f` returns `None` for any end-point, returns
76     /// `None`.
77     pub fn maybe_map<F, U>(&self, mut f: F) -> Option<TransitiveRelation<U>>
78     where
79         F: FnMut(T) -> Option<U>,
80         U: Clone + Debug + Eq + Hash + Copy,
81     {
82         let mut result = TransitiveRelation::default();
83         for edge in &self.edges {
84             result.add(f(self.elements[edge.source.0])?, f(self.elements[edge.target.0])?);
85         }
86         Some(result)
87     }
88
89     /// Indicate that `a < b` (where `<` is this relation)
90     pub fn add(&mut self, a: T, b: T) {
91         let a = self.add_index(a);
92         let b = self.add_index(b);
93         let edge = Edge { source: a, target: b };
94         if !self.edges.contains(&edge) {
95             self.edges.push(edge);
96
97             // added an edge, clear the cache
98             *self.closure.get_mut() = None;
99         }
100     }
101
102     /// Checks whether `a < target` (transitively)
103     pub fn contains(&self, a: T, b: T) -> bool {
104         match (self.index(a), self.index(b)) {
105             (Some(a), Some(b)) => self.with_closure(|closure| closure.contains(a.0, b.0)),
106             (None, _) | (_, None) => false,
107         }
108     }
109
110     /// Thinking of `x R y` as an edge `x -> y` in a graph, this
111     /// returns all things reachable from `a`.
112     ///
113     /// Really this probably ought to be `impl Iterator<Item = &T>`, but
114     /// I'm too lazy to make that work, and -- given the caching
115     /// strategy -- it'd be a touch tricky anyhow.
116     pub fn reachable_from(&self, a: T) -> Vec<T> {
117         match self.index(a) {
118             Some(a) => {
119                 self.with_closure(|closure| closure.iter(a.0).map(|i| self.elements[i]).collect())
120             }
121             None => vec![],
122         }
123     }
124
125     /// Picks what I am referring to as the "postdominating"
126     /// upper-bound for `a` and `b`. This is usually the least upper
127     /// bound, but in cases where there is no single least upper
128     /// bound, it is the "mutual immediate postdominator", if you
129     /// imagine a graph where `a < b` means `a -> b`.
130     ///
131     /// This function is needed because region inference currently
132     /// requires that we produce a single "UB", and there is no best
133     /// choice for the LUB. Rather than pick arbitrarily, I pick a
134     /// less good, but predictable choice. This should help ensure
135     /// that region inference yields predictable results (though it
136     /// itself is not fully sufficient).
137     ///
138     /// Examples are probably clearer than any prose I could write
139     /// (there are corresponding tests below, btw). In each case,
140     /// the query is `postdom_upper_bound(a, b)`:
141     ///
142     /// ```text
143     /// // Returns Some(x), which is also LUB.
144     /// a -> a1 -> x
145     ///            ^
146     ///            |
147     /// b -> b1 ---+
148     ///
149     /// // Returns `Some(x)`, which is not LUB (there is none)
150     /// // diagonal edges run left-to-right.
151     /// a -> a1 -> x
152     ///   \/       ^
153     ///   /\       |
154     /// b -> b1 ---+
155     ///
156     /// // Returns `None`.
157     /// a -> a1
158     /// b -> b1
159     /// ```
160     pub fn postdom_upper_bound(&self, a: T, b: T) -> Option<T> {
161         let mubs = self.minimal_upper_bounds(a, b);
162         self.mutual_immediate_postdominator(mubs)
163     }
164
165     /// Viewing the relation as a graph, computes the "mutual
166     /// immediate postdominator" of a set of points (if one
167     /// exists). See `postdom_upper_bound` for details.
168     pub fn mutual_immediate_postdominator<'a>(&'a self, mut mubs: Vec<T>) -> Option<T> {
169         loop {
170             match mubs.len() {
171                 0 => return None,
172                 1 => return Some(mubs[0]),
173                 _ => {
174                     let m = mubs.pop().unwrap();
175                     let n = mubs.pop().unwrap();
176                     mubs.extend(self.minimal_upper_bounds(n, m));
177                 }
178             }
179         }
180     }
181
182     /// Returns the set of bounds `X` such that:
183     ///
184     /// - `a < X` and `b < X`
185     /// - there is no `Y != X` such that `a < Y` and `Y < X`
186     ///   - except for the case where `X < a` (i.e., a strongly connected
187     ///     component in the graph). In that case, the smallest
188     ///     representative of the SCC is returned (as determined by the
189     ///     internal indices).
190     ///
191     /// Note that this set can, in principle, have any size.
192     pub fn minimal_upper_bounds(&self, a: T, b: T) -> Vec<T> {
193         let (Some(mut a), Some(mut b)) = (self.index(a), self.index(b)) else {
194             return vec![];
195         };
196
197         // in some cases, there are some arbitrary choices to be made;
198         // it doesn't really matter what we pick, as long as we pick
199         // the same thing consistently when queried, so ensure that
200         // (a, b) are in a consistent relative order
201         if a > b {
202             mem::swap(&mut a, &mut b);
203         }
204
205         let lub_indices = self.with_closure(|closure| {
206             // Easy case is when either a < b or b < a:
207             if closure.contains(a.0, b.0) {
208                 return vec![b.0];
209             }
210             if closure.contains(b.0, a.0) {
211                 return vec![a.0];
212             }
213
214             // Otherwise, the tricky part is that there may be some c
215             // where a < c and b < c. In fact, there may be many such
216             // values. So here is what we do:
217             //
218             // 1. Find the vector `[X | a < X && b < X]` of all values
219             //    `X` where `a < X` and `b < X`.  In terms of the
220             //    graph, this means all values reachable from both `a`
221             //    and `b`. Note that this vector is also a set, but we
222             //    use the term vector because the order matters
223             //    to the steps below.
224             //    - This vector contains upper bounds, but they are
225             //      not minimal upper bounds. So you may have e.g.
226             //      `[x, y, tcx, z]` where `x < tcx` and `y < tcx` and
227             //      `z < x` and `z < y`:
228             //
229             //           z --+---> x ----+----> tcx
230             //               |           |
231             //               |           |
232             //               +---> y ----+
233             //
234             //      In this case, we really want to return just `[z]`.
235             //      The following steps below achieve this by gradually
236             //      reducing the list.
237             // 2. Pare down the vector using `pare_down`. This will
238             //    remove elements from the vector that can be reached
239             //    by an earlier element.
240             //    - In the example above, this would convert `[x, y,
241             //      tcx, z]` to `[x, y, z]`. Note that `x` and `y` are
242             //      still in the vector; this is because while `z < x`
243             //      (and `z < y`) holds, `z` comes after them in the
244             //      vector.
245             // 3. Reverse the vector and repeat the pare down process.
246             //    - In the example above, we would reverse to
247             //      `[z, y, x]` and then pare down to `[z]`.
248             // 4. Reverse once more just so that we yield a vector in
249             //    increasing order of index. Not necessary, but why not.
250             //
251             // I believe this algorithm yields a minimal set. The
252             // argument is that, after step 2, we know that no element
253             // can reach its successors (in the vector, not the graph).
254             // After step 3, we know that no element can reach any of
255             // its predecessors (because of step 2) nor successors
256             // (because we just called `pare_down`)
257             //
258             // This same algorithm is used in `parents` below.
259
260             let mut candidates = closure.intersect_rows(a.0, b.0); // (1)
261             pare_down(&mut candidates, closure); // (2)
262             candidates.reverse(); // (3a)
263             pare_down(&mut candidates, closure); // (3b)
264             candidates
265         });
266
267         lub_indices
268             .into_iter()
269             .rev() // (4)
270             .map(|i| self.elements[i])
271             .collect()
272     }
273
274     /// Given an element A, returns the maximal set {B} of elements B
275     /// such that
276     ///
277     /// - A != B
278     /// - A R B is true
279     /// - for each i, j: `B[i]` R `B[j]` does not hold
280     ///
281     /// The intuition is that this moves "one step up" through a lattice
282     /// (where the relation is encoding the `<=` relation for the lattice).
283     /// So e.g., if the relation is `->` and we have
284     ///
285     /// ```
286     /// a -> b -> d -> f
287     /// |              ^
288     /// +--> c -> e ---+
289     /// ```
290     ///
291     /// then `parents(a)` returns `[b, c]`. The `postdom_parent` function
292     /// would further reduce this to just `f`.
293     pub fn parents(&self, a: T) -> Vec<T> {
294         let Some(a) = self.index(a) else {
295             return vec![];
296         };
297
298         // Steal the algorithm for `minimal_upper_bounds` above, but
299         // with a slight tweak. In the case where `a R a`, we remove
300         // that from the set of candidates.
301         let ancestors = self.with_closure(|closure| {
302             let mut ancestors = closure.intersect_rows(a.0, a.0);
303
304             // Remove anything that can reach `a`. If this is a
305             // reflexive relation, this will include `a` itself.
306             ancestors.retain(|&e| !closure.contains(e, a.0));
307
308             pare_down(&mut ancestors, closure); // (2)
309             ancestors.reverse(); // (3a)
310             pare_down(&mut ancestors, closure); // (3b)
311             ancestors
312         });
313
314         ancestors
315             .into_iter()
316             .rev() // (4)
317             .map(|i| self.elements[i])
318             .collect()
319     }
320
321     fn with_closure<OP, R>(&self, op: OP) -> R
322     where
323         OP: FnOnce(&BitMatrix<usize, usize>) -> R,
324     {
325         let mut closure_cell = self.closure.borrow_mut();
326         let mut closure = closure_cell.take();
327         if closure.is_none() {
328             closure = Some(self.compute_closure());
329         }
330         let result = op(closure.as_ref().unwrap());
331         *closure_cell = closure;
332         result
333     }
334
335     fn compute_closure(&self) -> BitMatrix<usize, usize> {
336         let mut matrix = BitMatrix::new(self.elements.len(), self.elements.len());
337         let mut changed = true;
338         while changed {
339             changed = false;
340             for edge in &self.edges {
341                 // add an edge from S -> T
342                 changed |= matrix.insert(edge.source.0, edge.target.0);
343
344                 // add all outgoing edges from T into S
345                 changed |= matrix.union_rows(edge.target.0, edge.source.0);
346             }
347         }
348         matrix
349     }
350
351     /// Lists all the base edges in the graph: the initial _non-transitive_ set of element
352     /// relations, which will be later used as the basis for the transitive closure computation.
353     pub fn base_edges(&self) -> impl Iterator<Item = (T, T)> + '_ {
354         self.edges
355             .iter()
356             .map(move |edge| (self.elements[edge.source.0], self.elements[edge.target.0]))
357     }
358 }
359
360 /// Pare down is used as a step in the LUB computation. It edits the
361 /// candidates array in place by removing any element j for which
362 /// there exists an earlier element i<j such that i -> j. That is,
363 /// after you run `pare_down`, you know that for all elements that
364 /// remain in candidates, they cannot reach any of the elements that
365 /// come after them.
366 ///
367 /// Examples follow. Assume that a -> b -> c and x -> y -> z.
368 ///
369 /// - Input: `[a, b, x]`. Output: `[a, x]`.
370 /// - Input: `[b, a, x]`. Output: `[b, a, x]`.
371 /// - Input: `[a, x, b, y]`. Output: `[a, x]`.
372 fn pare_down(candidates: &mut Vec<usize>, closure: &BitMatrix<usize, usize>) {
373     let mut i = 0;
374     while let Some(&candidate_i) = candidates.get(i) {
375         i += 1;
376
377         let mut j = i;
378         let mut dead = 0;
379         while let Some(&candidate_j) = candidates.get(j) {
380             if closure.contains(candidate_i, candidate_j) {
381                 // If `i` can reach `j`, then we can remove `j`. So just
382                 // mark it as dead and move on; subsequent indices will be
383                 // shifted into its place.
384                 dead += 1;
385             } else {
386                 candidates[j - dead] = candidate_j;
387             }
388             j += 1;
389         }
390         candidates.truncate(j - dead);
391     }
392 }