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::EqualityMode;
11use crate::ir::{Atom, Program, RuleHead, Term, VariableSymbol};
12use crate::position::{AtomSlot, HeadAtomPath, RuleIndex, RuleSite};
13use crate::scc::SuccessorGraph;
14use crate::stratify::overlaps;
15
16#[derive(Debug, Default)]
19struct PositionGraph {
20 equality_mode: EqualityMode,
21 ids: BTreeMap<ArgumentPosition, usize>,
23 positions: Vec<ArgumentPosition>,
24 successors: Vec<Vec<(usize, bool)>>,
26 special: Vec<SpecialEdge>,
27}
28
29impl PositionGraph {
30 fn build(program: &Program, equality_mode: EqualityMode) -> Self {
31 let mut graph = Self {
32 equality_mode,
33 ..Self::default()
34 };
35 let scopes: Vec<_> = program
37 .rules
38 .iter()
39 .enumerate()
40 .map(|(index, rule)| VariableSources::of_body(RuleIndex::new(index), &rule.body))
41 .collect();
42 for (index, (rule, sources)) in program.rules.iter().zip(&scopes).enumerate() {
43 let head = HeadOccurrences::new(RuleIndex::new(index), &rule.head);
44 graph.add_head(&head, sources);
45 }
46 for (producer, rule) in program.rules.iter().enumerate() {
47 let head = HeadOccurrences::new(RuleIndex::new(producer), &rule.head);
48 graph.add_flows(&head, &scopes);
49 }
50 graph
51 }
52
53 fn node(&mut self, position: &ArgumentPosition) -> usize {
54 if let Some(&id) = self.ids.get(position) {
55 return id;
56 }
57 let id = self.positions.len();
58 self.ids.insert(position.clone(), id);
59 self.positions.push(position.clone());
60 self.successors.push(Vec::new());
61 id
62 }
63
64 fn edge(
65 &mut self,
66 from: &ArgumentPosition,
67 to: &ArgumentPosition,
68 kind: Option<InventionKind>,
69 ) {
70 let source = self.node(from);
71 let target = self.node(to);
72 self.successors[source].push((target, kind.is_some()));
73 if let Some(kind) = kind {
74 self.special.push(SpecialEdge {
75 from: from.clone(),
76 to: to.clone(),
77 kind,
78 });
79 }
80 }
81
82 fn add_head(&mut self, head: &HeadOccurrences<'_>, sources: &VariableSources<'_>) {
87 for (path, atom) in head.head.atoms() {
88 for (slot, term) in atom.terms.iter().enumerate() {
89 let to = head.position(path, atom, slot);
90 self.node(&to);
91 let wrapper = match term {
92 Term::Variable(_) | Term::Constant(_) => None,
93 Term::TripleTerm(_) => Some(InventionKind::TripleTerm),
94 Term::Skolem { .. } => Some(InventionKind::Skolem),
95 };
96 let mut existential = false;
97 term.visit_variables(&mut |variable| {
98 existential |= head.head.is_existential(variable);
99 if let Some(kind) = sources.clock_invention(variable) {
100 for body in &sources.atoms {
104 for slot in 0..body.atom.arity() {
105 self.edge(
106 &body.position(head.rule, slot),
107 &to,
108 Some(wrapper.unwrap_or(kind)),
109 );
110 }
111 }
112 }
113 for source in sources.of(variable) {
114 self.edge(&source.position, &to, wrapper.or(source.invention));
115 }
116 });
117 if existential {
118 for variable in head.frontier() {
119 for source in sources.of(&variable) {
120 self.edge(&source.position, &to, Some(InventionKind::Existential));
121 }
122 }
123 }
124 }
125 }
126 }
127
128 fn add_flows(&mut self, head: &HeadOccurrences<'_>, scopes: &[VariableSources<'_>]) {
131 let mode = self.equality_mode;
132 for (path, atom) in head.head.atoms() {
133 for (consumer, scope) in scopes.iter().enumerate() {
134 for body in scope.atoms.iter().filter(|body| match mode {
135 EqualityMode::Default => overlaps(atom, body.atom),
136 EqualityMode::SameAs => {
137 atom.predicate == body.atom.predicate && atom.arity() == body.atom.arity()
138 }
139 }) {
140 for slot in 0..atom.arity() {
141 let from = head.position(path, atom, slot);
142 let to = body.position(RuleIndex::new(consumer), slot);
143 self.edge(&from, &to, None);
144 }
145 }
146 }
147 }
148 }
149
150 fn component_of(&self, sccs: &[BTreeSet<usize>]) -> Vec<usize> {
151 let mut component = vec![0; self.positions.len()];
153 for (index, members) in sccs.iter().enumerate() {
154 for &node in members {
155 component[node] = index;
156 }
157 }
158 component
159 }
160
161 fn violation(
162 &self,
163 sccs: &[BTreeSet<usize>],
164 component: &[usize],
165 ) -> Option<TerminationViolation> {
166 let edge = self
167 .special
168 .iter()
169 .filter(|edge| component[self.ids[&edge.from]] == component[self.ids[&edge.to]])
170 .min()?;
171 let members = &sccs[component[self.ids[&edge.from]]];
172 let positions = members
173 .iter()
174 .map(|&id| self.positions[id].clone())
175 .collect();
176 Some(TerminationViolation::new(
177 TerminationCriterion::WeaklyAcyclic,
178 self.equality_mode,
179 edge.clone(),
180 positions,
181 ))
182 }
183
184 fn certificate(&self, sccs: &[BTreeSet<usize>], component: &[usize]) -> WeakAcyclicity {
188 let mut rank = vec![0_usize; sccs.len()];
189 for index in (0..sccs.len()).rev() {
190 for &node in &sccs[index] {
191 for &(target, special) in &self.successors[node] {
192 let target = component[target];
193 if target != index {
194 rank[target] = rank[target].max(rank[index] + usize::from(special));
195 }
196 }
197 }
198 }
199 let skolem_depth = rank.iter().copied().max().unwrap_or(0);
200 let deepest = (skolem_depth > 0)
201 .then(|| {
202 self.ids
203 .iter()
204 .find(|&(_, &id)| rank[component[id]] == skolem_depth)
205 .map(|(position, _)| position.clone())
206 })
207 .flatten();
208 WeakAcyclicity {
209 law_version: TerminationCriterion::WeaklyAcyclic.law_version(),
210 equality_mode: self.equality_mode,
211 positions: self.positions.len(),
212 special_edges: self.special.len(),
213 skolem_depth,
214 deepest,
215 }
216 }
217}
218
219struct HeadOccurrences<'a> {
221 rule: RuleIndex,
222 head: &'a RuleHead,
223}
224
225impl<'a> HeadOccurrences<'a> {
226 fn new(rule: RuleIndex, head: &'a RuleHead) -> Self {
227 Self { rule, head }
228 }
229
230 fn position(&self, path: HeadAtomPath, atom: &Atom, slot: usize) -> ArgumentPosition {
231 ArgumentPosition::new(
232 atom.predicate.clone(),
233 AtomSlot::new(slot),
234 self.rule,
235 RuleSite::Head(path),
236 )
237 }
238
239 fn frontier(&self) -> impl Iterator<Item = VariableSymbol> + '_ {
242 self.head
243 .variables()
244 .into_iter()
245 .filter(|variable| !self.head.is_existential(variable))
246 }
247}
248
249impl SuccessorGraph for PositionGraph {
250 fn node_count(&self) -> usize {
251 self.positions.len()
252 }
253
254 fn successor(&self, node: usize, nth: usize) -> Option<usize> {
255 self.successors[node].get(nth).map(|&(target, _)| target)
256 }
257}
258
259impl Program {
260 pub fn check_weak_acyclicity(&self) -> Result<WeakAcyclicity, TerminationViolation> {
287 self.check_weak_acyclicity_with_equality_mode(EqualityMode::Default)
288 }
289
290 pub fn check_weak_acyclicity_with_equality_mode(
303 &self,
304 equality_mode: EqualityMode,
305 ) -> Result<WeakAcyclicity, TerminationViolation> {
306 let graph = PositionGraph::build(self, equality_mode);
307 let sccs = graph.strongly_connected_components();
308 let component = graph.component_of(&sccs);
309 match graph.violation(&sccs, &component) {
310 Some(violation) => Err(violation),
311 None => Ok(graph.certificate(&sccs, &component)),
312 }
313 }
314}