Add Node::eval_number[_with_context] methods

Relates to #20
This commit is contained in:
Sebastian Schmidt 2019-03-27 18:54:45 +01:00
parent 7d0abc8406
commit 720b2f90c2
3 changed files with 28 additions and 0 deletions

View File

@ -9,6 +9,7 @@
* Make the `TupleType` alias public
* Add the `ValueType` enum that represents the type of a value for easier comparisons and matchings
* Add `EvalexprResult<T>` type that uses the `EvalexprError` type (renamed from `Error`)
* Add `Node::eval_number` and `Node::eval_number_with_context` to evaluate to int or float and silently converting to float
### Removed

View File

@ -94,6 +94,19 @@ impl Node {
}
}
/// Evaluates the operator tree rooted at this node into a float with an the given context.
/// If the result of the expression is an integer, it is silently converted into a float.
///
/// Fails, if one of the operators in the expression tree fails.
pub fn eval_number_with_context(&self, context: &Context) -> Result<FloatType, EvalexprError> {
match self.eval_with_context(context) {
Ok(Value::Int(int)) => Ok(int as FloatType),
Ok(Value::Float(float)) => Ok(float),
Ok(value) => Err(EvalexprError::expected_int(value)),
Err(error) => Err(error),
}
}
/// Evaluates the operator tree rooted at this node into a boolean with an the given context.
///
/// Fails, if one of the operators in the expression tree fails.
@ -137,6 +150,14 @@ impl Node {
self.eval_int_with_context(&EmptyContext)
}
/// Evaluates the operator tree rooted at this node into a float with an empty context.
/// If the result of the expression is an integer, it is silently converted into a float.
///
/// Fails, if one of the operators in the expression tree fails.
pub fn eval_number(&self) -> Result<FloatType, EvalexprError> {
self.eval_number_with_context(&EmptyContext)
}
/// Evaluates the operator tree rooted at this node into a boolean with an empty context.
///
/// Fails, if one of the operators in the expression tree fails.

View File

@ -374,6 +374,12 @@ fn test_shortcut_functions() {
.eval_int_with_context(&context),
Ok(3)
);
assert_eq!(
build_operator_tree("3")
.unwrap()
.eval_number_with_context(&context),
Ok(3.0)
);
assert_eq!(
build_operator_tree("true").unwrap().eval_boolean(),
Ok(true)