From 720b2f90c281aff413139bc8f68ef932afa27fad Mon Sep 17 00:00:00 2001 From: Sebastian Schmidt Date: Wed, 27 Mar 2019 18:54:45 +0100 Subject: [PATCH] Add Node::eval_number[_with_context] methods Relates to #20 --- CHANGELOG.md | 1 + src/tree/mod.rs | 21 +++++++++++++++++++++ tests/integration.rs | 6 ++++++ 3 files changed, 28 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b65f70..5ebc3fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` 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 diff --git a/src/tree/mod.rs b/src/tree/mod.rs index f967fed..6f501f7 100644 --- a/src/tree/mod.rs +++ b/src/tree/mod.rs @@ -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 { + 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 { + 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. diff --git a/tests/integration.rs b/tests/integration.rs index 0490b3b..301ad14 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -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)