Skip to main content

graphity_core/
dfs_traverser.rs

1use crate::error::check_index;
2use crate::{Graph, dfs_frames};
3
4/// Bit 0 of a node's packed state: the node has been discovered.
5const VISITED: u32 = 0b01;
6/// Bit 1 of a node's packed state: the node is on the current search path.
7const ON_STACK: u32 = 0b10;
8
9/// The hooks of a depth-first search of your own, which a [`DfsTraverser`] runs: a type of yours
10/// implements [`enter_node`](Self::enter_node) and, if needed, [`leave_node`](Self::leave_node).
11///
12/// Java's `DfsTraverser` is an abstract class whose subclass overrides the hooks `enterNode` and
13/// `leaveNode` and calls the protected methods `isVisited`, `isOnStack` and `stop`. In Rust, the
14/// state of the search stays in the [`DfsTraverser`], the hooks are this trait, and the protected
15/// methods are on the [`DfsControl`] each hook receives. The hooks are called through a generic
16/// parameter, so they are inlined into the loop of the search. A closure `FnMut(u32) -> bool` is a
17/// set of hooks with only the preorder hook.
18pub trait DfsHooks {
19    /// Called when the search reaches `node`, before its out-nodes: the preorder hook.
20    ///
21    /// The search calls it once per node: for a start node, or for an unvisited out-node of the node it
22    /// is searching. From this call on, `node` counts as visited and is on the current path. Returning
23    /// `true` lets the search go on with the out-nodes of `node`. Returning `false` skips them, and
24    /// [`leave_node`](Self::leave_node) follows right away; out-nodes skipped this way stay unvisited
25    /// unless the search reaches them from another node.
26    fn enter_node(&mut self, node: u32, control: &mut DfsControl<'_>) -> bool;
27
28    /// Called when the search leaves `node`, after it has searched from all its out-nodes: the postorder
29    /// hook. Does nothing unless implemented.
30    ///
31    /// The search calls it once for every node it has visited, right after
32    /// [`enter_node`](Self::enter_node) if that returned `false`. From this call on, `node` is no longer
33    /// on the current path. After [`DfsControl::stop`], it is not called for the nodes still on the path.
34    fn leave_node(&mut self, node: u32, control: &mut DfsControl<'_>) {
35        let _ = (node, control);
36    }
37}
38
39impl<F: FnMut(u32) -> bool> DfsHooks for F {
40    #[inline]
41    fn enter_node(&mut self, node: u32, _control: &mut DfsControl<'_>) -> bool {
42        self(node)
43    }
44}
45
46/// What a hook may ask or do during a run of a depth-first search: read the graph, ask whether a node
47/// is visited or on the current path, and stop the run - the protected members of Java's
48/// `DfsTraverser` and `DfsEdgeTraverser`, which share this type.
49pub struct DfsControl<'a> {
50    graph: &'a Graph,
51    state: &'a [u32],
52    stop_requested: &'a mut bool,
53}
54
55impl<'a> DfsControl<'a> {
56    #[inline]
57    pub(crate) fn new(graph: &'a Graph, state: &'a [u32], stop_requested: &'a mut bool) -> Self {
58        Self {
59            graph,
60            state,
61            stop_requested,
62        }
63    }
64
65    /// Returns the graph that the search runs on - Java's protected field `graph`.
66    ///
67    /// **Time:** O(1).
68    #[inline]
69    pub fn graph(&self) -> &Graph {
70        self.graph
71    }
72
73    /// Returns whether the search has reached `node`, in this run or in an earlier one. It returns `true`
74    /// if [`enter_node`](DfsHooks::enter_node) has been called for `node`.
75    ///
76    /// `node` is a node ID in `0..node_count`; for any other value the method returns `false` or panics
77    /// with an `index out of bounds` message.
78    ///
79    /// **Time:** O(1).
80    #[inline]
81    pub fn is_visited(&self, node: u32) -> bool {
82        flags(self.state, node) & VISITED != 0
83    }
84
85    /// Returns whether `node` is on the stack of the search, that is, on the current path.
86    ///
87    /// The current path leads from the node where the search started to the node being searched. A node is
88    /// on the path from its [`enter_node`](DfsHooks::enter_node) until its
89    /// [`leave_node`](DfsHooks::leave_node). An edge from the node being searched to a node on the path
90    /// closes a cycle.
91    ///
92    /// `node` is a node ID in `0..node_count`; for any other value the method returns `false` or panics
93    /// with an `index out of bounds` message.
94    ///
95    /// **Time:** O(1).
96    #[inline]
97    pub fn is_on_stack(&self, node: u32) -> bool {
98        flags(self.state, node) & ON_STACK != 0
99    }
100
101    /// Stops the run in progress: the run returns as soon as the hook that calls this method returns,
102    /// without calling another hook.
103    ///
104    /// It works from every hook; from [`visit_edge`](crate::DfsEdgeHooks::visit_edge), it does the same as
105    /// returning [`EdgeAction::Stop`](crate::EdgeAction::Stop). [`leave_node`](DfsHooks::leave_node) is
106    /// not called for the nodes on the current path, but they count as visited and as no longer on the
107    /// path. This includes a node whose `enter_node` called this method. A later run skips every node
108    /// visited so far; it does not go on where the stopped run ended. To cancel a run from another thread,
109    /// let a hook check a flag of your own and call this method.
110    ///
111    /// **Time:** O(1).
112    #[inline]
113    pub fn stop(&mut self) {
114        *self.stop_requested = true;
115    }
116}
117
118#[inline]
119pub(crate) fn flags(state: &[u32], node: u32) -> u32 {
120    let v = node as usize;
121    state[v >> 4] >> ((v & 0xF) << 1)
122}
123
124/// Clears the on-stack flag of every node in `frames[0..=top]`, once per stop.
125pub(crate) fn leave_stack(state: &mut [u32], frames: &[u32], top: usize) {
126    for d in 0..=top {
127        let w = frames[2 * d] as usize;
128        state[w >> 4] &= !(ON_STACK << ((w & 0xF) << 1));
129    }
130}
131
132/// The base of a depth-first search of your own over a [`Graph`] - Java's abstract class
133/// `DfsTraverser`. A type of yours implements the hooks [`enter_node`](DfsHooks::enter_node) and
134/// [`leave_node`](DfsHooks::leave_node) of [`DfsHooks`], and a `run` method starts the search with
135/// them.
136///
137/// The search visits each node it reaches once. It calls [`enter_node`](DfsHooks::enter_node) when it
138/// reaches a node (preorder) and [`leave_node`](DfsHooks::leave_node) when it has searched from all
139/// out-nodes of the node (postorder). It takes the out-nodes of each node in ascending order, so the
140/// hooks come in the order of a textbook recursive
141/// [depth-first search](https://en.wikipedia.org/wiki/Depth-first_search). The search itself runs
142/// without recursion and keeps its stack on the heap, so a deep graph does not overflow the call
143/// stack. Here, `calls` are the calls between the methods of a program, and the postorder puts each
144/// method after the methods it calls, except along calls that close a cycle:
145///
146/// <!-- example: traversals.rs#leaveNode -->
147/// ```
148/// # use graphity_core::{DfsControl, DfsHooks, DfsTraverser};
149/// # let calls = graphity_core::Graph::of(
150/// #     &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
151/// #     &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
152/// # ).unwrap();
153/// # let main = 0;
154/// struct CalleesFirst {
155///     order: Vec<u32>,
156/// }
157///
158/// impl DfsHooks for CalleesFirst {
159///     fn enter_node(&mut self, _method: u32, _: &mut DfsControl<'_>) -> bool {
160///         true
161///     }
162///
163///     fn leave_node(&mut self, method: u32, _: &mut DfsControl<'_>) {
164///         self.order.push(method);
165///     }
166/// }
167///
168/// let mut callees_first = CalleesFirst { order: Vec::new() };
169/// DfsTraverser::new(&calls).run_from(main, &mut callees_first);
170/// // callees_first.order: [1, 6, 8, 3, 7, 9, 4, 5, 2, 0] - parseArgs, parse, read, load,
171/// // format, write, save, show, run and main
172/// # assert_eq!(callees_first.order, [1, 6, 8, 3, 7, 9, 4, 5, 2, 0]);
173/// ```
174///
175/// Between its two hooks, a node is on the current path. The current path leads from the node where
176/// the search started to the node being searched. The hooks may call [`DfsControl::is_visited`] and
177/// [`DfsControl::is_on_stack`], end the search at a node by returning `false` from
178/// [`enter_node`](DfsHooks::enter_node), and end the whole run with [`DfsControl::stop`]. A closure,
179/// which is a set of hooks with only the preorder hook, counts the nodes that a run from node 1
180/// reaches:
181///
182/// ```
183/// use graphity_core::{DfsTraverser, GraphBuilder};
184///
185/// let mut b = GraphBuilder::new();
186/// b.add_nodes(4);
187/// b.add_edge_pairs(&[0, 1, 1, 2, 0, 3]);
188/// let graph = b.build();
189///
190/// let mut count = 0;
191/// DfsTraverser::new(&graph).run_from(1, &mut |_node| { count += 1; true });
192/// assert_eq!(count, 2);
193/// ```
194///
195/// [`run`](Self::run) searches from every node in ascending order, [`run_from`](Self::run_from)
196/// from one node and [`run_from_nodes`](Self::run_from_nodes) from several, such as the root nodes
197/// that [`graphs::root_nodes`](crate::graphs::root_nodes) returns. The visited nodes add up over the
198/// runs of a traverser: a node is visited at most once in the lifetime of the traverser, and a later
199/// run skips it.
200///
201/// A hook cannot start another run of the same traverser. Java throws `IllegalStateException`; in
202/// Rust, a run borrows the traverser mutably and a hook receives only a [`DfsControl`], so the borrow
203/// checker rejects the call at compile time:
204///
205/// ```compile_fail,E0499
206/// use graphity_core::{DfsTraverser, GraphBuilder};
207///
208/// let graph = GraphBuilder::new().build();
209/// let mut traverser = DfsTraverser::new(&graph);
210/// traverser.run(&mut |_node| {
211///     traverser.run_from(0, &mut |_| true); // error: the traverser is borrowed by the run
212///     true
213/// });
214/// ```
215///
216/// If a run ends with a panic from a hook or from the search, the state of the traverser is undefined:
217/// nodes of the interrupted path may still count as on the path, for example. A new traverser is
218/// needed for further runs.
219///
220/// [`DfsEdgeTraverser`](crate::DfsEdgeTraverser) also calls a hook for every edge, which suits
221/// searches that look at edges to nodes already visited. This type calls no such hook, which makes it
222/// the faster choice where node hooks suffice. [`FrontierTraverser`](crate::FrontierTraverser)
223/// searches breadth-first. Common searches are ready-made, such as [`top_order`](crate::top_order),
224/// [`EdgeTypes`](crate::EdgeTypes), [`back_edges`](crate::back_edges) and
225/// [`graphs::find_cycle`](crate::graphs::find_cycle).
226///
227/// A traverser is mutable, and a run borrows it mutably, so the borrow rules keep two threads from
228/// running it at once - Java's instances are not safe to share between threads.
229///
230/// **Memory:** 2 bits per node for the visited state, and up to 8 x node_count bytes for the stack,
231/// which grows with the deepest path searched; the graph's arrays are shared.
232#[derive(Debug, Clone)]
233pub struct DfsTraverser {
234    graph: Graph,
235    /// Visited and on-stack flags, 2 bits per node, 16 nodes per word. Cumulative across runs.
236    state: Vec<u32>,
237    /// The search stack: two interleaved entries per frame, the node and its resume position.
238    /// Only carries the capacity across runs.
239    frames: Vec<u32>,
240}
241
242impl DfsTraverser {
243    /// Returns a traverser for `graph`, with no node visited - Java's constructor. The graph's arrays are
244    /// shared.
245    ///
246    /// **Time:** O(node_count).
247    pub fn new(graph: &Graph) -> Self {
248        let n = graph.node_count();
249        Self {
250            graph: graph.clone(),
251            state: vec![0; (n as usize >> 4) + 1],
252            frames: dfs_frames::initial(n),
253        }
254    }
255
256    /// Returns the graph that this traverser searches - Java's protected field `graph`.
257    ///
258    /// **Time:** O(1).
259    #[inline]
260    pub fn graph(&self) -> &Graph {
261        &self.graph
262    }
263
264    /// Returns whether a run has reached `node` so far - [`DfsControl::is_visited`] outside a run.
265    ///
266    /// `node` is a node ID in `0..node_count`; for any other value the method returns `false` or panics
267    /// with an `index out of bounds` message.
268    ///
269    /// **Time:** O(1).
270    #[inline]
271    pub fn is_visited(&self, node: u32) -> bool {
272        flags(&self.state, node) & VISITED != 0
273    }
274
275    /// Returns whether `node` is on the current path - [`DfsControl::is_on_stack`] outside a run. Outside
276    /// a run, no node is on the path.
277    ///
278    /// `node` is a node ID in `0..node_count`; for any other value the method returns `false` or panics
279    /// with an `index out of bounds` message.
280    ///
281    /// **Time:** O(1).
282    #[inline]
283    pub fn is_on_stack(&self, node: u32) -> bool {
284        flags(&self.state, node) & ON_STACK != 0
285    }
286
287    /// Searches from every node not visited yet, in ascending order, until every node is visited.
288    ///
289    /// A node that no earlier search has reached when its turn comes starts a search of its own.
290    ///
291    /// **Time:** O(node_count + edge_count), plus the hooks.
292    ///
293    /// # Panics
294    /// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
295    pub fn run<H: DfsHooks + ?Sized>(&mut self, hooks: &mut H) {
296        let mut stop = false;
297        for root in 0..self.graph.node_count() {
298            if !self.dfs_if_unvisited(root, hooks, &mut stop) {
299                return;
300            }
301        }
302    }
303
304    /// Searches from `start_node`, visiting the nodes it reaches that are not visited yet - Java's
305    /// overload `run(int)`.
306    ///
307    /// If `start_node` is visited already, nothing happens.
308    ///
309    /// **Time:** O(reachable nodes + reachable edges), plus the hooks.
310    ///
311    /// # Panics
312    /// With an `index out of bounds` message if `start_node` is not in `0..node_count`; with an
313    /// `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
314    #[track_caller]
315    pub fn run_from<H: DfsHooks + ?Sized>(&mut self, start_node: u32, hooks: &mut H) {
316        check_index(start_node, self.graph.node_count());
317        let mut stop = false;
318        self.dfs_if_unvisited(start_node, hooks, &mut stop);
319    }
320
321    /// Searches from each of `start_nodes` in list order, skipping those visited already - Java's
322    /// overload `run(IntList)`.
323    ///
324    /// The list is checked before the first hook, so a start node out of range leaves the traverser
325    /// unchanged. [`DfsControl::stop`] ends the whole call, not only the search from one start node. The
326    /// run borrows the list, so it cannot change until the call returns.
327    ///
328    /// **Time:** O(start_nodes.len() + reachable nodes + reachable edges), plus the hooks.
329    ///
330    /// # Panics
331    /// With an `index out of bounds` message if a start node is not in `0..node_count`; with an
332    /// `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
333    #[track_caller]
334    pub fn run_from_nodes<H: DfsHooks + ?Sized>(&mut self, start_nodes: &[u32], hooks: &mut H) {
335        crate::error::check_nodes(start_nodes, self.graph.node_count());
336        let mut stop = false;
337        for &start in start_nodes {
338            if !self.dfs_if_unvisited(start, hooks, &mut stop) {
339                return;
340            }
341        }
342    }
343
344    /// The single entry of every run method: the visited check lives here only. Returns `false`
345    /// if the traversal was stopped.
346    fn dfs_if_unvisited<H: DfsHooks + ?Sized>(
347        &mut self,
348        root: u32,
349        hooks: &mut H,
350        stop: &mut bool,
351    ) -> bool {
352        self.is_visited(root) || self.dfs_from(root as usize, hooks, stop)
353    }
354
355    /// Iterative depth-first search from `root`, which is unvisited. The scan keeps its cursor in
356    /// locals and touches the stack only when it descends. Returns `false` if stopped.
357    fn dfs_from<H: DfsHooks + ?Sized>(
358        &mut self,
359        root: usize,
360        hooks: &mut H,
361        stop: &mut bool,
362    ) -> bool {
363        let Self {
364            graph,
365            state,
366            frames,
367        } = self;
368        let graph = &*graph;
369        let out = graph.out_adjacency_start();
370        let adj = graph.out_adjacency();
371        let n = graph.node_count();
372
373        macro_rules! call {
374            ($hook:ident, $node:expr) => {{
375                let mut control = DfsControl::new(graph, &state[..], &mut *stop);
376                hooks.$hook($node as u32, &mut control)
377            }};
378        }
379
380        let r_shift = (root & 0xF) << 1;
381        state[root >> 4] |= (VISITED | ON_STACK) << r_shift;
382        let descend = call!(enter_node, root);
383        if *stop {
384            state[root >> 4] &= !(ON_STACK << r_shift);
385            return false;
386        }
387        if !descend {
388            state[root >> 4] &= !(ON_STACK << r_shift);
389            call!(leave_node, root);
390            return !*stop;
391        }
392        frames[0] = root as u32;
393        frames[1] = out[root];
394        let mut top = 0usize;
395
396        'outer: loop {
397            let u = frames[2 * top] as usize;
398            let end = out[u + 1] as usize;
399            let mut i = frames[2 * top + 1] as usize;
400            while i < end {
401                let v = adj[i] as usize;
402                i += 1;
403                let shift = (v & 0xF) << 1;
404                if (state[v >> 4] >> shift) & VISITED == 0 {
405                    // Tree edge.
406                    state[v >> 4] |= (VISITED | ON_STACK) << shift;
407                    let descend = call!(enter_node, v);
408                    if *stop {
409                        state[v >> 4] &= !(ON_STACK << shift);
410                        leave_stack(state, frames, top);
411                        return false;
412                    }
413                    if descend {
414                        frames[2 * top + 1] = i as u32;
415                        top += 1;
416                        if top == frames.len() >> 1 {
417                            dfs_frames::grow(frames, n);
418                        }
419                        frames[2 * top] = v as u32;
420                        frames[2 * top + 1] = out[v];
421                        continue 'outer;
422                    }
423                    // Pruned: the frame's cursor is saved only on descent; u's scan goes on.
424                    state[v >> 4] &= !(ON_STACK << shift);
425                    call!(leave_node, v);
426                    if *stop {
427                        leave_stack(state, frames, top);
428                        return false;
429                    }
430                }
431            }
432            state[u >> 4] &= !(ON_STACK << ((u & 0xF) << 1));
433            call!(leave_node, u);
434            if top == 0 {
435                return !*stop;
436            }
437            top -= 1;
438            if *stop {
439                leave_stack(state, frames, top);
440                return false;
441            }
442        }
443    }
444}