datalog_structural_model/termination/
graph.rs1use std::collections::{BTreeMap, BTreeSet};
4
5use super::criterion::TerminationCriterion;
6use super::edge::{ArgumentPosition, InventionKind, SpecialEdge};
7use super::sources::VariableSources;
8use super::verdict::WeakAcyclicity;
9use super::violation::TerminationViolation;
10use crate::ir::{Atom, Program, RuleHead, Term, VariableSymbol};
11use crate::position::{AtomSlot, HeadAtomPath, RuleIndex, RuleSite};
12use crate::scc::SuccessorGraph;
13use crate::stratify::overlaps;
14
15#[derive(Debug, Default)]
18struct PositionGraph {
19 ids: BTreeMap<ArgumentPosition, usize>,
21 positions: Vec<ArgumentPosition>,
22 successors: Vec<Vec<(usize, bool)>>,
24 special: Vec<SpecialEdge>,
25}
26
27impl PositionGraph {
28 fn build(program: &Program) -> Self {
29 let mut graph = Self::default();
30 let scopes: Vec<_> = program
32 .rules
33 .iter()
34 .enumerate()
35 .map(|(index, rule)| VariableSources::of_body(RuleIndex::new(index), &rule.body))
36 .collect();
37 for (index, (rule, sources)) in program.rules.iter().zip(&scopes).enumerate() {
38 let head = HeadOccurrences::new(RuleIndex::new(index), &rule.head);
39 graph.add_head(&head, sources);
40 }
41 for (producer, rule) in program.rules.iter().enumerate() {
42 let head = HeadOccurrences::new(RuleIndex::new(producer), &rule.head);
43 graph.add_flows(&head, &scopes);
44 }
45 graph
46 }
47
48 fn node(&mut self, position: &ArgumentPosition) -> usize {
49 if let Some(&id) = self.ids.get(position) {
50 return id;
51 }
52 let id = self.positions.len();
53 self.ids.insert(position.clone(), id);
54 self.positions.push(position.clone());
55 self.successors.push(Vec::new());
56 id
57 }
58
59 fn edge(
60 &mut self,
61 from: &ArgumentPosition,
62 to: &ArgumentPosition,
63 kind: Option<InventionKind>,
64 ) {
65 let source = self.node(from);
66 let target = self.node(to);
67 self.successors[source].push((target, kind.is_some()));
68 if let Some(kind) = kind {
69 self.special.push(SpecialEdge {
70 from: from.clone(),
71 to: to.clone(),
72 kind,
73 });
74 }
75 }
76
77 fn add_head(&mut self, head: &HeadOccurrences<'_>, sources: &VariableSources<'_>) {
82 for (path, atom) in head.head.atoms() {
83 for (slot, term) in atom.terms.iter().enumerate() {
84 let to = head.position(path, atom, slot);
85 self.node(&to);
86 let wrapper = match term {
87 Term::Variable(_) | Term::Constant(_) => None,
88 Term::TripleTerm(_) => Some(InventionKind::TripleTerm),
89 Term::Skolem { .. } => Some(InventionKind::Skolem),
90 };
91 let mut existential = false;
92 term.visit_variables(&mut |variable| {
93 existential |= head.head.is_existential(variable);
94 for source in sources.of(variable) {
95 self.edge(&source.position, &to, wrapper.or(source.invention));
96 }
97 });
98 if existential {
99 for variable in head.frontier() {
100 for source in sources.of(&variable) {
101 self.edge(&source.position, &to, Some(InventionKind::Existential));
102 }
103 }
104 }
105 }
106 }
107 }
108
109 fn add_flows(&mut self, head: &HeadOccurrences<'_>, scopes: &[VariableSources<'_>]) {
112 for (path, atom) in head.head.atoms() {
113 for (consumer, scope) in scopes.iter().enumerate() {
114 for body in scope.atoms.iter().filter(|body| overlaps(atom, body.atom)) {
115 for slot in 0..atom.arity() {
116 let from = head.position(path, atom, slot);
117 let to = body.position(RuleIndex::new(consumer), slot);
118 self.edge(&from, &to, None);
119 }
120 }
121 }
122 }
123 }
124
125 fn component_of(&self, sccs: &[BTreeSet<usize>]) -> Vec<usize> {
126 let mut component = vec![0; self.positions.len()];
128 for (index, members) in sccs.iter().enumerate() {
129 for &node in members {
130 component[node] = index;
131 }
132 }
133 component
134 }
135
136 fn violation(
137 &self,
138 sccs: &[BTreeSet<usize>],
139 component: &[usize],
140 ) -> Option<TerminationViolation> {
141 let edge = self
142 .special
143 .iter()
144 .filter(|edge| component[self.ids[&edge.from]] == component[self.ids[&edge.to]])
145 .min()?;
146 let members = &sccs[component[self.ids[&edge.from]]];
147 let positions = members
148 .iter()
149 .map(|&id| self.positions[id].clone())
150 .collect();
151 Some(TerminationViolation::new(
152 TerminationCriterion::WeaklyAcyclic,
153 edge.clone(),
154 positions,
155 ))
156 }
157
158 fn certificate(&self, sccs: &[BTreeSet<usize>], component: &[usize]) -> WeakAcyclicity {
162 let mut rank = vec![0_usize; sccs.len()];
163 for index in (0..sccs.len()).rev() {
164 for &node in &sccs[index] {
165 for &(target, special) in &self.successors[node] {
166 let target = component[target];
167 if target != index {
168 rank[target] = rank[target].max(rank[index] + usize::from(special));
169 }
170 }
171 }
172 }
173 let skolem_depth = rank.iter().copied().max().unwrap_or(0);
174 let deepest = (skolem_depth > 0)
175 .then(|| {
176 self.ids
177 .iter()
178 .find(|&(_, &id)| rank[component[id]] == skolem_depth)
179 .map(|(position, _)| position.clone())
180 })
181 .flatten();
182 WeakAcyclicity {
183 positions: self.positions.len(),
184 special_edges: self.special.len(),
185 skolem_depth,
186 deepest,
187 }
188 }
189}
190
191struct HeadOccurrences<'a> {
193 rule: RuleIndex,
194 head: &'a RuleHead,
195}
196
197impl<'a> HeadOccurrences<'a> {
198 fn new(rule: RuleIndex, head: &'a RuleHead) -> Self {
199 Self { rule, head }
200 }
201
202 fn position(&self, path: HeadAtomPath, atom: &Atom, slot: usize) -> ArgumentPosition {
203 ArgumentPosition::new(
204 atom.predicate.clone(),
205 AtomSlot::new(slot),
206 self.rule,
207 RuleSite::Head(path),
208 )
209 }
210
211 fn frontier(&self) -> impl Iterator<Item = VariableSymbol> + '_ {
214 self.head
215 .variables()
216 .into_iter()
217 .filter(|variable| !self.head.is_existential(variable))
218 }
219}
220
221impl SuccessorGraph for PositionGraph {
222 fn node_count(&self) -> usize {
223 self.positions.len()
224 }
225
226 fn successor(&self, node: usize, nth: usize) -> Option<usize> {
227 self.successors[node].get(nth).map(|&(target, _)| target)
228 }
229}
230
231impl Program {
232 pub fn check_weak_acyclicity(&self) -> Result<WeakAcyclicity, TerminationViolation> {
257 let graph = PositionGraph::build(self);
258 let sccs = graph.strongly_connected_components();
259 let component = graph.component_of(&sccs);
260 match graph.violation(&sccs, &component) {
261 Some(violation) => Err(violation),
262 None => Ok(graph.certificate(&sccs, &component)),
263 }
264 }
265}