predicator_rs/context.rs
1//! The context an evaluation reads its variables from.
2
3use crate::{EvaluationError, Key, Map, Value, boundary};
4
5/// The variables an evaluation reads: each root name bound to a value. A
6/// `load` reads a root by its string name; a name the context does not bind
7/// is unbound, which is not the same as a name bound to
8/// [`Value::Undefined`].
9///
10/// Every bound value is checked against the value domain when an
11/// evaluation starts: a float that is not finite (`non_finite_number`) and
12/// lists and maps nested past 100 levels (`depth_limit_exceeded`) are
13/// refused with an [`EvaluationError`].
14///
15/// ```
16/// use predicator_rs::{Context, Map, Value};
17///
18/// let mut context = Context::new();
19/// context.insert("score", Value::from(90));
20/// let bindings: Map = [("score", Value::from(90))].into_iter().collect();
21/// assert_eq!(context, Context::from(bindings));
22/// ```
23#[derive(Debug, Clone, Default, PartialEq)]
24pub struct Context {
25 bindings: Map,
26}
27
28impl Context {
29 /// An empty context.
30 ///
31 /// ```
32 /// use predicator_rs::{Context, Key};
33 ///
34 /// assert_eq!(Context::new().get(&Key::from("x")), None);
35 /// ```
36 pub fn new() -> Context {
37 Context::default()
38 }
39
40 /// Binds `name` to `value`, answering the value it replaces.
41 ///
42 /// ```
43 /// use predicator_rs::{Context, Value};
44 ///
45 /// let mut context = Context::new();
46 /// assert_eq!(context.insert("x", Value::from(1)), None);
47 /// assert_eq!(context.insert("x", Value::from(2)), Some(Value::from(1)));
48 /// ```
49 pub fn insert(&mut self, name: impl Into<Key>, value: Value) -> Option<Value> {
50 self.bindings.insert(name, value)
51 }
52
53 /// The value bound to `key`, if the context binds it: how a caller reads
54 /// the context a statement program leaves ([`execute`](crate::execute)).
55 ///
56 /// ```
57 /// use predicator_rs::{Context, Key, Value};
58 ///
59 /// let mut context = Context::new();
60 /// context.insert("score", Value::from(90));
61 /// assert_eq!(context.get(&Key::from("score")), Some(&Value::from(90)));
62 /// assert_eq!(context.get(&Key::from("other")), None);
63 /// ```
64 pub fn get(&self, key: &Key) -> Option<&Value> {
65 self.bindings.get(key)
66 }
67
68 /// The bindings, for a `store` to write.
69 pub(crate) fn bindings_mut(&mut self) -> &mut Map {
70 &mut self.bindings
71 }
72
73 /// The bindings, for a `store` to check its path against.
74 pub(crate) fn bindings(&self) -> &Map {
75 &self.bindings
76 }
77
78 /// The value bound to the root `name`, if the context binds it.
79 pub(crate) fn root(&self, name: &str) -> Option<&Value> {
80 self.bindings.get_str(name)
81 }
82
83 /// The first bound value outside the value domain, refused.
84 pub(crate) fn check(&self) -> Result<(), EvaluationError> {
85 self.bindings.values().try_for_each(boundary::check)
86 }
87}
88
89impl From<Map> for Context {
90 /// The context binding each key of `bindings` to its value.
91 fn from(bindings: Map) -> Context {
92 Context { bindings }
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 // Sabotage: with root looking the name up as Key::Integer(0), this test
101 // fails.
102 #[test]
103 fn a_context_binds_roots_by_name_and_tells_unbound_from_undefined() {
104 let mut context = Context::new();
105 assert_eq!(context.insert("x", Value::from(1)), None);
106 assert_eq!(context.insert("x", Value::from(2)), Some(Value::from(1)));
107 context.insert("u", Value::Undefined);
108 assert_eq!(context.root("x"), Some(&Value::from(2)));
109 assert_eq!(context.root("u"), Some(&Value::Undefined));
110 assert_eq!(context.root("y"), None);
111 assert!(context.check().is_ok());
112 }
113
114 // Sabotage: with check answering Ok(()) without a walk, this test fails.
115 #[test]
116 fn a_bound_value_outside_the_domain_is_refused() {
117 let mut context = Context::new();
118 context.insert("ok", Value::from(1));
119 context.insert("x", Value::List(vec![Value::Float(f64::NAN)]));
120 assert_eq!(
121 context.check().map_err(|error| error.reason().to_owned()),
122 Err("non_finite_number".to_owned())
123 );
124 }
125}