Skip to main content

datalog_structural_model/ir/head/
collections.rs

1//! Non-empty collections inside a [`RuleHead`](super::RuleHead): they cannot
2//! be built empty, neither by constructor nor by deserialization.
3
4use std::collections::BTreeSet;
5use std::{error::Error, fmt};
6
7use crate::error_code::ErrorCode;
8use crate::ir::atom::Atom;
9use crate::ir::symbols::VariableSymbol;
10
11/// Which head collection was given no elements.
12#[derive(
13    Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
14)]
15pub enum HeadCollectionKind {
16    /// A [`HeadConjunction`].
17    Conjunction,
18    /// A [`HeadDisjunction`].
19    Disjunction,
20    /// An [`ExistentialVariables`] set.
21    ExistentialVariables,
22}
23
24impl fmt::Display for HeadCollectionKind {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        f.write_str(match self {
27            Self::Conjunction => "head conjunction",
28            Self::Disjunction => "head disjunction",
29            Self::ExistentialVariables => "existential variable set",
30        })
31    }
32}
33
34/// A head collection was constructed without elements.
35#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct EmptyHeadCollection {
38    kind: HeadCollectionKind,
39}
40
41impl EmptyHeadCollection {
42    /// Code of every empty head collection.
43    pub const CODE_EMPTY_HEAD_COLLECTION: ErrorCode = ErrorCode::new("empty-head-collection");
44
45    const fn new(kind: HeadCollectionKind) -> Self {
46        Self { kind }
47    }
48
49    /// The collection that was empty.
50    #[must_use]
51    pub const fn kind(&self) -> HeadCollectionKind {
52        self.kind
53    }
54
55    /// Stable kebab-case code of this error.
56    #[must_use]
57    pub const fn code(&self) -> ErrorCode {
58        Self::CODE_EMPTY_HEAD_COLLECTION
59    }
60}
61
62impl fmt::Display for EmptyHeadCollection {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(
65            f,
66            "[{}] a {} needs at least one element",
67            self.code(),
68            self.kind
69        )
70    }
71}
72
73impl Error for EmptyHeadCollection {}
74
75/// A non-empty conjunction of head atoms, in authored order.
76#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
77#[serde(try_from = "Vec<Atom>", into = "Vec<Atom>")]
78pub struct HeadConjunction(
79    // bounded: atoms of one authored rule head.
80    Vec<Atom>,
81);
82
83impl HeadConjunction {
84    /// A conjunction of `atoms`.
85    /// # Errors
86    /// Rejects an empty atom list.
87    pub fn try_new(atoms: Vec<Atom>) -> Result<Self, EmptyHeadCollection> {
88        if atoms.is_empty() {
89            return Err(EmptyHeadCollection::new(HeadCollectionKind::Conjunction));
90        }
91        Ok(Self(atoms))
92    }
93
94    /// The atoms, never empty.
95    #[must_use]
96    pub fn atoms(&self) -> &[Atom] {
97        &self.0
98    }
99
100    /// Mutable access to the atoms; the count cannot change.
101    pub fn atoms_mut(&mut self) -> &mut [Atom] {
102        &mut self.0
103    }
104}
105
106impl TryFrom<Vec<Atom>> for HeadConjunction {
107    type Error = EmptyHeadCollection;
108    fn try_from(atoms: Vec<Atom>) -> Result<Self, Self::Error> {
109        Self::try_new(atoms)
110    }
111}
112
113impl From<HeadConjunction> for Vec<Atom> {
114    fn from(conjunction: HeadConjunction) -> Self {
115        conjunction.0
116    }
117}
118
119impl From<Atom> for HeadConjunction {
120    fn from(atom: Atom) -> Self {
121        Self(vec![atom])
122    }
123}
124
125/// A non-empty disjunction of head conjunctions, in authored order.
126#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
127#[serde(try_from = "Vec<HeadConjunction>", into = "Vec<HeadConjunction>")]
128pub struct HeadDisjunction(
129    // bounded: disjuncts of one authored rule head.
130    Vec<HeadConjunction>,
131);
132
133impl HeadDisjunction {
134    /// A disjunction of `disjuncts`.
135    /// # Errors
136    /// Rejects an empty disjunct list.
137    pub fn try_new(disjuncts: Vec<HeadConjunction>) -> Result<Self, EmptyHeadCollection> {
138        if disjuncts.is_empty() {
139            return Err(EmptyHeadCollection::new(HeadCollectionKind::Disjunction));
140        }
141        Ok(Self(disjuncts))
142    }
143
144    /// The disjuncts, never empty.
145    #[must_use]
146    pub fn disjuncts(&self) -> &[HeadConjunction] {
147        &self.0
148    }
149
150    /// Mutable access to the disjuncts; the count cannot change.
151    pub fn disjuncts_mut(&mut self) -> &mut [HeadConjunction] {
152        &mut self.0
153    }
154}
155
156impl TryFrom<Vec<HeadConjunction>> for HeadDisjunction {
157    type Error = EmptyHeadCollection;
158    fn try_from(disjuncts: Vec<HeadConjunction>) -> Result<Self, Self::Error> {
159        Self::try_new(disjuncts)
160    }
161}
162
163impl From<HeadDisjunction> for Vec<HeadConjunction> {
164    fn from(disjunction: HeadDisjunction) -> Self {
165        disjunction.0
166    }
167}
168
169/// A non-empty set of existentially quantified head variables, kept in
170/// symbol order without duplicates so equal sets have one encoding.
171#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
172#[serde(try_from = "Vec<VariableSymbol>", into = "Vec<VariableSymbol>")]
173pub struct ExistentialVariables(
174    // bounded: variables of one authored rule head.
175    Vec<VariableSymbol>,
176);
177
178impl ExistentialVariables {
179    /// The set of `variables`; duplicates collapse.
180    /// # Errors
181    /// Rejects an empty variable list.
182    pub fn try_new(
183        variables: impl IntoIterator<Item = VariableSymbol>,
184    ) -> Result<Self, EmptyHeadCollection> {
185        let set: BTreeSet<VariableSymbol> = variables.into_iter().collect();
186        if set.is_empty() {
187            return Err(EmptyHeadCollection::new(
188                HeadCollectionKind::ExistentialVariables,
189            ));
190        }
191        Ok(Self(set.into_iter().collect()))
192    }
193
194    /// The variables in symbol order, never empty.
195    #[must_use]
196    pub fn variables(&self) -> &[VariableSymbol] {
197        &self.0
198    }
199
200    /// Whether `variable` is existentially quantified.
201    #[must_use]
202    pub fn contains(&self, variable: &VariableSymbol) -> bool {
203        self.0.binary_search(variable).is_ok()
204    }
205}
206
207impl TryFrom<Vec<VariableSymbol>> for ExistentialVariables {
208    type Error = EmptyHeadCollection;
209    fn try_from(variables: Vec<VariableSymbol>) -> Result<Self, Self::Error> {
210        Self::try_new(variables)
211    }
212}
213
214impl From<ExistentialVariables> for Vec<VariableSymbol> {
215    fn from(variables: ExistentialVariables) -> Self {
216        variables.0
217    }
218}