Skip to main content

shacl_ir/compiled/
dependency_graph.rs

1use crate::shape_label_idx::ShapeLabelIdx;
2use petgraph::algo::is_cyclic_directed;
3use petgraph::visit::EdgeRef;
4use petgraph::{Directed, prelude::GraphMap};
5use std::fmt::Display;
6
7#[derive(Debug, Default, Clone)]
8pub struct DependencyGraph {
9    graph: GraphMap<ShapeLabelIdx, PosNeg, Directed>,
10}
11
12impl DependencyGraph {
13    pub fn new() -> Self {
14        DependencyGraph { graph: GraphMap::new() }
15    }
16
17    pub fn add_edge(&mut self, from: ShapeLabelIdx, to: ShapeLabelIdx, pos_neg: PosNeg) {
18        self.graph.add_edge(from, to, pos_neg);
19    }
20
21    pub fn neg_cycles(&self) -> Vec<Vec<(ShapeLabelIdx, ShapeLabelIdx, Vec<ShapeLabelIdx>)>> {
22        let mut result = Vec::new();
23        let scc = petgraph::algo::tarjan_scc(&self.graph);
24        for component in &scc {
25            let mut neg_cycle = Vec::new();
26            for node in component.iter().as_slice() {
27                let edges = self.graph.edges_directed(*node, petgraph::Direction::Outgoing);
28                for edge in edges {
29                    if component.contains(&edge.target()) && edge.weight().is_neg() {
30                        let mut shapes = Vec::new();
31                        for node in component.iter() {
32                            shapes.push(*node);
33                        }
34                        let target = edge.target();
35                        neg_cycle.push((*node, target, shapes));
36                        break;
37                    }
38                }
39            }
40            if !neg_cycle.is_empty() {
41                result.push(neg_cycle);
42            }
43        }
44        result
45    }
46
47    pub fn has_neg_cycle(&self) -> bool {
48        let neg_cycles = self.neg_cycles();
49        !neg_cycles.is_empty()
50    }
51
52    /// Check if the dependency graph has any cycles (including positive cycles).
53    pub fn has_cycles(&self) -> bool {
54        is_cyclic_directed(&self.graph)
55    }
56
57    pub fn all_edges(&self) -> DependencyGraphIter<'_> {
58        DependencyGraphIter {
59            inner: self.graph.all_edges(),
60        }
61    }
62}
63
64impl Display for DependencyGraph {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        writeln!(f, "Dependency Graph:")?;
67        for (from, posneg, to) in self.all_edges() {
68            writeln!(f, "  {} --{}--> {}", from, posneg, to)?;
69        }
70        Ok(())
71    }
72}
73
74/// Iterator over the edges of the dependency graph.
75/// The iterator yields tuples of the form (from, posneg, to).
76pub struct DependencyGraphIter<'a> {
77    inner: petgraph::graphmap::AllEdges<'a, ShapeLabelIdx, PosNeg, petgraph::Directed>,
78}
79impl Iterator for DependencyGraphIter<'_> {
80    type Item = (ShapeLabelIdx, PosNeg, ShapeLabelIdx);
81
82    fn next(&mut self) -> Option<Self::Item> {
83        self.inner.next().map(|(from, to, posneg)| (from, *posneg, to))
84    }
85}
86
87#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
88pub enum PosNeg {
89    #[default]
90    Pos,
91    Neg,
92}
93
94impl PosNeg {
95    pub fn is_pos(&self) -> bool {
96        matches!(self, PosNeg::Pos)
97    }
98
99    pub fn is_neg(&self) -> bool {
100        matches!(self, PosNeg::Neg)
101    }
102
103    pub fn pos() -> PosNeg {
104        PosNeg::Pos
105    }
106
107    pub fn neg() -> PosNeg {
108        PosNeg::Neg
109    }
110
111    pub fn change(&self) -> PosNeg {
112        match self {
113            PosNeg::Pos => PosNeg::Neg,
114            PosNeg::Neg => PosNeg::Pos,
115        }
116    }
117}
118
119impl Display for PosNeg {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        match self {
122            PosNeg::Pos => write!(f, "[+]"),
123            PosNeg::Neg => write!(f, "[-]"),
124        }
125    }
126}