Skip to main content

cargo/util/
dependency_queue.rs

1//! A graph-like structure used to represent a set of dependencies and in what
2//! order they should be built.
3//!
4//! This structure is used to store the dependency graph and dynamically update
5//! it to figure out when a dependency should be built.
6
7use std::collections::hash_map::Entry::{Occupied, Vacant};
8use std::collections::{HashMap, HashSet};
9use std::hash::Hash;
10
11pub use self::Freshness::{Dirty, Fresh};
12
13#[derive(Debug)]
14pub struct DependencyQueue<K: Eq + Hash, V> {
15    /// A list of all known keys to build.
16    ///
17    /// The value of the hash map is list of dependencies which still need to be
18    /// built before the package can be built. Note that the set is dynamically
19    /// updated as more dependencies are built.
20    dep_map: HashMap<K, (HashSet<K>, V)>,
21
22    /// A reverse mapping of a package to all packages that depend on that
23    /// package.
24    ///
25    /// This map is statically known and does not get updated throughout the
26    /// lifecycle of the DependencyQueue.
27    reverse_dep_map: HashMap<K, HashSet<K>>,
28
29    /// A set of dirty packages.
30    ///
31    /// Packages may become dirty over time if their dependencies are rebuilt.
32    dirty: HashSet<K>,
33
34    /// The packages which are currently being built, waiting for a call to
35    /// `finish`.
36    pending: HashSet<K>,
37
38    /// Topological depth of each key
39    depth: HashMap<K, usize>,
40}
41
42/// Indication of the freshness of a package.
43///
44/// A fresh package does not necessarily need to be rebuilt (unless a dependency
45/// was also rebuilt), and a dirty package must always be rebuilt.
46#[derive(PartialEq, Eq, Debug, Clone, Copy)]
47pub enum Freshness {
48    Fresh,
49    Dirty,
50}
51
52impl Freshness {
53    pub fn combine(self, other: Freshness) -> Freshness {
54        match self {
55            Fresh => other,
56            Dirty => Dirty,
57        }
58    }
59}
60
61impl<K: Hash + Eq + Clone, V> Default for DependencyQueue<K, V> {
62    fn default() -> DependencyQueue<K, V> {
63        DependencyQueue::new()
64    }
65}
66
67impl<K: Hash + Eq + Clone, V> DependencyQueue<K, V> {
68    /// Creates a new dependency queue with 0 packages.
69    pub fn new() -> DependencyQueue<K, V> {
70        DependencyQueue {
71            dep_map: HashMap::new(),
72            reverse_dep_map: HashMap::new(),
73            dirty: HashSet::new(),
74            pending: HashSet::new(),
75            depth: HashMap::new(),
76        }
77    }
78
79    /// Adds a new package to this dependency queue.
80    ///
81    /// It is assumed that any dependencies of this package will eventually also
82    /// be added to the dependency queue.
83    pub fn queue(&mut self, fresh: Freshness, key: &K, value: V, dependencies: &[K]) -> &mut V {
84        let slot = match self.dep_map.entry(key.clone()) {
85            Occupied(v) => return &mut v.into_mut().1,
86            Vacant(v) => v,
87        };
88
89        if fresh == Dirty {
90            self.dirty.insert(key.clone());
91        }
92
93        let mut my_dependencies = HashSet::new();
94        for dep in dependencies {
95            my_dependencies.insert(dep.clone());
96            let rev = self
97                .reverse_dep_map
98                .entry(dep.clone())
99                .or_insert_with(HashSet::new);
100            rev.insert(key.clone());
101        }
102        &mut slot.insert((my_dependencies, value)).1
103    }
104
105    /// All nodes have been added, calculate some internal metadata and prepare
106    /// for `dequeue`.
107    pub fn queue_finished(&mut self) {
108        for key in self.dep_map.keys() {
109            depth(key, &self.reverse_dep_map, &mut self.depth);
110        }
111
112        fn depth<K: Hash + Eq + Clone>(
113            key: &K,
114            map: &HashMap<K, HashSet<K>>,
115            results: &mut HashMap<K, usize>,
116        ) -> usize {
117            const IN_PROGRESS: usize = !0;
118
119            if let Some(&depth) = results.get(key) {
120                assert_ne!(depth, IN_PROGRESS, "cycle in DependencyQueue");
121                return depth;
122            }
123
124            results.insert(key.clone(), IN_PROGRESS);
125
126            let depth = 1 + map
127                .get(&key)
128                .into_iter()
129                .flat_map(|it| it)
130                .map(|dep| depth(dep, map, results))
131                .max()
132                .unwrap_or(0);
133
134            *results.get_mut(key).unwrap() = depth;
135
136            depth
137        }
138    }
139
140    /// Dequeues a package that is ready to be built.
141    ///
142    /// A package is ready to be built when it has 0 un-built dependencies. If
143    /// `None` is returned then no packages are ready to be built.
144    pub fn dequeue(&mut self) -> Option<(Freshness, K, V)> {
145        // Look at all our crates and find everything that's ready to build (no
146        // deps). After we've got that candidate set select the one which has
147        // the maximum depth in the dependency graph. This way we should
148        // hopefully keep CPUs hottest the longest by ensuring that long
149        // dependency chains are scheduled early on in the build process and the
150        // leafs higher in the tree can fill in the cracks later.
151        //
152        // TODO: it'd be best here to throw in a heuristic of crate size as
153        //       well. For example how long did this crate historically take to
154        //       compile? How large is its source code? etc.
155        let next = self
156            .dep_map
157            .iter()
158            .filter(|&(_, &(ref deps, _))| deps.is_empty())
159            .map(|(key, _)| key.clone())
160            .max_by_key(|k| self.depth[k]);
161        let key = match next {
162            Some(key) => key,
163            None => return None,
164        };
165        let (_, data) = self.dep_map.remove(&key).unwrap();
166        let fresh = if self.dirty.contains(&key) {
167            Dirty
168        } else {
169            Fresh
170        };
171        self.pending.insert(key.clone());
172        Some((fresh, key, data))
173    }
174
175    /// Returns whether there are remaining packages to be built.
176    pub fn is_empty(&self) -> bool {
177        self.dep_map.is_empty() && self.pending.is_empty()
178    }
179
180    /// Returns the number of remaining packages to be built.
181    pub fn len(&self) -> usize {
182        self.dep_map.len() + self.pending.len()
183    }
184
185    /// Indicate that a package has been built.
186    ///
187    /// This function will update the dependency queue with this information,
188    /// possibly allowing the next invocation of `dequeue` to return a package.
189    pub fn finish(&mut self, key: &K, fresh: Freshness) {
190        assert!(self.pending.remove(key));
191        let reverse_deps = match self.reverse_dep_map.get(key) {
192            Some(deps) => deps,
193            None => return,
194        };
195        for dep in reverse_deps.iter() {
196            if fresh == Dirty {
197                self.dirty.insert(dep.clone());
198            }
199            assert!(self.dep_map.get_mut(dep).unwrap().0.remove(key));
200        }
201    }
202}
203
204#[cfg(test)]
205mod test {
206    use super::{DependencyQueue, Freshness};
207
208    #[test]
209    fn deep_first() {
210        let mut q = DependencyQueue::new();
211
212        q.queue(Freshness::Fresh, &1, (), &[]);
213        q.queue(Freshness::Fresh, &2, (), &[1]);
214        q.queue(Freshness::Fresh, &3, (), &[]);
215        q.queue(Freshness::Fresh, &4, (), &[2, 3]);
216        q.queue(Freshness::Fresh, &5, (), &[4, 3]);
217        q.queue_finished();
218
219        assert_eq!(q.dequeue(), Some((Freshness::Fresh, 1, ())));
220        assert_eq!(q.dequeue(), Some((Freshness::Fresh, 3, ())));
221        assert_eq!(q.dequeue(), None);
222        q.finish(&3, Freshness::Fresh);
223        assert_eq!(q.dequeue(), None);
224        q.finish(&1, Freshness::Fresh);
225        assert_eq!(q.dequeue(), Some((Freshness::Fresh, 2, ())));
226        assert_eq!(q.dequeue(), None);
227        q.finish(&2, Freshness::Fresh);
228        assert_eq!(q.dequeue(), Some((Freshness::Fresh, 4, ())));
229        assert_eq!(q.dequeue(), None);
230        q.finish(&4, Freshness::Fresh);
231        assert_eq!(q.dequeue(), Some((Freshness::Fresh, 5, ())));
232    }
233}