Skip to main content

bast3st_eval/spec/runtime/
criterion.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{
4    catchable::cerr,
5    spec::{
6        MachineConstruction, Numeric, PrimitiveValue, RuntimeAction, SpecialCritVariant, Text,
7        ValueReference,
8        machine::Machine,
9        runtime::{MaybeEval, RuntimeValue},
10    },
11};
12
13#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
14pub struct RuntimeCriterion {
15    fulfilled: Result<(), Option<Text>>,
16    inner: InnerRuntimeCriterion,
17}
18
19impl InnerRuntimeCriterion {
20    pub fn build(self, is_fulfilled: bool, failure_explaination: Option<Text>) -> RuntimeCriterion {
21        RuntimeCriterion::new(is_fulfilled, failure_explaination, self)
22    }
23    pub fn build_fulfilled(self) -> RuntimeCriterion {
24        RuntimeCriterion::new_fulfilled(self)
25    }
26    pub fn build_unfulfilled(self, failure_explaination: Option<Text>) -> RuntimeCriterion {
27        RuntimeCriterion::new_unfulfilled(failure_explaination, self)
28    }
29}
30impl RuntimeCriterion {
31    pub fn new(
32        is_fulfilled: bool,
33        failure_explaination: Option<Text>,
34        inner: InnerRuntimeCriterion,
35    ) -> Self {
36        if is_fulfilled {
37            Self::new_fulfilled(inner)
38        } else {
39            Self::new_unfulfilled(failure_explaination, inner)
40        }
41    }
42    pub fn new_fulfilled(inner: InnerRuntimeCriterion) -> Self {
43        Self {
44            inner,
45            fulfilled: Ok(()),
46        }
47    }
48    pub fn new_unfulfilled(
49        failure_explaination: Option<Text>,
50        inner: InnerRuntimeCriterion,
51    ) -> Self {
52        Self {
53            inner,
54            fulfilled: Err(failure_explaination),
55        }
56    }
57    pub fn is_fulfilled(&self) -> bool {
58        self.fulfilled.is_ok()
59    }
60    pub fn is_not_fulfilled(&self) -> bool {
61        self.fulfilled.is_err()
62    }
63    pub fn failure_explaination(&self) -> Option<&Text> {
64        self.fulfilled.as_ref().err().and_then(|x| x.as_ref())
65    }
66    pub fn set_failure_explaination_if_failed(
67        mut self,
68        mut failure_explaination: Option<ValueReference>,
69        overwrite_existing: bool,
70    ) -> Machine<RuntimeCriterion> {
71        if !overwrite_existing || self.is_fulfilled() {
72            failure_explaination = None;
73        }
74        failure_explaination.query(|failure_explaination| {
75            if self.is_not_fulfilled() {
76                self.fulfilled = Err(failure_explaination);
77            }
78            self.into()
79        })
80    }
81}
82
83#[derive(Debug, PartialEq, Clone, PartialOrd, Serialize, Deserialize)]
84#[serde(tag = "t", rename_all = "kebab-case")]
85pub enum InnerRuntimeCriterion {
86    Negated {
87        clause: Box<RuntimeCriterion>,
88    },
89    AnyOf {
90        clauses: Vec<MaybeEval<RuntimeCriterion>>,
91    },
92    AllOf {
93        clauses: Vec<MaybeEval<RuntimeCriterion>>,
94    },
95    ContainOnlynum {
96        sub: PrimitiveValue,
97        sup: Text,
98        found: Vec<Numeric>,
99    },
100    ContainNum {
101        sub: Numeric,
102        sup: Text,
103        found: Vec<Numeric>,
104    },
105    ContainText {
106        sub: PrimitiveValue,
107        sup: Text,
108    },
109
110    ContainWithGaps {
111        parts: Vec<PrimitiveValue>,
112        unevaluated_parts: usize,
113        sup: Text,
114    },
115    MatchesRegex {
116        pattern: Text,
117        sup: RuntimeValue,
118    },
119
120    GreaterThen {
121        left: PrimitiveValue,
122        right: PrimitiveValue,
123    },
124    LowerThen {
125        left: PrimitiveValue,
126        right: PrimitiveValue,
127    },
128    GreaterEqual {
129        left: PrimitiveValue,
130        right: PrimitiveValue,
131    },
132    LowerEqual {
133        left: PrimitiveValue,
134        right: PrimitiveValue,
135    },
136    NotEqual {
137        left: PrimitiveValue,
138        right: PrimitiveValue,
139    },
140    Equal {
141        left: PrimitiveValue,
142        right: PrimitiveValue,
143    },
144    Catch {
145        criterion: Box<RuntimeCriterion>,
146        error: cerr,
147        only_if: Option<Box<MaybeEval<RuntimeCriterion>>>,
148        default_value: Option<Box<MaybeEval<RuntimeCriterion>>>,
149        action: Option<MaybeEval<RuntimeAction>>,
150    },
151    IfThenElse {
152        if_: Box<RuntimeCriterion>,
153        selected_branch: Box<RuntimeCriterion>,
154        other_branch: Box<MaybeEval<RuntimeCriterion>>,
155    },
156    SpecialCrit {
157        variant: SpecialCritVariant,
158    },
159}
160
161#[cfg(test)]
162mod tests {
163    use crate::spec::RuntimeCriterion;
164
165    #[test]
166    fn test_serde_runtime_criterion() {
167        let val_ok = RuntimeCriterion {
168            fulfilled: Ok(()),
169            inner: super::InnerRuntimeCriterion::Equal {
170                left: "x".into(),
171                right: "x".into(),
172            },
173        };
174        let val_err = RuntimeCriterion {
175            fulfilled: Err(Some("test".into())),
176            inner: super::InnerRuntimeCriterion::Equal {
177                left: "x".into(),
178                right: "y".into(),
179            },
180        };
181        let val_ok_ser = serde_json::to_string(&val_ok).unwrap();
182        let val_err_ser = serde_json::to_string(&val_err).unwrap();
183        assert_eq!(
184            r#"{"fulfilled":{"Ok":null},"inner":{"t":"equal","left":"x","right":"x"}}"#,
185            val_ok_ser
186        );
187        assert_eq!(
188            r#"{"fulfilled":{"Err":"test"},"inner":{"t":"equal","left":"x","right":"y"}}"#,
189            val_err_ser
190        );
191    }
192}