Implemented configuration

This commit is contained in:
Sebastian Schmidt 2019-03-15 19:28:59 +02:00
parent 406bfe0e05
commit b1abbd6cfd
4 changed files with 19 additions and 6 deletions

View File

@ -1,13 +1,22 @@
use crate::{error::Error, value::Value};
use std::collections::HashMap;
pub trait Configuration {
fn get_value(&self, identifier: &str) -> Result<Value, Error>;
fn get_value(&self, identifier: &str) -> Option<&Value>;
}
pub struct EmptyConfiguration;
impl Configuration for EmptyConfiguration {
fn get_value(&self, _identifier: &str) -> Result<Value, Error> {
Err(Error::IdentifierNotFound)
fn get_value(&self, identifier: &str) -> Option<&Value> {
None
}
}
pub type HashMapConfiguration = HashMap<String, Value>;
impl Configuration for HashMapConfiguration {
fn get_value(&self, identifier: &str) -> Option<&Value> {
self.get(identifier)
}
}

View File

@ -29,7 +29,7 @@ pub enum Error {
PrecedenceViolation,
/// An identifier operation did not find its value in the configuration.
IdentifierNotFound,
IdentifierNotFound(String),
/// A value has the wrong type.
TypeError,

View File

@ -24,7 +24,7 @@ mod test {
assert_eq!(eval("3.3"), Ok(Value::Float(3.3)));
assert_eq!(eval("true"), Ok(Value::Boolean(true)));
assert_eq!(eval("false"), Ok(Value::Boolean(false)));
assert_eq!(eval("blub"), Err(Error::IdentifierNotFound));
assert_eq!(eval("blub"), Err(Error::IdentifierNotFound("blub".to_string())));
assert_eq!(eval("-3"), Ok(Value::Int(-3)));
assert_eq!(eval("-3.6"), Ok(Value::Float(-3.6)));
assert_eq!(eval("----3"), Ok(Value::Int(3)));

View File

@ -479,6 +479,10 @@ impl Operator for Identifier {
fn eval(&self, arguments: &[Value], configuration: &Configuration) -> Result<Value, Error> {
expect_argument_amount(arguments.len(), 0)?;
configuration.get_value(&self.identifier)
if let Some(value) = configuration.get_value(&self.identifier).cloned() {
Ok(value)
} else {
Err(Error::IdentifierNotFound(self.identifier.clone()))
}
}
}