Debian Codegraph @

crates/graph/src/tsort.rs

raw symbols SCIP
1 #![allow(clippy::if_same_then_else)]
2 use crate::{Error, RevnoVec};
3 use rustc_hash::{FxHashMap, FxHashSet};
4 use std::collections::HashMap;
5 use std::hash::Hash;
6
7 #[derive(Debug)]
8 pub struct TopoSorter<K: Eq + Hash> {
9 graph: FxHashMap<K, Vec<K>>,
10
11 visitable: FxHashSet<K>,
12
13 // this is a stack storing the depth first search into the graph.
14 pending_node_stack: Vec<K>,
15
16 // at each level of 'recursion' we have to check each parent. This
17 // stack stores the parents we have not yet checked for the node at the
18 // matching depth in pending_node_stack
19 pending_parents_stack: Vec<Vec<K>>,
20
21 // this is a set of the completed nodes for fast checking whether a
22 // parent in a node we are processing on the stack has already been
23 // emitted and thus can be skipped.
24 completed_node_names: FxHashSet<K>,
25 }
26
27 impl<K: Eq + Hash + std::fmt::Debug + Clone> TopoSorter<K> {
28 /// Create a new `TopoSorter` from a graph represented as a sequence of pairs
29 /// of node_name->parent_names_list.
30 pub fn new(graph: impl Iterator<Item = (K, Vec<K>)>) -> TopoSorter<K> {
31 let mut g = FxHashMap::default();
32 for (node, parents) in graph {
33 g.insert(node, parents);
34 }
35 let visitable = g.keys().cloned().collect();
36 TopoSorter {
37 graph: g,
38 visitable,
39 pending_node_stack: vec![],
40 pending_parents_stack: vec![],
41 completed_node_names: FxHashSet::default(),
42 }
43 }
44
45 /// Sort the graph and return the nodes as a vector.
46 ///
47 /// After calling this the sorter is empty and you must create a new one.
48 pub fn sorted(&mut self) -> std::result::Result<Vec<K>, Error<K>> {
49 self.iter_topo_order()
50 .collect::<std::result::Result<Vec<K>, Error<K>>>()
51 }
52
53 /// Yield the nodes of the graph in a topological order.
54 ///
55 /// After finishing iteration the sorter is empty and you cannot continue
56 /// iteration.
57 pub fn iter_topo_order(
58 &mut self,
59 ) -> impl Iterator<Item = std::result::Result<K, Error<K>>> + '_ {
60 self
61 }
62 }
63
64 impl<K: Eq + Hash + std::fmt::Debug + Clone> Iterator for TopoSorter<K> {
65 type Item = std::result::Result<K, Error<K>>;
66 fn next(&mut self) -> Option<std::result::Result<K, Error<K>>> {
67 loop {
68 // loop until pending_node_stack is empty
69 while !self.pending_node_stack.is_empty() {
70 let parents_to_visit = self.pending_parents_stack.last_mut().unwrap();
71
72 // if there are no parents left, the revision is done
73 if parents_to_visit.is_empty() {
74 // append the revision to the topo sorted list
75 // all the nodes parents have been added to the output,
76 // now we can add it to the output.
77 let popped_node = self.pending_node_stack.pop().unwrap();
78 self.pending_parents_stack.pop();
79 self.completed_node_names.insert(popped_node.clone());
80 return Some(Ok(popped_node));
81 } else {
82 // recurse depth first into a single parent
83 let next_node_name = parents_to_visit.pop().unwrap();
84 if self.completed_node_names.contains(&next_node_name) {
85 // parent was already completed by a child, skip it.
86 continue;
87 }
88 if !self.visitable.contains(&next_node_name) {
89 // parent is not a node in the original graph, skip it.
90 continue;
91 }
92
93 // transfer it along with its parents from the source graph
94 // into the top of the current depth first search stack.
95 if let Some(parents) = self.graph.remove(&next_node_name) {
96 self.pending_node_stack.push(next_node_name);
97 self.pending_parents_stack.push(parents);
98 } else {
99 // if the next node is not in the source graph it has
100 // already been popped from it and placed into the
101 // current search stack (but not completed or we would
102 // have hit the continue 6 lines up). this indicates a
103 // cycle.
104 return Some(Err(Error::Cycle(self.pending_node_stack.to_vec())));
105 }
106 }
107 }
108 if let Some(node_name) = self.graph.keys().next() {
109 let node_name = node_name.clone();
110 let parents = self.graph.remove(&node_name).unwrap();
111 // now pick a random node in the source graph, and transfer it to the
112 // top of the depth first search stack of pending nodes.
113 self.pending_node_stack.push(node_name);
114 self.pending_parents_stack.push(parents);
115 } else {
116 // if the source graph is empty, we are done.
117 return None;
118 }
119 }
120 }
121 }
122
123 /// Merge-aware topological sorting of a graph.
124 ///
125 /// :param graph: sequence of pairs of node_name->parent_names_list.
126 /// i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
127 /// For this input the output from the sort or
128 /// iter_topo_order routines will be:
129 /// 'A', 'B', 'C'
130 /// :param branch_tip: the tip of the branch to graph. Revisions not
131 /// reachable from branch_tip are not included in the
132 /// output.
133 /// :param mainline_revisions: If not None this forces a mainline to be
134 /// used rather than synthesised from the graph.
135 /// This must be a valid path through some part
136 /// of the graph. If the mainline does not cover all
137 /// the revisions, output stops at the start of the
138 /// old revision listed in the mainline revisions
139 /// list.
140 /// The order for this parameter is oldest-first.
141 /// :param generate_revno: Optional parameter controlling the generation of
142 /// revision number sequences in the output. See the output description
143 /// for more details.
144 ///
145 /// The result is a list sorted so that all parents come before
146 /// their children. Each element of the list is a tuple containing:
147 /// `(sequence_number, node_name, merge_depth, end_of_merge)`.
148 ///
149 /// - `sequence_number`: the sequence of this row in the output. Useful for
150 /// GUIs.
151 /// - `node_name`: the node name; opaque text to the merge routine.
152 /// - `merge_depth`: how many levels of merging deep this node has been found.
153 /// - `revno_sequence`: when requested this field provides a sequence of
154 /// revision numbers for all revisions. The format is
155 /// `(REVNO, BRANCHNUM, BRANCHREVNO)`. `BRANCHNUM` is the number of the
156 /// branch that the revno is on. From left to right the `REVNO` numbers
157 /// are the sequence numbers within that branch of the revision.
158 /// For instance, the graph `{A:[], B:['A'], C:['A', 'B']}` will get
159 /// the following revno sequences assigned: `A:(1,), B:(1,1,1), C:(2,)`.
160 /// This should be read as 'A is the first commit in the trunk',
161 /// 'B is the first commit on the first branch made from A', 'C is the
162 /// second commit in the trunk'.
163 /// - `end_of_merge`: when true the next node is part of a different merge.
164 ///
165 /// Node identifiers can be any hashable object, and are typically strings.
166 ///
167 /// If you have a graph like `[('a', ['b']), ('a', ['c'])]` this will only
168 /// use one of the two values for 'a'.
169 ///
170 /// The graph is sorted lazily: until you iterate or sort the input is not
171 /// processed other than to create an internal representation.
172 ///
173 /// Iteration or sorting may raise a cycle error if a cycle is present in
174 /// the graph.
175 ///
176 /// # Background on the design
177 ///
178 /// The end of any cluster or 'merge' occurs when:
179 ///
180 /// 1. the next revision has a lower merge depth than we do:
181 ///
182 /// ```text
183 /// A 0
184 /// B 1
185 /// C 2
186 /// D 1
187 /// E 0
188 /// ```
189 ///
190 /// C and D are the ends of clusters; E might be but we need more data.
191 ///
192 /// 2. or the next revision at our merge depth is not our left most ancestor.
193 /// This is required to handle multiple-merges in one commit:
194 ///
195 /// ```text
196 /// A 0 [F, B, E]
197 /// B 1 [D, C]
198 /// C 2 [D]
199 /// D 1 [F]
200 /// E 1 [F]
201 /// F 0
202 /// ```
203 ///
204 /// C is the end of a cluster due to rule 1. D is not the end of a
205 /// cluster from rule 1, but is from rule 2: E is not its left most
206 /// ancestor. E is the end of a cluster due to rule 1. F might be but we
207 /// need more data.
208 ///
209 /// We show connecting lines to a parent when:
210 ///
211 /// - The parent is the start of a merge within this cluster. That is, the
212 /// merge was not done to the mainline before this cluster was merged to
213 /// the mainline. This can be detected thus: the parent has a higher
214 /// merge depth and is the next revision in the list. The next-revision
215 /// constraint is needed for this case:
216 ///
217 /// ```text
218 /// A 0 [D, B]
219 /// B 1 [C, F] # we do not want to show a line to F which is depth 2
220 /// # but not a merge
221 /// C 1 [H] # note that this is a long line to show back to the
222 /// # ancestor - see the end of merge rules.
223 /// D 0 [G, E]
224 /// E 1 [G, F]
225 /// F 2 [G]
226 /// G 1 [H]
227 /// H 0
228 /// ```
229 ///
230 /// - Part of this merge's branch: the parent has the same merge depth and
231 /// is our left most parent and we are not the end of the cluster:
232 ///
233 /// ```text
234 /// A 0 [C, B] lines: [B, C]
235 /// B 1 [E, C] lines: [C]
236 /// C 0 [D] lines: [D]
237 /// D 0 [F, E] lines: [E, F]
238 /// E 1 [F] lines: [F]
239 /// F 0
240 /// ```
241 ///
242 /// - The end of this merge/cluster: we can only have multiple parents at
243 /// the end of a cluster if this branch was previously merged into the
244 /// 'mainline'.
245 ///
246 /// - If we have one and only one parent, show it. Note that this may be
247 /// to a greater merge depth — for instance if this branch continued
248 /// from a deeply nested branch to add something to it.
249 /// - If we have more than one parent, show the second oldest (older ==
250 /// further down the list) parent with an equal or lower merge depth.
251 pub struct MergeSorter<K> {
252 // this is a stack storing the depth first search into the graph.
253 node_name_stack: Vec<K>,
254 // at each level of recursion we need the merge depth this node is at:
255 node_merge_depth_stack: Vec<usize>,
256 // at each level of 'recursion' we have to check each parent. This
257 // stack stores the parents we have not yet checked for the node at the
258 // matching depth in _node_name_stack
259 pending_parents_stack: Vec<Vec<K>>,
260 // When we first look at a node we assign it a seqence number from its
261 // leftmost parent.
262 first_child_stack: Vec<Option<bool>>,
263 // This records for each node when we have processed its left most
264 // unmerged subtree. After this subtree is scheduled, all other subtrees
265 // have their merge depth increased by one from this nodes merge depth.
266 // it contains tuples - name, merge_depth
267 left_subtree_pushed_stack: Vec<bool>,
268 generate_revno: bool,
269 // The full parent map. Read-only after construction. This used to be
270 // stored twice (once mutable for destructive iteration via `remove`, once
271 // immutable for end-of-merge lookups); it is now stored once and the
272 // "still pending" bookkeeping lives in `not_yet_scheduled`.
273 graph: HashMap<K, Vec<K>>,
274 // Nodes in `graph` that have not yet been pushed onto the pending stack.
275 // Plays the role of the old mutable `graph`'s key set.
276 not_yet_scheduled: FxHashSet<K>,
277 stop_revision: Option<K>,
278 revnos: FxHashMap<K, (Option<RevnoVec>, bool)>,
279 // Each mainline revision counts how many child branches have spawned from it.
280 revno_to_branch_count: FxHashMap<usize, usize>,
281 // this is a set of the nodes who have been completely analysed for fast
282 // membership checking
283 completed_node_names: FxHashSet<K>,
284 // this is the scheduling of nodes list.
285 // Nodes are scheduled
286 // from the bottom left of the tree: in the tree
287 // A 0 [D, B]
288 // B 1 [C]
289 // C 1 [D]
290 // D 0 [F, E]
291 // E 1 [F]
292 // F 0
293 // the scheduling order is: F, E, D, C, B, A
294 // that is - 'left subtree, right subtree, node'
295 // which would mean that when we schedule A we can emit the entire tree.
296 scheduled_nodes: Vec<(K, usize, RevnoVec)>,
297 sequence_number: usize,
298 }
299
300 /// A single row emitted by [`MergeSorter`].
301 ///
302 /// Fields in order: sequence number, node name, merge depth, optional revno
303 /// sequence, and an end-of-merge flag. See the [`MergeSorter`] docs for the
304 /// meaning of each field.
305 pub type MergeSortRow<K> = (usize, K, usize, Option<RevnoVec>, bool);
306
307 impl<K: Eq + Hash + Clone + std::fmt::Debug> MergeSorter<K> {
308 pub fn new(
309 mut graph: HashMap<K, Vec<K>>,
310 branch_tip: Option<K>,
311 mainline_revisions: Option<Vec<K>>,
312 generate_revno: bool,
313 ) -> Self {
314 let stop_revision;
315
316 // if there is an explicit mainline, alter the graph to match. This is
317 // easier than checking at every merge whether we are on the mainline and
318 // if so which path to take.
319 if let Some(mainline_revisions) = mainline_revisions.as_ref() {
320 stop_revision = Some(mainline_revisions[0].clone());
321
322 // skip the first revision, its what we reach and its parents are
323 // therefore irrelevant
324 for (index, revision) in mainline_revisions[1..].iter().enumerate() {
325 // NB: index 0 means self._mainline_revisions[1]
326 // if the mainline matches the graph, nothing to do.
327 let parent = &mainline_revisions[index];
328 let graph_parent_ids = graph.get_mut(revision).unwrap();
329 if !graph_parent_ids.is_empty() {
330 if graph_parent_ids[0] == *parent {
331 continue;
332 }
333 let current_position =
334 graph_parent_ids.iter().position(|x| x == parent).unwrap();
335 graph_parent_ids.swap(0, current_position);
336 } else {
337 // We ran into a ghost, skip over it, this is a workaround for
338 // bug #243536, the _graph has had ghosts stripped, but the
339 // mainline_revisions have not
340 continue;
341 }
342 }
343 } else {
344 stop_revision = None;
345 }
346
347 // we need to know the revision numbers of revisions to determine
348 // the revision numbers of their descendants
349 // this is a graph from node to [revno_tuple, first_child]
350 // where first_child is True if no other children have seen this node
351 // and revno_tuple is the tuple that was assigned to the node.
352 // we dont know revnos to start with, so we start it seeded with
353 // [None, True]
354 let revnos = graph
355 .keys()
356 .map(|revision| (revision.clone(), (None, true)))
357 .collect::<FxHashMap<K, (Option<RevnoVec>, bool)>>();
358 let not_yet_scheduled: FxHashSet<K> = graph.keys().cloned().collect();
359
360 let mut sorter = MergeSorter {
361 generate_revno,
362 graph,
363 not_yet_scheduled,
364 stop_revision,
365 revnos,
366 revno_to_branch_count: FxHashMap::default(),
367 node_name_stack: Vec::new(),
368 node_merge_depth_stack: Vec::new(),
369 pending_parents_stack: Vec::new(),
370 first_child_stack: Vec::new(),
371 completed_node_names: FxHashSet::default(),
372 scheduled_nodes: Vec::new(),
373 left_subtree_pushed_stack: Vec::new(),
374 sequence_number: 0,
375 };
376
377 if let Some(branch_tip) = branch_tip {
378 let parents = sorter.take_parents(&branch_tip).unwrap();
379 sorter.push_node(branch_tip, 0, parents);
380 }
381 sorter
382 }
383
384 /// Mark `key` as scheduled and return a clone of its parent list, or
385 /// `None` if it was already scheduled or not in the graph.
386 fn take_parents(&mut self, key: &K) -> Option<Vec<K>> {
387 if self.not_yet_scheduled.remove(key) {
388 Some(self.graph[key].clone())
389 } else {
390 None
391 }
392 }
393
394 /// Sort the graph and return as a list.
395 ///
396 /// After calling this the sorter is empty and you must create a new one.
397 pub fn sorted(&mut self) -> std::result::Result<Vec<MergeSortRow<K>>, Error<K>> {
398 self.iter_topo_order().collect()
399 }
400
401 ///
402 /// After finishing iteration the sorter is empty and you cannot continue
403 /// iteration.
404 pub fn iter_topo_order(
405 &mut self,
406 ) -> impl Iterator<Item = std::result::Result<MergeSortRow<K>, Error<K>>> + '_ {
407 self
408 }
409
410 /// Add node_name to the pending node stack.
411 ///
412 /// Names in this stack will get emitted into the output as they are popped
413 /// off the stack.
414 pub fn push_node(&mut self, node_name: K, merge_depth: usize, parents: Vec<K>) {
415 self.node_name_stack.push(node_name);
416 self.node_merge_depth_stack.push(merge_depth);
417 self.left_subtree_pushed_stack.push(false);
418
419 // As we push it, figure out if this is the first child
420 let first_child: Option<bool>;
421 if !parents.is_empty() {
422 // Node has parents, assign from the left most parent.
423 if let Some(entry) = self.revnos.get_mut(&parents[0]) {
424 first_child = Some(entry.1);
425 entry.1 = false;
426 } else {
427 // Left-hand parent is a ghost, consider it not to exist
428 first_child = None;
429 }
430 } else {
431 first_child = None;
432 }
433 self.pending_parents_stack.push(parents);
434 self.first_child_stack.push(first_child);
435 }
436
437 pub fn pop_node(&mut self) -> K {
438 // Pop the top node off the stack
439 //
440 // The node is appended to the sorted output.
441 let node_name = self.node_name_stack.pop().unwrap();
442 let merge_depth = self.node_merge_depth_stack.pop().unwrap();
443 let first_child = self.first_child_stack.pop().unwrap();
444 // remove this node from the pending lists:
445 self.left_subtree_pushed_stack.pop().unwrap();
446 self.pending_parents_stack.pop().unwrap();
447
448 let parents = self.graph.get(&node_name).unwrap();
449 // Left-hand parent's revno, if it exists and isn't a ghost.
450 let parent_revno = parents
451 .first()
452 .and_then(|p| self.revnos.get(p))
453 .and_then(|entry| entry.0.clone());
454 let revno: RevnoVec = if let Some(parent_revno) = parent_revno {
455 if first_child == Some(true) {
456 // as the first child, we just increase the final revision number
457 parent_revno.bump_last()
458 } else {
459 // not the first child, make a new branch
460 let base_revno = parent_revno[0];
461 let branch_count = self
462 .revno_to_branch_count
463 .get(&base_revno)
464 .copied()
465 .unwrap_or(0)
466 + 1;
467 self.revno_to_branch_count.insert(base_revno, branch_count);
468 parent_revno.new_branch(branch_count)
469 }
470 } else {
471 // no parents, use the root sequence
472 let root_count = if let Some(root_count) = self.revno_to_branch_count.get(&0) {
473 root_count + 1
474 } else {
475 0
476 };
477 self.revno_to_branch_count.insert(0, root_count);
478 if root_count > 0 {
479 RevnoVec::from(vec![0, root_count, 1])
480 } else {
481 RevnoVec::from(1)
482 }
483 };
484
485 // store the revno for this node for future reference
486 self.revnos
487 .entry(node_name.clone())
488 .and_modify(|e| e.0 = Some(revno.clone()));
489 self.completed_node_names.insert(node_name.clone());
490 self.scheduled_nodes
491 .push((node_name.clone(), merge_depth, revno));
492 node_name
493 }
494
495 fn build(&mut self) -> std::result::Result<(), Error<K>> {
496 while !self.node_name_stack.is_empty() {
497 let parents_to_visit = self.pending_parents_stack.last().unwrap();
498 if parents_to_visit.is_empty() {
499 self.pop_node();
500 } else {
501 while !self.pending_parents_stack.last().unwrap().is_empty() {
502 let is_left_subtree;
503 let next_node_name;
504 if !self.left_subtree_pushed_stack.last().unwrap() {
505 next_node_name = self.pending_parents_stack.last_mut().unwrap().remove(0);
506 is_left_subtree = true;
507 *self.left_subtree_pushed_stack.last_mut().unwrap() = true;
508 // recurse depth first into the primary parent
509 } else {
510 next_node_name = self
511 .pending_parents_stack
512 .last_mut()
513 .unwrap()
514 .pop()
515 .unwrap();
516 is_left_subtree = false;
517 // place any merges in right-to-left order for scheduling
518 // which gives us left-to-right order after we reverse
519 // the scheduled queue. XXX: This has the effect of
520 // allocating common-new revisions to the right-most
521 // subtree rather than the left most, which will
522 // display nicely (you get smaller trees at the top
523 // of the combined merge).
524 }
525 if self.completed_node_names.contains(&next_node_name) {
526 // this parent was completed by a child on the
527 // call stack. skip it.
528 continue;
529 }
530
531 // otherwise transfer it from the source graph into the
532 // top of the current depth first search stack.
533 let parents = match self.take_parents(&next_node_name) {
534 Some(parents) => parents,
535 None => {
536 // if the next node is not marked as pending it has
537 // already been popped from the source graph and
538 // placed into the current search stack (but not
539 // completed or we would have hit the continue 4
540 // lines up). this indicates a cycle.
541 if self.graph.contains_key(&next_node_name) {
542 return Err(Error::Cycle(self.node_name_stack.clone()));
543 } else {
544 // This is just a ghost parent, ignore it
545 continue;
546 }
547 }
548 };
549 let next_merge_depth =
550 usize::from(!is_left_subtree) + self.node_merge_depth_stack.last().unwrap();
551 self.push_node(next_node_name, next_merge_depth, parents);
552 // and do not continue processing parents until this 'call'
553 // has recursed.
554 break;
555 }
556 }
557 }
558 Ok(())
559 }
560 }
561
562 impl<K: Eq + Hash + std::fmt::Debug + Clone> Iterator for MergeSorter<K> {
563 type Item = std::result::Result<MergeSortRow<K>, Error<K>>;
564 fn next(&mut self) -> Option<Self::Item> {
565 if let Err(err) = self.build() {
566 return Some(Err(err));
567 }
568 let (node_name, merge_depth, revno) = self.scheduled_nodes.pop()?;
569 if let Some(stop) = self.stop_revision.as_ref() {
570 if &node_name == stop {
571 return None;
572 }
573 }
574 let end_of_merge = match self.scheduled_nodes.last() {
575 // last revision is the end of a merge
576 None => true,
577 // the next node is to our left
578 Some((_, next_depth, _)) if *next_depth < merge_depth => true,
579 // the next node was part of a multiple-merge
580 Some((next_name, next_depth, _)) if *next_depth == merge_depth => {
581 !self.graph.get(&node_name).unwrap().contains(next_name)
582 }
583 _ => false,
584 };
585 let revno_out = self.generate_revno.then_some(revno);
586 let result = (
587 self.sequence_number,
588 node_name,
589 merge_depth,
590 revno_out,
591 end_of_merge,
592 );
593 self.sequence_number += 1;
594 Some(Ok(result))
595 }
596 }
597
598 pub fn merge_sort<K: Eq + Hash + std::fmt::Debug + Clone>(
599 graph: HashMap<K, Vec<K>>,
600 branch_tip: Option<K>,
601 mainline_revisions: Option<Vec<K>>,
602 generate_revno: bool,
603 ) -> std::result::Result<Vec<MergeSortRow<K>>, Error<K>> {
604 MergeSorter::new(graph, branch_tip, mainline_revisions, generate_revno).sorted()
605 }