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