Skip to main content

lemma/evaluation/
operations.rs

1//! Operation types and result handling for evaluation
2
3use std::fmt;
4use std::sync::Arc;
5
6use crate::planning::semantics::{
7    DataPath, LemmaType, LiteralValue, SemanticDateTime, SemanticTime, TypeSpecification,
8};
9use serde::Serialize;
10
11/// Why an operation yielded no value (domain veto).
12///
13/// JSON serialization is a single string (see [`fmt::Display`]). There is intentionally no
14/// `Deserialize` implementation: veto payloads are engine output only.
15#[derive(Debug, Clone, PartialEq)]
16pub enum VetoType {
17    /// Evaluation needed a data that was not provided
18    MissingData {
19        data: DataPath,
20        suggestion: Option<String>,
21    },
22    /// Explicit `veto "reason"` in Lemma source
23    UserDefined { message: Option<String> },
24    /// Runtime domain failure (division by zero, date overflow, bad Data override, etc.)
25    Computation { message: String },
26}
27
28impl fmt::Display for VetoType {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self {
31            VetoType::MissingData {
32                data,
33                suggestion: Some(suggestion),
34            } => write!(f, "Missing data: {data} (did you mean '{suggestion}'?)"),
35            VetoType::MissingData {
36                data,
37                suggestion: None,
38            } => write!(f, "Missing data: {data}"),
39            VetoType::UserDefined { message: Some(msg) } => write!(f, "{msg}"),
40            VetoType::UserDefined { message: None } => write!(f, "Vetoed"),
41            VetoType::Computation { message } => write!(f, "{message}"),
42        }
43    }
44}
45
46impl VetoType {
47    #[must_use]
48    pub fn computation(message: impl Into<String>) -> Self {
49        VetoType::Computation {
50            message: message.into(),
51        }
52    }
53
54    #[must_use]
55    pub fn missing_data(data: DataPath, suggestion: Option<String>) -> Self {
56        VetoType::MissingData { data, suggestion }
57    }
58}
59
60impl Serialize for VetoType {
61    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
62    where
63        S: serde::Serializer,
64    {
65        serializer.serialize_str(&self.to_string())
66    }
67}
68
69/// Result of an operation (evaluating a rule or expression)
70/// TODO: Rename. This can also represent a data value.
71#[derive(Debug, Clone, PartialEq, Serialize)]
72#[serde(rename_all = "snake_case")]
73pub enum OperationResult {
74    /// Operation produced a value
75    Value(Arc<LiteralValue>),
76    /// Operation was vetoed (valid result, no value)
77    Veto(VetoType),
78}
79
80impl OperationResult {
81    pub fn from_literal(value: LiteralValue) -> Self {
82        Self::Value(Arc::new(value))
83    }
84
85    pub fn from_literal_arc(value: Arc<LiteralValue>) -> Self {
86        Self::Value(value)
87    }
88
89    pub fn vetoed(&self) -> bool {
90        matches!(self, OperationResult::Veto(_))
91    }
92
93    #[must_use]
94    pub fn value(&self) -> Option<&LiteralValue> {
95        match self {
96            OperationResult::Value(value) => Some(value.as_ref()),
97            OperationResult::Veto(_) => None,
98        }
99    }
100
101    #[must_use]
102    pub fn value_arc(&self) -> Option<&Arc<LiteralValue>> {
103        match self {
104            OperationResult::Value(value) => Some(value),
105            OperationResult::Veto(_) => None,
106        }
107    }
108
109    pub fn number(number: rust_decimal::Decimal) -> Self {
110        Self::from_literal(LiteralValue::number_from_decimal(number))
111    }
112
113    pub fn measure(
114        value: rust_decimal::Decimal,
115        unit: impl Into<String>,
116        lemma_type: Option<LemmaType>,
117    ) -> Self {
118        use crate::computation::rational::checked_mul;
119        let lemma_type = std::sync::Arc::new(
120            lemma_type.unwrap_or_else(|| LemmaType::primitive(TypeSpecification::measure())),
121        );
122        let unit_name = unit.into();
123        let rational = crate::literals::rational_from_parsed_decimal(value)
124            .expect("BUG: operation result measure must lift at boundary");
125        let factor = if let TypeSpecification::Measure { units, .. } = &lemma_type.specifications {
126            units
127                .get(&unit_name)
128                .map(|u| u.factor.clone())
129                .unwrap_or_else(|_| {
130                    panic!(
131                        "BUG: OperationResult::measure unit '{}' not declared on type",
132                        unit_name
133                    )
134                })
135        } else {
136            crate::computation::rational::rational_one()
137        };
138        let canonical = checked_mul(&rational, &factor)
139            .expect("BUG: measure canonicalization overflow in OperationResult::measure");
140        Self::from_literal(LiteralValue::measure_with_type(
141            canonical, unit_name, lemma_type,
142        ))
143    }
144
145    pub fn text(text: impl Into<String>) -> Self {
146        Self::from_literal(LiteralValue::text(text.into()))
147    }
148
149    pub fn date(date: impl Into<SemanticDateTime>) -> Self {
150        Self::from_literal(LiteralValue::date(date.into()))
151    }
152
153    pub fn time(time: impl Into<SemanticTime>) -> Self {
154        Self::from_literal(LiteralValue::time(time.into()))
155    }
156
157    pub fn boolean(boolean: bool) -> Self {
158        Self::from_literal(LiteralValue::from_bool(boolean))
159    }
160
161    pub fn ratio(rational: rust_decimal::Decimal) -> Self {
162        Self::from_literal(LiteralValue::ratio_from_decimal(rational, None))
163    }
164
165    pub fn veto(veto: impl Into<String>) -> Self {
166        Self::Veto(VetoType::UserDefined {
167            message: Some(veto.into()),
168        })
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::VetoType;
175    use crate::planning::semantics::DataPath;
176
177    #[test]
178    fn veto_type_serializes_as_display_string() {
179        let v = VetoType::missing_data(DataPath::new(vec![], "product".to_string()), None);
180        let json = serde_json::to_string(&v).expect("serialize");
181        assert_eq!(json, "\"Missing data: product\"");
182    }
183}