use crate::{EvaluationError, Key, Map, Value, boundary};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Context {
bindings: Map,
}
impl Context {
pub fn new() -> Context {
Context::default()
}
pub fn insert(&mut self, name: impl Into<Key>, value: Value) -> Option<Value> {
self.bindings.insert(name, value)
}
pub fn get(&self, key: &Key) -> Option<&Value> {
self.bindings.get(key)
}
pub(crate) fn bindings_mut(&mut self) -> &mut Map {
&mut self.bindings
}
pub(crate) fn bindings(&self) -> &Map {
&self.bindings
}
pub(crate) fn root(&self, name: &str) -> Option<&Value> {
self.bindings.get_str(name)
}
pub(crate) fn check(&self) -> Result<(), EvaluationError> {
self.bindings.values().try_for_each(boundary::check)
}
}
impl From<Map> for Context {
fn from(bindings: Map) -> Context {
Context { bindings }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_context_binds_roots_by_name_and_tells_unbound_from_undefined() {
let mut context = Context::new();
assert_eq!(context.insert("x", Value::from(1)), None);
assert_eq!(context.insert("x", Value::from(2)), Some(Value::from(1)));
context.insert("u", Value::Undefined);
assert_eq!(context.root("x"), Some(&Value::from(2)));
assert_eq!(context.root("u"), Some(&Value::Undefined));
assert_eq!(context.root("y"), None);
assert!(context.check().is_ok());
}
#[test]
fn a_bound_value_outside_the_domain_is_refused() {
let mut context = Context::new();
context.insert("ok", Value::from(1));
context.insert("x", Value::List(vec![Value::Float(f64::NAN)]));
assert_eq!(
context.check().map_err(|error| error.reason().to_owned()),
Err("non_finite_number".to_owned())
);
}
}