Rename Error to EvalexprError and add EvalexprResult

Relates to #27
This commit is contained in:
Sebastian Schmidt 2019-03-27 16:33:46 +01:00
parent d64aacea17
commit fd879193b6
11 changed files with 158 additions and 153 deletions

View File

@ -1,9 +1,10 @@
use std::fmt; use std::fmt;
use Error;
impl fmt::Display for Error { use EvalexprError;
impl fmt::Display for EvalexprError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use Error::*; use EvalexprError::*;
match self { match self {
WrongOperatorArgumentAmount { expected, actual } => write!( WrongOperatorArgumentAmount { expected, actual } => write!(
f, f,

View File

@ -5,15 +5,16 @@
//! The module also contains some helper functions starting with `expect_` that check for a condition and return `Err(_)` if the condition is not fulfilled. //! The module also contains some helper functions starting with `expect_` that check for a condition and return `Err(_)` if the condition is not fulfilled.
//! They are meant as shortcuts to not write the same error checking code everywhere. //! They are meant as shortcuts to not write the same error checking code everywhere.
use crate::value::Value;
use token::PartialToken; use token::PartialToken;
use value::TupleType; use value::TupleType;
use crate::value::Value;
mod display; mod display;
/// Errors used in this crate. /// Errors used in this crate.
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum Error { pub enum EvalexprError {
/// An operator was called with a wrong amount of arguments. /// An operator was called with a wrong amount of arguments.
WrongOperatorArgumentAmount { WrongOperatorArgumentAmount {
/// The expected amount of arguments. /// The expected amount of arguments.
@ -158,122 +159,124 @@ pub enum Error {
CustomMessage(String), CustomMessage(String),
} }
impl Error { impl EvalexprError {
pub(crate) fn wrong_operator_argument_amount(actual: usize, expected: usize) -> Self { pub(crate) fn wrong_operator_argument_amount(actual: usize, expected: usize) -> Self {
Error::WrongOperatorArgumentAmount { actual, expected } EvalexprError::WrongOperatorArgumentAmount { actual, expected }
} }
pub(crate) fn wrong_function_argument_amount(actual: usize, expected: usize) -> Self { pub(crate) fn wrong_function_argument_amount(actual: usize, expected: usize) -> Self {
Error::WrongFunctionArgumentAmount { actual, expected } EvalexprError::WrongFunctionArgumentAmount { actual, expected }
} }
/// Constructs `Error::TypeError{actual, expected}`. /// Constructs `Error::TypeError{actual, expected}`.
pub fn type_error(actual: Value, expected: TupleType) -> Self { pub fn type_error(actual: Value, expected: TupleType) -> Self {
Error::TypeError { actual, expected } EvalexprError::TypeError { actual, expected }
} }
/// Constructs `Error::ExpectedString(actual)`. /// Constructs `Error::ExpectedString(actual)`.
pub fn expected_string(actual: Value) -> Self { pub fn expected_string(actual: Value) -> Self {
Error::ExpectedString { actual } EvalexprError::ExpectedString { actual }
} }
/// Constructs `Error::ExpectedInt(actual)`. /// Constructs `Error::ExpectedInt(actual)`.
pub fn expected_int(actual: Value) -> Self { pub fn expected_int(actual: Value) -> Self {
Error::ExpectedInt { actual } EvalexprError::ExpectedInt { actual }
} }
/// Constructs `Error::ExpectedFloat(actual)`. /// Constructs `Error::ExpectedFloat(actual)`.
pub fn expected_float(actual: Value) -> Self { pub fn expected_float(actual: Value) -> Self {
Error::ExpectedFloat { actual } EvalexprError::ExpectedFloat { actual }
} }
/// Constructs `Error::ExpectedNumber(actual)`. /// Constructs `Error::ExpectedNumber(actual)`.
pub fn expected_number(actual: Value) -> Self { pub fn expected_number(actual: Value) -> Self {
Error::ExpectedNumber { actual } EvalexprError::ExpectedNumber { actual }
} }
/// Constructs `Error::ExpectedBoolean(actual)`. /// Constructs `Error::ExpectedBoolean(actual)`.
pub fn expected_boolean(actual: Value) -> Self { pub fn expected_boolean(actual: Value) -> Self {
Error::ExpectedBoolean { actual } EvalexprError::ExpectedBoolean { actual }
} }
/// Constructs `Error::ExpectedTuple(actual)`. /// Constructs `Error::ExpectedTuple(actual)`.
pub fn expected_tuple(actual: Value) -> Self { pub fn expected_tuple(actual: Value) -> Self {
Error::ExpectedTuple { actual } EvalexprError::ExpectedTuple { actual }
} }
pub(crate) fn unmatched_partial_token( pub(crate) fn unmatched_partial_token(
first: PartialToken, first: PartialToken,
second: Option<PartialToken>, second: Option<PartialToken>,
) -> Self { ) -> Self {
Error::UnmatchedPartialToken { first, second } EvalexprError::UnmatchedPartialToken { first, second }
} }
pub(crate) fn addition_error(augend: Value, addend: Value) -> Self { pub(crate) fn addition_error(augend: Value, addend: Value) -> Self {
Error::AdditionError { augend, addend } EvalexprError::AdditionError { augend, addend }
} }
pub(crate) fn subtraction_error(minuend: Value, subtrahend: Value) -> Self { pub(crate) fn subtraction_error(minuend: Value, subtrahend: Value) -> Self {
Error::SubtractionError { EvalexprError::SubtractionError {
minuend, minuend,
subtrahend, subtrahend,
} }
} }
pub(crate) fn negation_error(argument: Value) -> Self { pub(crate) fn negation_error(argument: Value) -> Self {
Error::NegationError { argument } EvalexprError::NegationError { argument }
} }
pub(crate) fn multiplication_error(multiplicand: Value, multiplier: Value) -> Self { pub(crate) fn multiplication_error(multiplicand: Value, multiplier: Value) -> Self {
Error::MultiplicationError { EvalexprError::MultiplicationError {
multiplicand, multiplicand,
multiplier, multiplier,
} }
} }
pub(crate) fn division_error(dividend: Value, divisor: Value) -> Self { pub(crate) fn division_error(dividend: Value, divisor: Value) -> Self {
Error::DivisionError { dividend, divisor } EvalexprError::DivisionError { dividend, divisor }
} }
pub(crate) fn modulation_error(dividend: Value, divisor: Value) -> Self { pub(crate) fn modulation_error(dividend: Value, divisor: Value) -> Self {
Error::ModulationError { dividend, divisor } EvalexprError::ModulationError { dividend, divisor }
} }
} }
/// Returns `Ok(())` if the actual and expected parameters are equal, and `Err(Error::WrongOperatorArgumentAmount)` otherwise. /// Returns `Ok(())` if the actual and expected parameters are equal, and `Err(Error::WrongOperatorArgumentAmount)` otherwise.
pub(crate) fn expect_operator_argument_amount(actual: usize, expected: usize) -> Result<(), Error> { pub(crate) fn expect_operator_argument_amount(actual: usize, expected: usize) -> Result<(), EvalexprError> {
if actual == expected { if actual == expected {
Ok(()) Ok(())
} else { } else {
Err(Error::wrong_operator_argument_amount(actual, expected)) Err(EvalexprError::wrong_operator_argument_amount(actual, expected))
} }
} }
/// Returns `Ok(())` if the actual and expected parameters are equal, and `Err(Error::WrongFunctionArgumentAmount)` otherwise. /// Returns `Ok(())` if the actual and expected parameters are equal, and `Err(Error::WrongFunctionArgumentAmount)` otherwise.
pub(crate) fn expect_function_argument_amount(actual: usize, expected: usize) -> Result<(), Error> { pub(crate) fn expect_function_argument_amount(actual: usize, expected: usize) -> Result<(), EvalexprError> {
if actual == expected { if actual == expected {
Ok(()) Ok(())
} else { } else {
Err(Error::wrong_function_argument_amount(actual, expected)) Err(EvalexprError::wrong_function_argument_amount(actual, expected))
} }
} }
/// Returns `Ok(())` if the given value is numeric. /// Returns `Ok(())` if the given value is numeric.
/// Numeric types are `Value::Int` and `Value::Float`. /// Numeric types are `Value::Int` and `Value::Float`.
/// Otherwise, `Err(Error::ExpectedNumber)` is returned. /// Otherwise, `Err(Error::ExpectedNumber)` is returned.
pub fn expect_number(actual: &Value) -> Result<(), Error> { pub fn expect_number(actual: &Value) -> Result<(), EvalexprError> {
match actual { match actual {
Value::Float(_) | Value::Int(_) => Ok(()), Value::Float(_) | Value::Int(_) => Ok(()),
_ => Err(Error::expected_number(actual.clone())), _ => Err(EvalexprError::expected_number(actual.clone())),
} }
} }
/// Returns `Ok(())` if the given value is a `Value::Boolean`, or `Err(Error::ExpectedBoolean)` otherwise. /// Returns `Ok(())` if the given value is a `Value::Boolean`, or `Err(Error::ExpectedBoolean)` otherwise.
pub fn expect_boolean(actual: &Value) -> Result<bool, Error> { pub fn expect_boolean(actual: &Value) -> Result<bool, EvalexprError> {
match actual { match actual {
Value::Boolean(boolean) => Ok(*boolean), Value::Boolean(boolean) => Ok(*boolean),
_ => Err(Error::expected_boolean(actual.clone())), _ => Err(EvalexprError::expected_boolean(actual.clone())),
} }
} }
impl std::error::Error for Error {} impl std::error::Error for EvalexprError {}
pub type EvalexprResult<T> = Result<T, EvalexprError>;

View File

@ -1,6 +1,6 @@
use value::{FloatType, IntType}; use EvalexprError;
use Error;
use Function; use Function;
use value::{FloatType, IntType};
use Value; use Value;
pub fn builtin_function(identifier: &str) -> Option<Function> { pub fn builtin_function(identifier: &str) -> Option<Function> {
@ -18,7 +18,7 @@ pub fn builtin_function(identifier: &str) -> Option<Function> {
} else if let Value::Int(int) = argument { } else if let Value::Int(int) = argument {
min_int = min_int.min(*int); min_int = min_int.min(*int);
} else { } else {
return Err(Error::expected_number(argument.clone())); return Err(EvalexprError::expected_number(argument.clone()));
} }
} }
@ -42,7 +42,7 @@ pub fn builtin_function(identifier: &str) -> Option<Function> {
} else if let Value::Int(int) = argument { } else if let Value::Int(int) = argument {
max_int = max_int.max(*int); max_int = max_int.max(*int);
} else { } else {
return Err(Error::expected_number(argument.clone())); return Err(EvalexprError::expected_number(argument.clone()));
} }
} }

View File

@ -1,4 +1,4 @@
use error::{self, Error}; use error::{self, EvalexprError};
use value::Value; use value::Value;
pub(crate) mod builtin; pub(crate) mod builtin;
@ -19,7 +19,7 @@ pub(crate) mod builtin;
/// ``` /// ```
pub struct Function { pub struct Function {
argument_amount: Option<usize>, argument_amount: Option<usize>,
function: Box<Fn(&[Value]) -> Result<Value, Error>>, function: Box<Fn(&[Value]) -> Result<Value, EvalexprError>>,
} }
impl Function { impl Function {
@ -31,7 +31,7 @@ impl Function {
/// The `function` is a boxed function that takes a slice of values and returns a `Result<Value, Error>`. /// The `function` is a boxed function that takes a slice of values and returns a `Result<Value, Error>`.
pub fn new( pub fn new(
argument_amount: Option<usize>, argument_amount: Option<usize>,
function: Box<Fn(&[Value]) -> Result<Value, Error>>, function: Box<Fn(&[Value]) -> Result<Value, EvalexprError>>,
) -> Self { ) -> Self {
Self { Self {
argument_amount, argument_amount,
@ -39,7 +39,7 @@ impl Function {
} }
} }
pub(crate) fn call(&self, arguments: &[Value]) -> Result<Value, Error> { pub(crate) fn call(&self, arguments: &[Value]) -> Result<Value, EvalexprError> {
if let Some(argument_amount) = self.argument_amount { if let Some(argument_amount) = self.argument_amount {
error::expect_function_argument_amount(arguments.len(), argument_amount)?; error::expect_function_argument_amount(arguments.len(), argument_amount)?;
} }

View File

@ -1,6 +1,6 @@
use Configuration; use Configuration;
use EmptyConfiguration; use EmptyConfiguration;
use Error; use EvalexprError;
use FloatType; use FloatType;
use IntType; use IntType;
use Node; use Node;
@ -20,7 +20,7 @@ use value::TupleType;
/// ``` /// ```
/// ///
/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* /// *See the [crate doc](index.html) for more examples and explanations of the expression format.*
pub fn eval(string: &str) -> Result<Value, Error> { pub fn eval(string: &str) -> Result<Value, EvalexprError> {
eval_with_configuration(string, &EmptyConfiguration) eval_with_configuration(string, &EmptyConfiguration)
} }
@ -42,7 +42,7 @@ pub fn eval(string: &str) -> Result<Value, Error> {
pub fn eval_with_configuration( pub fn eval_with_configuration(
string: &str, string: &str,
configuration: &Configuration, configuration: &Configuration,
) -> Result<Value, Error> { ) -> Result<Value, EvalexprError> {
tree::tokens_to_operator_tree(token::tokenize(string)?)?.eval_with_configuration(configuration) tree::tokens_to_operator_tree(token::tokenize(string)?)?.eval_with_configuration(configuration)
} }
@ -70,17 +70,17 @@ pub fn eval_with_configuration(
/// ``` /// ```
/// ///
/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* /// *See the [crate doc](index.html) for more examples and explanations of the expression format.*
pub fn build_operator_tree(string: &str) -> Result<Node, Error> { pub fn build_operator_tree(string: &str) -> Result<Node, EvalexprError> {
tree::tokens_to_operator_tree(token::tokenize(string)?) tree::tokens_to_operator_tree(token::tokenize(string)?)
} }
/// Evaluate the given expression string into a string. /// Evaluate the given expression string into a string.
/// ///
/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* /// *See the [crate doc](index.html) for more examples and explanations of the expression format.*
pub fn eval_string(string: &str) -> Result<String, Error> { pub fn eval_string(string: &str) -> Result<String, EvalexprError> {
match eval(string) { match eval(string) {
Ok(Value::String(string)) => Ok(string), Ok(Value::String(string)) => Ok(string),
Ok(value) => Err(Error::expected_string(value)), Ok(value) => Err(EvalexprError::expected_string(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -88,10 +88,10 @@ pub fn eval_string(string: &str) -> Result<String, Error> {
/// Evaluate the given expression string into an integer. /// Evaluate the given expression string into an integer.
/// ///
/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* /// *See the [crate doc](index.html) for more examples and explanations of the expression format.*
pub fn eval_int(string: &str) -> Result<IntType, Error> { pub fn eval_int(string: &str) -> Result<IntType, EvalexprError> {
match eval(string) { match eval(string) {
Ok(Value::Int(int)) => Ok(int), Ok(Value::Int(int)) => Ok(int),
Ok(value) => Err(Error::expected_int(value)), Ok(value) => Err(EvalexprError::expected_int(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -99,10 +99,10 @@ pub fn eval_int(string: &str) -> Result<IntType, Error> {
/// Evaluate the given expression string into a float. /// Evaluate the given expression string into a float.
/// ///
/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* /// *See the [crate doc](index.html) for more examples and explanations of the expression format.*
pub fn eval_float(string: &str) -> Result<FloatType, Error> { pub fn eval_float(string: &str) -> Result<FloatType, EvalexprError> {
match eval(string) { match eval(string) {
Ok(Value::Float(float)) => Ok(float), Ok(Value::Float(float)) => Ok(float),
Ok(value) => Err(Error::expected_float(value)), Ok(value) => Err(EvalexprError::expected_float(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -110,10 +110,10 @@ pub fn eval_float(string: &str) -> Result<FloatType, Error> {
/// Evaluate the given expression string into a boolean. /// Evaluate the given expression string into a boolean.
/// ///
/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* /// *See the [crate doc](index.html) for more examples and explanations of the expression format.*
pub fn eval_boolean(string: &str) -> Result<bool, Error> { pub fn eval_boolean(string: &str) -> Result<bool, EvalexprError> {
match eval(string) { match eval(string) {
Ok(Value::Boolean(boolean)) => Ok(boolean), Ok(Value::Boolean(boolean)) => Ok(boolean),
Ok(value) => Err(Error::expected_boolean(value)), Ok(value) => Err(EvalexprError::expected_boolean(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -121,10 +121,10 @@ pub fn eval_boolean(string: &str) -> Result<bool, Error> {
/// Evaluate the given expression string into a tuple. /// Evaluate the given expression string into a tuple.
/// ///
/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* /// *See the [crate doc](index.html) for more examples and explanations of the expression format.*
pub fn eval_tuple(string: &str) -> Result<TupleType, Error> { pub fn eval_tuple(string: &str) -> Result<TupleType, EvalexprError> {
match eval(string) { match eval(string) {
Ok(Value::Tuple(tuple)) => Ok(tuple), Ok(Value::Tuple(tuple)) => Ok(tuple),
Ok(value) => Err(Error::expected_tuple(value)), Ok(value) => Err(EvalexprError::expected_tuple(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -135,10 +135,10 @@ pub fn eval_tuple(string: &str) -> Result<TupleType, Error> {
pub fn eval_string_with_configuration( pub fn eval_string_with_configuration(
string: &str, string: &str,
configuration: &Configuration, configuration: &Configuration,
) -> Result<String, Error> { ) -> Result<String, EvalexprError> {
match eval_with_configuration(string, configuration) { match eval_with_configuration(string, configuration) {
Ok(Value::String(string)) => Ok(string), Ok(Value::String(string)) => Ok(string),
Ok(value) => Err(Error::expected_string(value)), Ok(value) => Err(EvalexprError::expected_string(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -149,10 +149,10 @@ pub fn eval_string_with_configuration(
pub fn eval_int_with_configuration( pub fn eval_int_with_configuration(
string: &str, string: &str,
configuration: &Configuration, configuration: &Configuration,
) -> Result<IntType, Error> { ) -> Result<IntType, EvalexprError> {
match eval_with_configuration(string, configuration) { match eval_with_configuration(string, configuration) {
Ok(Value::Int(int)) => Ok(int), Ok(Value::Int(int)) => Ok(int),
Ok(value) => Err(Error::expected_int(value)), Ok(value) => Err(EvalexprError::expected_int(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -163,10 +163,10 @@ pub fn eval_int_with_configuration(
pub fn eval_float_with_configuration( pub fn eval_float_with_configuration(
string: &str, string: &str,
configuration: &Configuration, configuration: &Configuration,
) -> Result<FloatType, Error> { ) -> Result<FloatType, EvalexprError> {
match eval_with_configuration(string, configuration) { match eval_with_configuration(string, configuration) {
Ok(Value::Float(float)) => Ok(float), Ok(Value::Float(float)) => Ok(float),
Ok(value) => Err(Error::expected_float(value)), Ok(value) => Err(EvalexprError::expected_float(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -177,10 +177,10 @@ pub fn eval_float_with_configuration(
pub fn eval_boolean_with_configuration( pub fn eval_boolean_with_configuration(
string: &str, string: &str,
configuration: &Configuration, configuration: &Configuration,
) -> Result<bool, Error> { ) -> Result<bool, EvalexprError> {
match eval_with_configuration(string, configuration) { match eval_with_configuration(string, configuration) {
Ok(Value::Boolean(boolean)) => Ok(boolean), Ok(Value::Boolean(boolean)) => Ok(boolean),
Ok(value) => Err(Error::expected_boolean(value)), Ok(value) => Err(EvalexprError::expected_boolean(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -191,10 +191,10 @@ pub fn eval_boolean_with_configuration(
pub fn eval_tuple_with_configuration( pub fn eval_tuple_with_configuration(
string: &str, string: &str,
configuration: &Configuration, configuration: &Configuration,
) -> Result<TupleType, Error> { ) -> Result<TupleType, EvalexprError> {
match eval_with_configuration(string, configuration) { match eval_with_configuration(string, configuration) {
Ok(Value::Tuple(tuple)) => Ok(tuple), Ok(Value::Tuple(tuple)) => Ok(tuple),
Ok(value) => Err(Error::expected_tuple(value)), Ok(value) => Err(EvalexprError::expected_tuple(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }

View File

@ -44,7 +44,7 @@
//! } else if let Value::Float(float) = arguments[0] { //! } else if let Value::Float(float) = arguments[0] {
//! Ok(Value::Float(float / 2.0)) //! Ok(Value::Float(float / 2.0))
//! } else { //! } else {
//! Err(Error::expected_number(arguments[0].clone())) //! Err(EvalexprError::expected_number(arguments[0].clone()))
//! } //! }
//! }))); //! })));
//! configuration.insert_function("avg", Function::new(Some(2) /* argument amount */, Box::new(|arguments| { //! configuration.insert_function("avg", Function::new(Some(2) /* argument amount */, Box::new(|arguments| {
@ -270,7 +270,7 @@ extern crate ron;
extern crate serde; extern crate serde;
pub use configuration::{Configuration, EmptyConfiguration, HashMapConfiguration}; pub use configuration::{Configuration, EmptyConfiguration, HashMapConfiguration};
pub use error::Error; pub use error::{EvalexprError, EvalexprResult};
pub use function::Function; pub use function::Function;
pub use interface::*; pub use interface::*;
pub use tree::Node; pub use tree::Node;

View File

@ -29,7 +29,7 @@ pub trait Operator: Debug + Display {
fn argument_amount(&self) -> usize; fn argument_amount(&self) -> usize;
/// Evaluates the operator with the given arguments and configuration. /// Evaluates the operator with the given arguments and configuration.
fn eval(&self, arguments: &[Value], configuration: &Configuration) -> Result<Value, Error>; fn eval(&self, arguments: &[Value], configuration: &Configuration) -> Result<Value, EvalexprError>;
} }
#[derive(Debug)] #[derive(Debug)]
@ -118,7 +118,7 @@ impl Operator for RootNode {
1 1
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 1)?; expect_operator_argument_amount(arguments.len(), 1)?;
Ok(arguments[0].clone()) Ok(arguments[0].clone())
} }
@ -137,7 +137,7 @@ impl Operator for Add {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -147,7 +147,7 @@ impl Operator for Add {
if let Some(result) = result { if let Some(result) = result {
Ok(Value::Int(result)) Ok(Value::Int(result))
} else { } else {
Err(Error::addition_error( Err(EvalexprError::addition_error(
arguments[0].clone(), arguments[0].clone(),
arguments[1].clone(), arguments[1].clone(),
)) ))
@ -173,7 +173,7 @@ impl Operator for Sub {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -183,7 +183,7 @@ impl Operator for Sub {
if let Some(result) = result { if let Some(result) = result {
Ok(Value::Int(result)) Ok(Value::Int(result))
} else { } else {
Err(Error::subtraction_error( Err(EvalexprError::subtraction_error(
arguments[0].clone(), arguments[0].clone(),
arguments[1].clone(), arguments[1].clone(),
)) ))
@ -209,7 +209,7 @@ impl Operator for Neg {
1 1
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 1)?; expect_operator_argument_amount(arguments.len(), 1)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
@ -218,7 +218,7 @@ impl Operator for Neg {
if let Some(result) = result { if let Some(result) = result {
Ok(Value::Int(result)) Ok(Value::Int(result))
} else { } else {
Err(Error::negation_error(arguments[0].clone())) Err(EvalexprError::negation_error(arguments[0].clone()))
} }
} else { } else {
Ok(Value::Float(-arguments[0].as_float().unwrap())) Ok(Value::Float(-arguments[0].as_float().unwrap()))
@ -239,7 +239,7 @@ impl Operator for Mul {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -249,7 +249,7 @@ impl Operator for Mul {
if let Some(result) = result { if let Some(result) = result {
Ok(Value::Int(result)) Ok(Value::Int(result))
} else { } else {
Err(Error::multiplication_error( Err(EvalexprError::multiplication_error(
arguments[0].clone(), arguments[0].clone(),
arguments[1].clone(), arguments[1].clone(),
)) ))
@ -275,7 +275,7 @@ impl Operator for Div {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -285,7 +285,7 @@ impl Operator for Div {
if let Some(result) = result { if let Some(result) = result {
Ok(Value::Int(result)) Ok(Value::Int(result))
} else { } else {
Err(Error::division_error( Err(EvalexprError::division_error(
arguments[0].clone(), arguments[0].clone(),
arguments[1].clone(), arguments[1].clone(),
)) ))
@ -311,7 +311,7 @@ impl Operator for Mod {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -321,7 +321,7 @@ impl Operator for Mod {
if let Some(result) = result { if let Some(result) = result {
Ok(Value::Int(result)) Ok(Value::Int(result))
} else { } else {
Err(Error::modulation_error( Err(EvalexprError::modulation_error(
arguments[0].clone(), arguments[0].clone(),
arguments[1].clone(), arguments[1].clone(),
)) ))
@ -347,7 +347,7 @@ impl Operator for Exp {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -374,7 +374,7 @@ impl Operator for Eq {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
if arguments[0] == arguments[1] { if arguments[0] == arguments[1] {
@ -398,7 +398,7 @@ impl Operator for Neq {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
if arguments[0] != arguments[1] { if arguments[0] != arguments[1] {
@ -422,7 +422,7 @@ impl Operator for Gt {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -456,7 +456,7 @@ impl Operator for Lt {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -490,7 +490,7 @@ impl Operator for Geq {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -524,7 +524,7 @@ impl Operator for Leq {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
expect_number(&arguments[0])?; expect_number(&arguments[0])?;
expect_number(&arguments[1])?; expect_number(&arguments[1])?;
@ -558,7 +558,7 @@ impl Operator for And {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
let a = expect_boolean(&arguments[0])?; let a = expect_boolean(&arguments[0])?;
let b = expect_boolean(&arguments[1])?; let b = expect_boolean(&arguments[1])?;
@ -584,7 +584,7 @@ impl Operator for Or {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 2)?; expect_operator_argument_amount(arguments.len(), 2)?;
let a = expect_boolean(&arguments[0])?; let a = expect_boolean(&arguments[0])?;
let b = expect_boolean(&arguments[1])?; let b = expect_boolean(&arguments[1])?;
@ -610,7 +610,7 @@ impl Operator for Not {
1 1
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 1)?; expect_operator_argument_amount(arguments.len(), 1)?;
let a = expect_boolean(&arguments[0])?; let a = expect_boolean(&arguments[0])?;
@ -635,7 +635,7 @@ impl Operator for Tuple {
2 2
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
if let Value::Tuple(tuple) = &arguments[0] { if let Value::Tuple(tuple) = &arguments[0] {
let mut tuple = tuple.clone(); let mut tuple = tuple.clone();
if let Value::Tuple(tuple2) = &arguments[1] { if let Value::Tuple(tuple2) = &arguments[1] {
@ -672,7 +672,7 @@ impl Operator for Const {
0 0
} }
fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], _configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 0)?; expect_operator_argument_amount(arguments.len(), 0)?;
Ok(self.value.clone()) Ok(self.value.clone())
@ -692,11 +692,11 @@ impl Operator for VariableIdentifier {
0 0
} }
fn eval(&self, _arguments: &[Value], configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, _arguments: &[Value], configuration: &Configuration) -> Result<Value, EvalexprError> {
if let Some(value) = configuration.get_value(&self.identifier).cloned() { if let Some(value) = configuration.get_value(&self.identifier).cloned() {
Ok(value) Ok(value)
} else { } else {
Err(Error::VariableIdentifierNotFound(self.identifier.clone())) Err(EvalexprError::VariableIdentifierNotFound(self.identifier.clone()))
} }
} }
} }
@ -714,7 +714,7 @@ impl Operator for FunctionIdentifier {
1 1
} }
fn eval(&self, arguments: &[Value], configuration: &Configuration) -> Result<Value, Error> { fn eval(&self, arguments: &[Value], configuration: &Configuration) -> Result<Value, EvalexprError> {
expect_operator_argument_amount(arguments.len(), 1)?; expect_operator_argument_amount(arguments.len(), 1)?;
let arguments = if let Value::Tuple(arguments) = &arguments[0] { let arguments = if let Value::Tuple(arguments) = &arguments[0] {
@ -728,7 +728,7 @@ impl Operator for FunctionIdentifier {
} else if let Some(builtin_function) = builtin_function(&self.identifier) { } else if let Some(builtin_function) = builtin_function(&self.identifier) {
builtin_function.call(arguments) builtin_function.call(arguments)
} else { } else {
Err(Error::FunctionIdentifierNotFound(self.identifier.clone())) Err(EvalexprError::FunctionIdentifierNotFound(self.identifier.clone()))
} }
} }
} }

View File

@ -1,4 +1,4 @@
use error::Error; use error::EvalexprError;
use value::{FloatType, IntType}; use value::{FloatType, IntType};
mod display; mod display;
@ -173,7 +173,7 @@ fn str_to_tokens(string: &str) -> Vec<PartialToken> {
} }
/// Resolves all partial tokens by converting them to complex tokens. /// Resolves all partial tokens by converting them to complex tokens.
fn resolve_literals(mut tokens: &[PartialToken]) -> Result<Vec<Token>, Error> { fn resolve_literals(mut tokens: &[PartialToken]) -> Result<Vec<Token>, EvalexprError> {
let mut result = Vec::new(); let mut result = Vec::new();
while tokens.len() > 0 { while tokens.len() > 0 {
let first = tokens[0].clone(); let first = tokens[0].clone();
@ -204,7 +204,7 @@ fn resolve_literals(mut tokens: &[PartialToken]) -> Result<Vec<Token>, Error> {
}, },
PartialToken::Eq => match second { PartialToken::Eq => match second {
Some(PartialToken::Eq) => Some(Token::Eq), Some(PartialToken::Eq) => Some(Token::Eq),
_ => return Err(Error::unmatched_partial_token(first, second)), _ => return Err(EvalexprError::unmatched_partial_token(first, second)),
}, },
PartialToken::ExclamationMark => match second { PartialToken::ExclamationMark => match second {
Some(PartialToken::Eq) => Some(Token::Eq), Some(PartialToken::Eq) => Some(Token::Eq),
@ -229,11 +229,11 @@ fn resolve_literals(mut tokens: &[PartialToken]) -> Result<Vec<Token>, Error> {
}, },
PartialToken::Ampersand => match second { PartialToken::Ampersand => match second {
Some(PartialToken::Ampersand) => Some(Token::And), Some(PartialToken::Ampersand) => Some(Token::And),
_ => return Err(Error::unmatched_partial_token(first, second)), _ => return Err(EvalexprError::unmatched_partial_token(first, second)),
}, },
PartialToken::VerticalBar => match second { PartialToken::VerticalBar => match second {
Some(PartialToken::VerticalBar) => Some(Token::Or), Some(PartialToken::VerticalBar) => Some(Token::Or),
_ => return Err(Error::unmatched_partial_token(first, second)), _ => return Err(EvalexprError::unmatched_partial_token(first, second)),
}, },
} }
.into_iter(), .into_iter(),
@ -244,6 +244,6 @@ fn resolve_literals(mut tokens: &[PartialToken]) -> Result<Vec<Token>, Error> {
Ok(result) Ok(result)
} }
pub(crate) fn tokenize(string: &str) -> Result<Vec<Token>, Error> { pub(crate) fn tokenize(string: &str) -> Result<Vec<Token>, EvalexprError> {
resolve_literals(&str_to_tokens(string)) resolve_literals(&str_to_tokens(string))
} }

View File

@ -1,9 +1,10 @@
use crate::{configuration::Configuration, error::Error, operator::*, value::Value};
use token::Token;
use value::TupleType;
use EmptyConfiguration; use EmptyConfiguration;
use FloatType; use FloatType;
use IntType; use IntType;
use token::Token;
use value::TupleType;
use crate::{configuration::Configuration, error::EvalexprError, operator::*, value::Value};
mod display; mod display;
@ -45,7 +46,7 @@ impl Node {
/// Evaluates the operator tree rooted at this node with the given configuration. /// Evaluates the operator tree rooted at this node with the given configuration.
/// ///
/// Fails, if one of the operators in the expression tree fails. /// Fails, if one of the operators in the expression tree fails.
pub fn eval_with_configuration(&self, configuration: &Configuration) -> Result<Value, Error> { pub fn eval_with_configuration(&self, configuration: &Configuration) -> Result<Value, EvalexprError> {
let mut arguments = Vec::new(); let mut arguments = Vec::new();
for child in self.children() { for child in self.children() {
arguments.push(child.eval_with_configuration(configuration)?); arguments.push(child.eval_with_configuration(configuration)?);
@ -56,7 +57,7 @@ impl Node {
/// Evaluates the operator tree rooted at this node with an empty configuration. /// Evaluates the operator tree rooted at this node with an empty configuration.
/// ///
/// Fails, if one of the operators in the expression tree fails. /// Fails, if one of the operators in the expression tree fails.
pub fn eval(&self) -> Result<Value, Error> { pub fn eval(&self) -> Result<Value, EvalexprError> {
self.eval_with_configuration(&EmptyConfiguration) self.eval_with_configuration(&EmptyConfiguration)
} }
@ -66,10 +67,10 @@ impl Node {
pub fn eval_string_with_configuration( pub fn eval_string_with_configuration(
&self, &self,
configuration: &Configuration, configuration: &Configuration,
) -> Result<String, Error> { ) -> Result<String, EvalexprError> {
match self.eval_with_configuration(configuration) { match self.eval_with_configuration(configuration) {
Ok(Value::String(string)) => Ok(string), Ok(Value::String(string)) => Ok(string),
Ok(value) => Err(Error::expected_string(value)), Ok(value) => Err(EvalexprError::expected_string(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -80,10 +81,10 @@ impl Node {
pub fn eval_float_with_configuration( pub fn eval_float_with_configuration(
&self, &self,
configuration: &Configuration, configuration: &Configuration,
) -> Result<FloatType, Error> { ) -> Result<FloatType, EvalexprError> {
match self.eval_with_configuration(configuration) { match self.eval_with_configuration(configuration) {
Ok(Value::Float(float)) => Ok(float), Ok(Value::Float(float)) => Ok(float),
Ok(value) => Err(Error::expected_float(value)), Ok(value) => Err(EvalexprError::expected_float(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -94,10 +95,10 @@ impl Node {
pub fn eval_int_with_configuration( pub fn eval_int_with_configuration(
&self, &self,
configuration: &Configuration, configuration: &Configuration,
) -> Result<IntType, Error> { ) -> Result<IntType, EvalexprError> {
match self.eval_with_configuration(configuration) { match self.eval_with_configuration(configuration) {
Ok(Value::Int(int)) => Ok(int), Ok(Value::Int(int)) => Ok(int),
Ok(value) => Err(Error::expected_int(value)), Ok(value) => Err(EvalexprError::expected_int(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -108,10 +109,10 @@ impl Node {
pub fn eval_boolean_with_configuration( pub fn eval_boolean_with_configuration(
&self, &self,
configuration: &Configuration, configuration: &Configuration,
) -> Result<bool, Error> { ) -> Result<bool, EvalexprError> {
match self.eval_with_configuration(configuration) { match self.eval_with_configuration(configuration) {
Ok(Value::Boolean(boolean)) => Ok(boolean), Ok(Value::Boolean(boolean)) => Ok(boolean),
Ok(value) => Err(Error::expected_boolean(value)), Ok(value) => Err(EvalexprError::expected_boolean(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -122,10 +123,10 @@ impl Node {
pub fn eval_tuple_with_configuration( pub fn eval_tuple_with_configuration(
&self, &self,
configuration: &Configuration, configuration: &Configuration,
) -> Result<TupleType, Error> { ) -> Result<TupleType, EvalexprError> {
match self.eval_with_configuration(configuration) { match self.eval_with_configuration(configuration) {
Ok(Value::Tuple(tuple)) => Ok(tuple), Ok(Value::Tuple(tuple)) => Ok(tuple),
Ok(value) => Err(Error::expected_tuple(value)), Ok(value) => Err(EvalexprError::expected_tuple(value)),
Err(error) => Err(error), Err(error) => Err(error),
} }
} }
@ -133,35 +134,35 @@ impl Node {
/// Evaluates the operator tree rooted at this node into a string with an empty configuration. /// Evaluates the operator tree rooted at this node into a string with an empty configuration.
/// ///
/// Fails, if one of the operators in the expression tree fails. /// Fails, if one of the operators in the expression tree fails.
pub fn eval_string(&self) -> Result<String, Error> { pub fn eval_string(&self) -> Result<String, EvalexprError> {
self.eval_string_with_configuration(&EmptyConfiguration) self.eval_string_with_configuration(&EmptyConfiguration)
} }
/// Evaluates the operator tree rooted at this node into a float with an empty configuration. /// Evaluates the operator tree rooted at this node into a float with an empty configuration.
/// ///
/// Fails, if one of the operators in the expression tree fails. /// Fails, if one of the operators in the expression tree fails.
pub fn eval_float(&self) -> Result<FloatType, Error> { pub fn eval_float(&self) -> Result<FloatType, EvalexprError> {
self.eval_float_with_configuration(&EmptyConfiguration) self.eval_float_with_configuration(&EmptyConfiguration)
} }
/// Evaluates the operator tree rooted at this node into an integer with an empty configuration. /// Evaluates the operator tree rooted at this node into an integer with an empty configuration.
/// ///
/// Fails, if one of the operators in the expression tree fails. /// Fails, if one of the operators in the expression tree fails.
pub fn eval_int(&self) -> Result<IntType, Error> { pub fn eval_int(&self) -> Result<IntType, EvalexprError> {
self.eval_int_with_configuration(&EmptyConfiguration) self.eval_int_with_configuration(&EmptyConfiguration)
} }
/// Evaluates the operator tree rooted at this node into a boolean with an empty configuration. /// Evaluates the operator tree rooted at this node into a boolean with an empty configuration.
/// ///
/// Fails, if one of the operators in the expression tree fails. /// Fails, if one of the operators in the expression tree fails.
pub fn eval_boolean(&self) -> Result<bool, Error> { pub fn eval_boolean(&self) -> Result<bool, EvalexprError> {
self.eval_boolean_with_configuration(&EmptyConfiguration) self.eval_boolean_with_configuration(&EmptyConfiguration)
} }
/// Evaluates the operator tree rooted at this node into a tuple with an empty configuration. /// Evaluates the operator tree rooted at this node into a tuple with an empty configuration.
/// ///
/// Fails, if one of the operators in the expression tree fails. /// Fails, if one of the operators in the expression tree fails.
pub fn eval_tuple(&self) -> Result<TupleType, Error> { pub fn eval_tuple(&self) -> Result<TupleType, EvalexprError> {
self.eval_tuple_with_configuration(&EmptyConfiguration) self.eval_tuple_with_configuration(&EmptyConfiguration)
} }
@ -177,13 +178,13 @@ impl Node {
self.children().len() == self.operator().argument_amount() self.children().len() == self.operator().argument_amount()
} }
fn insert_back_prioritized(&mut self, node: Node, is_root_node: bool) -> Result<(), Error> { fn insert_back_prioritized(&mut self, node: Node, is_root_node: bool) -> Result<(), EvalexprError> {
if self.operator().precedence() < node.operator().precedence() || is_root_node if self.operator().precedence() < node.operator().precedence() || is_root_node
// Right-to-left chaining // Right-to-left chaining
|| (self.operator().precedence() == node.operator().precedence() && !self.operator().is_left_to_right() && !node.operator().is_left_to_right()) || (self.operator().precedence() == node.operator().precedence() && !self.operator().is_left_to_right() && !node.operator().is_left_to_right())
{ {
if self.operator().is_leaf() { if self.operator().is_leaf() {
Err(Error::AppendedToLeafNode) Err(EvalexprError::AppendedToLeafNode)
} else if self.has_correct_amount_of_children() { } else if self.has_correct_amount_of_children() {
if self.children.last().unwrap().operator().precedence() if self.children.last().unwrap().operator().precedence()
< node.operator().precedence() < node.operator().precedence()
@ -197,7 +198,7 @@ impl Node {
.insert_back_prioritized(node, false) .insert_back_prioritized(node, false)
} else { } else {
if node.operator().is_leaf() { if node.operator().is_leaf() {
return Err(Error::AppendedToLeafNode); return Err(EvalexprError::AppendedToLeafNode);
} }
let last_child = self.children.pop().unwrap(); let last_child = self.children.pop().unwrap();
@ -212,12 +213,12 @@ impl Node {
Ok(()) Ok(())
} }
} else { } else {
Err(Error::PrecedenceViolation) Err(EvalexprError::PrecedenceViolation)
} }
} }
} }
pub(crate) fn tokens_to_operator_tree(tokens: Vec<Token>) -> Result<Node, Error> { pub(crate) fn tokens_to_operator_tree(tokens: Vec<Token>) -> Result<Node, EvalexprError> {
let mut root = vec![Node::root_node()]; let mut root = vec![Node::root_node()];
let mut last_token_is_rightsided_value = false; let mut last_token_is_rightsided_value = false;
let mut token_iter = tokens.iter().peekable(); let mut token_iter = tokens.iter().peekable();
@ -255,7 +256,7 @@ pub(crate) fn tokens_to_operator_tree(tokens: Vec<Token>) -> Result<Node, Error>
}, },
Token::RBrace => { Token::RBrace => {
if root.len() < 2 { if root.len() < 2 {
return Err(Error::UnmatchedRBrace); return Err(EvalexprError::UnmatchedRBrace);
} else { } else {
root.pop() root.pop()
} }
@ -281,7 +282,7 @@ pub(crate) fn tokens_to_operator_tree(tokens: Vec<Token>) -> Result<Node, Error>
if let Some(root) = root.last_mut() { if let Some(root) = root.last_mut() {
root.insert_back_prioritized(node, true)?; root.insert_back_prioritized(node, true)?;
} else { } else {
return Err(Error::UnmatchedRBrace); return Err(EvalexprError::UnmatchedRBrace);
} }
} }
@ -289,19 +290,19 @@ pub(crate) fn tokens_to_operator_tree(tokens: Vec<Token>) -> Result<Node, Error>
} }
if root.len() > 1 { if root.len() > 1 {
Err(Error::UnmatchedLBrace) Err(EvalexprError::UnmatchedLBrace)
} else if let Some(mut root) = root.pop() { } else if let Some(mut root) = root.pop() {
if root.children().len() > 1 { if root.children().len() > 1 {
Err(Error::wrong_operator_argument_amount( Err(EvalexprError::wrong_operator_argument_amount(
root.children().len(), root.children().len(),
1, 1,
)) ))
} else if let Some(child) = root.children.pop() { } else if let Some(child) = root.children.pop() {
Ok(child) Ok(child)
} else { } else {
Err(Error::EmptyExpression) Err(EvalexprError::EmptyExpression)
} }
} else { } else {
Err(Error::UnmatchedRBrace) Err(EvalexprError::UnmatchedRBrace)
} }
} }

View File

@ -1,4 +1,4 @@
use error::Error; use error::EvalexprError;
mod display; mod display;
@ -68,44 +68,44 @@ impl Value {
} }
/// Clones the value stored in `self` as `String`, or returns `Err` if `self` is not a `Value::String`. /// Clones the value stored in `self` as `String`, or returns `Err` if `self` is not a `Value::String`.
pub fn as_string(&self) -> Result<String, Error> { pub fn as_string(&self) -> Result<String, EvalexprError> {
match self { match self {
Value::String(string) => Ok(string.clone()), Value::String(string) => Ok(string.clone()),
value => Err(Error::expected_string(value.clone())), value => Err(EvalexprError::expected_string(value.clone())),
} }
} }
/// Clones the value stored in `self` as `IntType`, or returns `Err` if `self` is not a `Value::Int`. /// Clones the value stored in `self` as `IntType`, or returns `Err` if `self` is not a `Value::Int`.
pub fn as_int(&self) -> Result<IntType, Error> { pub fn as_int(&self) -> Result<IntType, EvalexprError> {
match self { match self {
Value::Int(i) => Ok(*i), Value::Int(i) => Ok(*i),
value => Err(Error::expected_int(value.clone())), value => Err(EvalexprError::expected_int(value.clone())),
} }
} }
/// Clones the value stored in `self` as `FloatType`, or returns `Err` if `self` is not a `Value::Float` or `Value::Int`. /// Clones the value stored in `self` as `FloatType`, or returns `Err` if `self` is not a `Value::Float` or `Value::Int`.
/// Note that this method silently converts `IntType` to `FloatType`, if `self` is a `Value::Int`. /// Note that this method silently converts `IntType` to `FloatType`, if `self` is a `Value::Int`.
pub fn as_float(&self) -> Result<FloatType, Error> { pub fn as_float(&self) -> Result<FloatType, EvalexprError> {
match self { match self {
Value::Float(f) => Ok(*f), Value::Float(f) => Ok(*f),
Value::Int(i) => Ok(*i as FloatType), Value::Int(i) => Ok(*i as FloatType),
value => Err(Error::expected_number(value.clone())), value => Err(EvalexprError::expected_number(value.clone())),
} }
} }
/// Clones the value stored in `self` as `bool`, or returns `Err` if `self` is not a `Value::Boolean`. /// Clones the value stored in `self` as `bool`, or returns `Err` if `self` is not a `Value::Boolean`.
pub fn as_boolean(&self) -> Result<bool, Error> { pub fn as_boolean(&self) -> Result<bool, EvalexprError> {
match self { match self {
Value::Boolean(boolean) => Ok(*boolean), Value::Boolean(boolean) => Ok(*boolean),
value => Err(Error::expected_boolean(value.clone())), value => Err(EvalexprError::expected_boolean(value.clone())),
} }
} }
/// Clones the value stored in `self` as `TupleType`, or returns`Err` if `self` is not a `Value::Tuple`. /// Clones the value stored in `self` as `TupleType`, or returns`Err` if `self` is not a `Value::Tuple`.
pub fn as_tuple(&self) -> Result<TupleType, Error> { pub fn as_tuple(&self) -> Result<TupleType, EvalexprError> {
match self { match self {
Value::Tuple(tuple) => Ok(tuple.clone()), Value::Tuple(tuple) => Ok(tuple.clone()),
value => Err(Error::expected_tuple(value.clone())), value => Err(EvalexprError::expected_tuple(value.clone())),
} }
} }
} }
@ -146,7 +146,7 @@ impl From<TupleType> for Value {
} }
} }
impl From<Value> for Result<Value, Error> { impl From<Value> for Result<Value, EvalexprError> {
fn from(value: Value) -> Self { fn from(value: Value) -> Self {
Ok(value) Ok(value)
} }

View File

@ -1,6 +1,6 @@
extern crate evalexpr; extern crate evalexpr;
use evalexpr::{error::*, *}; use evalexpr::{*, error::*};
#[test] #[test]
fn test_unary_examples() { fn test_unary_examples() {
@ -10,7 +10,7 @@ fn test_unary_examples() {
assert_eq!(eval("false"), Ok(Value::Boolean(false))); assert_eq!(eval("false"), Ok(Value::Boolean(false)));
assert_eq!( assert_eq!(
eval("blub"), eval("blub"),
Err(Error::VariableIdentifierNotFound("blub".to_string())) Err(EvalexprError::VariableIdentifierNotFound("blub".to_string()))
); );
assert_eq!(eval("-3"), Ok(Value::Int(-3))); assert_eq!(eval("-3"), Ok(Value::Int(-3)));
assert_eq!(eval("-3.6"), Ok(Value::Float(-3.6))); assert_eq!(eval("-3.6"), Ok(Value::Float(-3.6)));
@ -144,7 +144,7 @@ fn test_functions() {
} else if let Value::Float(float) = arguments[0] { } else if let Value::Float(float) = arguments[0] {
Ok(Value::Float(float - 2.0)) Ok(Value::Float(float - 2.0))
} else { } else {
Err(Error::expected_number(arguments[0].clone())) Err(EvalexprError::expected_number(arguments[0].clone()))
} }
}), }),
), ),
@ -186,7 +186,7 @@ fn test_n_ary_functions() {
} else if let Value::Float(float) = arguments[0] { } else if let Value::Float(float) = arguments[0] {
Ok(Value::Float(float - 2.0)) Ok(Value::Float(float - 2.0))
} else { } else {
Err(Error::expected_number(arguments[0].clone())) Err(EvalexprError::expected_number(arguments[0].clone()))
} }
}), }),
), ),
@ -262,7 +262,7 @@ fn test_n_ary_functions() {
); );
assert_eq!( assert_eq!(
eval_with_configuration("count()", &configuration), eval_with_configuration("count()", &configuration),
Err(Error::WrongOperatorArgumentAmount { Err(EvalexprError::WrongOperatorArgumentAmount {
actual: 0, actual: 0,
expected: 1 expected: 1
}) })
@ -290,20 +290,20 @@ fn test_n_ary_functions() {
fn test_errors() { fn test_errors() {
assert_eq!( assert_eq!(
eval("-true"), eval("-true"),
Err(Error::expected_number(Value::Boolean(true))) Err(EvalexprError::expected_number(Value::Boolean(true)))
); );
assert_eq!( assert_eq!(
eval("1-true"), eval("1-true"),
Err(Error::expected_number(Value::Boolean(true))) Err(EvalexprError::expected_number(Value::Boolean(true)))
); );
assert_eq!( assert_eq!(
eval("true-"), eval("true-"),
Err(Error::WrongOperatorArgumentAmount { Err(EvalexprError::WrongOperatorArgumentAmount {
actual: 1, actual: 1,
expected: 2 expected: 2
}) })
); );
assert_eq!(eval("!(()true)"), Err(Error::AppendedToLeafNode)); assert_eq!(eval("!(()true)"), Err(EvalexprError::AppendedToLeafNode));
} }
#[test] #[test]