vers3 0.2.0

Explicit-state model checking library
Documentation
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026, Marco Elver <me@marcoelver.com>

//! Utility functions.

use std::collections::{HashMap, HashSet};
use std::hash::Hash;

/// Returns `true` if the directed graph described by `edges` is acyclic (a DAG).
///
/// Uses iterative DFS with an explicit recursion stack to avoid stack overflows
/// on deep graphs. Each edge is a `(from, to)` pair; duplicate edges are ignored.
pub fn is_acyclic<N: Eq + Hash + Copy>(edges: &HashSet<(N, N)>) -> bool {
    find_cycle(edges).is_none()
}

/// Returns a cycle as a `Vec<N>` if one exists, or `None` if the graph is acyclic.
///
/// Uses iterative DFS; when a back-edge is found the current DFS path is sliced
/// from the cycle entry point to the current node to form the cycle.
pub fn find_cycle<N: Eq + Hash + Copy>(edges: &HashSet<(N, N)>) -> Option<Vec<N>> {
    // Build adjacency list.
    let mut adj: HashMap<N, Vec<N>> = HashMap::new();
    for &(from, to) in edges {
        adj.entry(from).or_default().push(to);
    }

    let nodes: Vec<N> = adj.keys().copied().collect();
    let mut visited: HashSet<N> = HashSet::new();

    // Iterative DFS: each stack frame is (node, index into its neighbor list).
    // `on_stack` tracks nodes on the current DFS path for cycle detection.
    // `path` mirrors the DFS stack with actual node values for cycle extraction.
    let mut on_stack: HashSet<N> = HashSet::new();
    let mut path: Vec<N> = Vec::new();

    for start in nodes {
        if visited.contains(&start) {
            continue;
        }
        // Stack entries: (node, neighbor_index).
        let mut stack: Vec<(N, usize)> = vec![(start, 0)];
        on_stack.insert(start);
        path.push(start);

        while let Some((node, idx)) = stack.last_mut() {
            let node = *node;
            let neighbors = adj.get(&node).map(Vec::as_slice).unwrap_or(&[]);
            if *idx < neighbors.len() {
                let next = neighbors[*idx];
                *idx += 1;
                if on_stack.contains(&next) {
                    // Back-edge: extract the cycle from `path`.
                    let cycle_start = path.iter().position(|&n| n == next).unwrap();
                    return Some(path[cycle_start..].to_vec());
                }
                if !visited.contains(&next) {
                    on_stack.insert(next);
                    path.push(next);
                    stack.push((next, 0));
                }
            } else {
                // All neighbors processed; node is finished.
                visited.insert(node);
                on_stack.remove(&node);
                path.pop();
                stack.pop();
            }
        }
    }

    None
}

// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn edges(pairs: &[(u64, u64)]) -> HashSet<(u64, u64)> {
        pairs.iter().copied().collect()
    }

    #[test]
    fn acyclic_empty() {
        assert!(is_acyclic::<u64>(&HashSet::new()));
    }

    #[test]
    fn acyclic_single_edge() {
        assert!(is_acyclic(&edges(&[(0, 1)])));
    }

    #[test]
    fn acyclic_line() {
        assert!(is_acyclic(&edges(&[(0, 1), (1, 2), (2, 3)])));
    }

    #[test]
    fn acyclic_diamond() {
        // 0 → 1, 0 → 2, 1 → 3, 2 → 3  (shared sink, no cycle)
        assert!(is_acyclic(&edges(&[(0, 1), (0, 2), (1, 3), (2, 3)])));
    }

    #[test]
    fn cyclic_self_loop() {
        assert!(!is_acyclic(&edges(&[(0, 0)])));
    }

    #[test]
    fn cyclic_two_node() {
        assert!(!is_acyclic(&edges(&[(0, 1), (1, 0)])));
    }

    #[test]
    fn cyclic_triangle() {
        assert!(!is_acyclic(&edges(&[(0, 1), (1, 2), (2, 0)])));
    }

    #[test]
    fn cyclic_buried_in_dag() {
        // DAG prefix (0→1→2) then cycle (2→3→2).
        assert!(!is_acyclic(&edges(&[(0, 1), (1, 2), (2, 3), (3, 2)])));
    }

    #[test]
    fn find_cycle_returns_none_for_dag() {
        assert!(find_cycle(&edges(&[(0, 1), (1, 2), (2, 3)])).is_none());
    }

    #[test]
    fn find_cycle_self_loop() {
        let c = find_cycle(&edges(&[(0, 0)])).unwrap();
        assert_eq!(c, vec![0]);
    }

    #[test]
    fn find_cycle_triangle() {
        // 0→1→2→0: cycle should contain all three nodes.
        let c = find_cycle(&edges(&[(0, 1), (1, 2), (2, 0)])).unwrap();
        assert_eq!(c.len(), 3);
    }

    #[test]
    fn find_cycle_buried() {
        // DAG prefix then cycle: only the cyclic nodes returned.
        let c = find_cycle(&edges(&[(0, 1), (1, 2), (2, 3), (3, 2)])).unwrap();
        // Cycle is 2→3→2, so two nodes.
        assert_eq!(c.len(), 2);
        assert!(c.contains(&2));
        assert!(c.contains(&3));
    }
}