Skip to main content

datalog_structural_model/termination/
violation.rs

1//! [`TerminationViolation`] — the cyclic special edge that defeats a criterion.
2
3use std::{error::Error, fmt};
4
5use super::criterion::TerminationCriterion;
6use super::edge::{ArgumentPosition, SpecialEdge};
7use crate::error_code::ErrorCode;
8
9/// A value-inventing edge whose endpoints share a strongly connected
10/// component of the position graph, so a recursive program can keep
11/// inventing values. This defeats the criterion; it does not prove that
12/// every evaluation diverges.
13#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
14#[serde(deny_unknown_fields)]
15pub struct TerminationViolation {
16    criterion: TerminationCriterion,
17    edge: Box<SpecialEdge>,
18    // bounded: positions of one component of the finite program.
19    component: Vec<ArgumentPosition>,
20}
21
22impl TerminationViolation {
23    pub(super) fn new(
24        criterion: TerminationCriterion,
25        edge: SpecialEdge,
26        mut component: Vec<ArgumentPosition>,
27    ) -> Self {
28        component.sort();
29        Self {
30            criterion,
31            edge: Box::new(edge),
32            component,
33        }
34    }
35
36    /// The criterion that was not met.
37    #[must_use]
38    pub fn criterion(&self) -> TerminationCriterion {
39        self.criterion
40    }
41
42    /// The first cyclic special edge in canonical order.
43    #[must_use]
44    pub fn edge(&self) -> &SpecialEdge {
45        &self.edge
46    }
47
48    /// Positions of the edge's strongly connected component, sorted.
49    #[must_use]
50    pub fn component(&self) -> &[ArgumentPosition] {
51        &self.component
52    }
53
54    /// Code of every violation of [`TerminationCriterion::WeaklyAcyclic`].
55    pub const CODE_NOT_WEAKLY_ACYCLIC: ErrorCode = ErrorCode::new("not-weakly-acyclic");
56
57    /// Stable kebab-case code of this violation.
58    #[must_use]
59    pub fn code(&self) -> ErrorCode {
60        match self.criterion {
61            TerminationCriterion::WeaklyAcyclic => Self::CODE_NOT_WEAKLY_ACYCLIC,
62        }
63    }
64}
65
66impl fmt::Display for TerminationViolation {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        write!(
69            f,
70            "[{}] {} is not met: {} lies on a cycle through positions ",
71            self.code(),
72            self.criterion,
73            self.edge
74        )?;
75        for (index, position) in self.component.iter().enumerate() {
76            if index > 0 {
77                f.write_str("; ")?;
78            }
79            position.fmt(f)?;
80        }
81        Ok(())
82    }
83}
84
85impl Error for TerminationViolation {}