Skip to main content

datalog_structural_model/ir/head/
rule_head.rs

1//! [`RuleHead`] — what a rule concludes from its body.
2
3use std::collections::BTreeSet;
4
5use super::collections::{ExistentialVariables, HeadConjunction, HeadDisjunction};
6use super::form::HeadForm;
7use crate::ir::atom::Atom;
8use crate::ir::symbols::VariableSymbol;
9use crate::position::{HeadAtomIndex, HeadAtomPath, HeadDisjunctIndex};
10
11/// The head of a [`Rule`](crate::Rule).
12///
13/// Every head reads as a disjunction of conjunctions of atoms: an atom is one
14/// disjunct of one atom, and [`Self::Falsum`] has no disjunct at all. Atoms
15/// are addressed by [`HeadAtomPath`] in that reading.
16#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
17#[serde(deny_unknown_fields)]
18pub enum RuleHead {
19    /// One atom: plain Datalog.
20    Atom(Atom),
21    /// Several atoms derived together from one body match.
22    Conjunction(HeadConjunction),
23    /// `∃ variables . conjunction`: each body match requires witnesses for
24    /// the existential variables.
25    Existential {
26        /// The existentially quantified variables.
27        variables: ExistentialVariables,
28        /// The atoms over body and existential variables.
29        conjunction: HeadConjunction,
30    },
31    /// At least one of the disjuncts holds for each body match.
32    Disjunction(HeadDisjunction),
33    /// `false`: the body must have no match. An inconsistency constraint.
34    Falsum,
35}
36
37impl RuleHead {
38    /// The head's logical form; see [`HeadForm`] for the precedence.
39    #[must_use]
40    pub fn form(&self) -> HeadForm {
41        match self {
42            Self::Falsum => HeadForm::Inconsistency,
43            Self::Existential { .. } => HeadForm::Existential,
44            Self::Disjunction(disjunction) if disjunction.disjuncts().len() > 1 => {
45                HeadForm::Disjunctive
46            }
47            Self::Atom(_) | Self::Conjunction(_) | Self::Disjunction(_) => {
48                if self
49                    .disjunct(HeadDisjunctIndex::new(0))
50                    .map_or(0, <[Atom]>::len)
51                    > 1
52                {
53                    HeadForm::Conjunctive
54                } else {
55                    HeadForm::Atomic
56                }
57            }
58        }
59    }
60
61    /// The single atom of a [`Self::Atom`] head; `None` for any other head.
62    #[must_use]
63    pub fn as_atom(&self) -> Option<&Atom> {
64        match self {
65            Self::Atom(atom) => Some(atom),
66            Self::Conjunction(_)
67            | Self::Existential { .. }
68            | Self::Disjunction(_)
69            | Self::Falsum => None,
70        }
71    }
72
73    /// Mutable access to the single atom of a [`Self::Atom`] head.
74    pub fn as_atom_mut(&mut self) -> Option<&mut Atom> {
75        match self {
76            Self::Atom(atom) => Some(atom),
77            Self::Conjunction(_)
78            | Self::Existential { .. }
79            | Self::Disjunction(_)
80            | Self::Falsum => None,
81        }
82    }
83
84    /// Number of disjuncts: zero for [`Self::Falsum`], otherwise at least one.
85    #[must_use]
86    pub fn disjunct_count(&self) -> usize {
87        match self {
88            Self::Falsum => 0,
89            Self::Disjunction(disjunction) => disjunction.disjuncts().len(),
90            Self::Atom(_) | Self::Conjunction(_) | Self::Existential { .. } => 1,
91        }
92    }
93
94    /// The atoms of one disjunct, or `None` past the last disjunct.
95    #[must_use]
96    pub fn disjunct(&self, index: HeadDisjunctIndex) -> Option<&[Atom]> {
97        match (self, index.get()) {
98            (Self::Atom(atom), 0) => Some(std::slice::from_ref(atom)),
99            (Self::Conjunction(conjunction) | Self::Existential { conjunction, .. }, 0) => {
100                Some(conjunction.atoms())
101            }
102            (Self::Disjunction(disjunction), index) => disjunction
103                .disjuncts()
104                .get(index)
105                .map(HeadConjunction::atoms),
106            _ => None,
107        }
108    }
109
110    /// Every head atom with its path, disjunct by disjunct in authored order.
111    pub fn atoms(&self) -> impl Iterator<Item = (HeadAtomPath, &Atom)> {
112        (0..self.disjunct_count()).flat_map(move |disjunct| {
113            let disjunct = HeadDisjunctIndex::new(disjunct);
114            self.disjunct(disjunct)
115                .into_iter()
116                .flatten()
117                .enumerate()
118                .map(move |(atom, value)| {
119                    (HeadAtomPath::new(disjunct, HeadAtomIndex::new(atom)), value)
120                })
121        })
122    }
123
124    /// Mutable access to every head atom, disjunct by disjunct.
125    pub fn atoms_mut(&mut self) -> Box<dyn Iterator<Item = &mut Atom> + '_> {
126        match self {
127            Self::Atom(atom) => Box::new(std::iter::once(atom)),
128            Self::Conjunction(conjunction) | Self::Existential { conjunction, .. } => {
129                Box::new(conjunction.atoms_mut().iter_mut())
130            }
131            Self::Disjunction(disjunction) => Box::new(
132                disjunction
133                    .disjuncts_mut()
134                    .iter_mut()
135                    .flat_map(|disjunct| disjunct.atoms_mut().iter_mut()),
136            ),
137            Self::Falsum => Box::new(std::iter::empty()),
138        }
139    }
140
141    /// The existentially quantified variables; empty unless existential.
142    #[must_use]
143    pub fn existential_variables(&self) -> &[VariableSymbol] {
144        match self {
145            Self::Existential { variables, .. } => variables.variables(),
146            Self::Atom(_) | Self::Conjunction(_) | Self::Disjunction(_) | Self::Falsum => &[],
147        }
148    }
149
150    /// Whether `variable` is existentially quantified by this head.
151    #[must_use]
152    pub fn is_existential(&self, variable: &VariableSymbol) -> bool {
153        match self {
154            Self::Existential { variables, .. } => variables.contains(variable),
155            Self::Atom(_) | Self::Conjunction(_) | Self::Disjunction(_) | Self::Falsum => false,
156        }
157    }
158
159    /// Distinct variables of every head atom, existential ones included.
160    #[must_use]
161    pub fn variables(&self) -> BTreeSet<VariableSymbol> {
162        self.atoms()
163            .flat_map(|(_, atom)| atom.variables())
164            .collect()
165    }
166}
167
168impl From<Atom> for RuleHead {
169    fn from(atom: Atom) -> Self {
170        Self::Atom(atom)
171    }
172}