Skip to main content

datalog_structural_model/position/
literal_path.rs

1//! [`LiteralPath`] — a literal in a rule body, possibly inside aggregates.
2
3use std::fmt;
4
5use super::index::LiteralIndex;
6
7/// Path from a rule body to one literal: the outer body position, then one
8/// inner-body position per enclosing aggregate.
9/// Deserialization rejects an empty path, which has no outer body position.
10#[derive(
11    Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
12)]
13#[serde(transparent)]
14pub struct LiteralPath(
15    // bounded: one step per authored aggregate nesting level.
16    #[serde(deserialize_with = "deserialize_steps")] Vec<LiteralIndex>,
17);
18
19fn deserialize_steps<'de, D>(deserializer: D) -> Result<Vec<LiteralIndex>, D::Error>
20where
21    D: serde::Deserializer<'de>,
22{
23    let steps = <Vec<LiteralIndex> as serde::Deserialize>::deserialize(deserializer)?;
24    if steps.is_empty() {
25        return Err(serde::de::Error::custom(
26            "literal path must contain at least one literal index",
27        ));
28    }
29    Ok(steps)
30}
31
32impl LiteralPath {
33    /// Path to a literal directly in the rule body.
34    #[must_use]
35    pub fn top(index: LiteralIndex) -> Self {
36        Self(vec![index])
37    }
38
39    /// Path to a literal inside the aggregate this path points to.
40    #[must_use]
41    pub fn inner(&self, index: LiteralIndex) -> Self {
42        let mut steps = self.0.clone();
43        steps.push(index);
44        Self(steps)
45    }
46
47    /// Outer body position followed by each inner-body position.
48    #[must_use]
49    pub fn steps(&self) -> &[LiteralIndex] {
50        &self.0
51    }
52
53    /// Position in the rule body of the outermost literal.
54    #[must_use]
55    pub fn outer(&self) -> LiteralIndex {
56        self.0[0]
57    }
58}
59
60impl fmt::Display for LiteralPath {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        write!(f, "body literal {}", self.0[0].get())?;
63        for step in &self.0[1..] {
64            write!(f, " > inner literal {}", step.get())?;
65        }
66        Ok(())
67    }
68}