2019-03-18 17:51:09 +00:00
# evalexpr
2016-11-16 16:31:52 +00:00
2019-03-20 13:04:59 +00:00
[![Project Status: Active – The project has reached a stable, usable state and is being actively developed. ](https://www.repostatus.org/badges/latest/active.svg )](https://www.repostatus.org/#active)
2019-03-20 10:07:02 +00:00
[![ ](http://meritbadge.herokuapp.com/evalexpr )](https://crates.io/crates/evalexpr)
[![ ](https://docs.rs/evalexpr/badge.svg )](https://docs.rs/evalexpr)
2016-11-16 16:12:26 +00:00
2019-03-28 11:09:06 +00:00
Evalexpr is an expression evaluator and tiny scripting language in Rust.
2019-03-19 14:47:17 +00:00
It has a small and easy to use interface and can be easily integrated into any application.
It is very lightweight and comes with no further dependencies.
Evalexpr is [available on crates.io ](https://crates.io/crates/evalexpr ), and its [API Documentation is available on docs.rs ](https://docs.rs/evalexpr ).
2017-02-25 06:51:55 +00:00
2019-03-19 08:43:52 +00:00
<!-- cargo - sync - readme start -->
2019-03-19 10:01:06 +00:00
## Quickstart
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
Add `evalexpr` as dependency to your `Cargo.toml` :
2019-03-19 08:43:52 +00:00
```toml
[dependencies]
2019-04-13 16:27:59 +00:00
evalexpr = "5"
2019-03-19 08:43:52 +00:00
```
2019-03-19 10:01:06 +00:00
Add the `extern crate` definition to your `main.rs` or `lib.rs` :
2019-03-19 08:43:52 +00:00
```rust
2019-03-19 10:01:06 +00:00
extern crate evalexpr;
2019-03-19 08:43:52 +00:00
```
2019-03-21 07:29:04 +00:00
Then you can use `evalexpr` to **evaluate expressions** like this:
2019-03-19 08:43:52 +00:00
```rust
2019-03-19 10:01:06 +00:00
use evalexpr::*;
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
assert_eq!(eval("1 + 2 + 3"), Ok(Value::from(6)));
2019-03-20 15:30:37 +00:00
// `eval` returns a variant of the `Value` enum,
// while `eval_[type]` returns the respective type directly.
// Both can be used interchangeably.
assert_eq!(eval_int("1 + 2 + 3"), Ok(6));
2019-03-19 10:01:06 +00:00
assert_eq!(eval("1 - 2 * 3"), Ok(Value::from(-5)));
assert_eq!(eval("1.0 + 2 * 3"), Ok(Value::from(7.0)));
assert_eq!(eval("true & & 4 > 2"), Ok(Value::from(true)));
2019-03-19 08:43:52 +00:00
```
2019-03-28 11:09:06 +00:00
You can **chain** expressions and **assign** to variables like this:
```rust
use evalexpr::*;
let mut context = HashMapContext::new();
// Assign 5 to a like this
assert_eq!(eval_empty_with_context_mut("a = 5", & mut context), Ok(EMPTY_VALUE));
// The HashMapContext is type safe, so this will fail now
assert_eq!(eval_empty_with_context_mut("a = 5.0", & mut context), Err(EvalexprError::expected_int(Value::from(5.0))));
// We can check which value the context stores for a like this
assert_eq!(context.get_value("a"), Some(&Value::from(5)));
// And use the value in another expression like this
assert_eq!(eval_int_with_context_mut("a = a + 2; a", & mut context), Ok(7));
```
2019-03-21 07:29:04 +00:00
And you can use **variables** and **functions** in expressions like this:
2019-03-19 08:43:52 +00:00
```rust
2019-03-19 10:01:06 +00:00
use evalexpr::*;
2019-03-19 14:47:17 +00:00
use evalexpr::error::expect_number;
2019-03-19 10:01:06 +00:00
2019-04-17 15:24:07 +00:00
let context = context_map! {
2019-04-26 15:33:59 +00:00
"five" => 5,
"twelve" => 12,
"f" => Function::new(Some(1) /* argument amount */, Box::new(|arguments| {
if let Value::Int(int) = arguments[0] {
Ok(Value::Int(int / 2))
} else if let Value::Float(float) = arguments[0] {
Ok(Value::Float(float / 2.0))
} else {
Err(EvalexprError::expected_number(arguments[0].clone()))
}
})),
"avg" => Function::new(Some(2) /* argument amount */, Box::new(|arguments| {
expect_number(&arguments[0])?;
expect_number(&arguments[1])?;
if let (Value::Int(a), Value::Int(b)) = (& arguments[0], & arguments[1]) {
Ok(Value::Int((a + b) / 2))
} else {
Ok(Value::Float((arguments[0].as_number()? + arguments[1].as_number()?) / 2.0))
}
}))
}.unwrap(); // Do proper error handling here
2019-03-19 10:01:06 +00:00
2019-03-27 17:09:20 +00:00
assert_eq!(eval_with_context("five + 8 > f(twelve)", & context), Ok(Value::from(true)));
// `eval_with_context` returns a variant of the `Value` enum,
// while `eval_[type]_with_context` returns the respective type directly.
2019-03-20 15:30:37 +00:00
// Both can be used interchangeably.
2019-03-27 17:09:20 +00:00
assert_eq!(eval_boolean_with_context("five + 8 > f(twelve)", & context), Ok(true));
assert_eq!(eval_with_context("avg(2, 4) == 3", & context), Ok(Value::from(true)));
2019-03-19 08:43:52 +00:00
```
2019-03-21 07:29:04 +00:00
You can also **precompile** expressions like this:
2019-03-19 08:43:52 +00:00
```rust
2019-03-19 10:01:06 +00:00
use evalexpr::*;
2019-03-27 17:09:20 +00:00
let precompiled = build_operator_tree("a * b - c > 5").unwrap(); // Do proper error handling here
2019-03-19 08:43:52 +00:00
2019-04-17 15:24:07 +00:00
let mut context = context_map! {
2019-04-26 15:33:59 +00:00
"a" => 6,
"b" => 2,
"c" => 3
}.unwrap(); // Do proper error handling here
2019-03-27 17:09:20 +00:00
assert_eq!(precompiled.eval_with_context(& context), Ok(Value::from(true)));
2019-03-19 08:43:52 +00:00
2019-03-28 08:14:37 +00:00
context.set_value("c".into(), 8.into()).unwrap(); // Do proper error handling here
2019-03-27 17:09:20 +00:00
assert_eq!(precompiled.eval_with_context(& context), Ok(Value::from(false)));
// `Node::eval_with_context` returns a variant of the `Value` enum,
// while `Node::eval_[type]_with_context` returns the respective type directly.
2019-03-20 15:30:37 +00:00
// Both can be used interchangeably.
2019-03-27 17:09:20 +00:00
assert_eq!(precompiled.eval_boolean_with_context(& context), Ok(false));
2019-03-19 08:43:52 +00:00
```
2019-03-19 10:01:06 +00:00
## Features
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
### Operators
2019-03-19 08:43:52 +00:00
2019-03-19 14:47:17 +00:00
This crate offers a set of binary and unary operators for building expressions.
Operators have a precedence to determine their order of evaluation.
The precedence should resemble that of most common programming languages, especially Rust.
The precedence of variables and values is 200, and the precedence of function literals is 190.
2019-03-19 10:01:06 +00:00
Supported binary operators:
2019-03-19 08:43:52 +00:00
2019-03-28 14:01:20 +00:00
| Operator | Precedence | Description |
|----------|------------|-------------|
| ^ | 120 | Exponentiation |
| * | 100 | Product |
| / | 100 | Division |
| % | 100 | Modulo |
2019-04-13 16:27:59 +00:00
| + | 95 | Sum or String Concatenation |
2019-03-28 14:01:20 +00:00
| - | 95 | Difference |
| < | 80 | Lower than |
| \> | 80 | Greater than |
| < = | 80 | Lower than or equal |
| \>= | 80 | Greater than or equal |
| == | 80 | Equal |
| != | 80 | Not equal |
| & & | 75 | Logical and |
| | | | 70 | Logical or |
| = | 50 | Assignment |
| , | 40 | Aggregation |
| ; | 0 | Expression Chaining |
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
Supported unary operators:
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
| Operator | Precedence | Description |
|----------|------------|-------------|
| - | 110 | Negation |
| ! | 110 | Logical not |
2019-03-19 08:43:52 +00:00
2019-03-19 16:58:53 +00:00
#### The Aggregation Operator
The aggregation operator aggregates two values into a tuple.
If one of the values is a tuple already, the resulting tuple will be flattened.
Example:
```rust
use evalexpr::*;
assert_eq!(eval("1, 2, 3"), Ok(Value::from(vec![Value::from(1), Value::from(2), Value::from(3)])));
```
2019-03-28 10:46:40 +00:00
#### The Assignment Operator
This crate features the assignment operator, that allows expressions to store their result in a variable in the expression context.
If an expression uses the assignment operator, it must be evaluated with a mutable context.
Note that assignments are type safe, meaning if an identifier is assigned a value of a type once, it cannot be assigned a value of another type.
```rust
use evalexpr::*;
let mut context = HashMapContext::new();
assert_eq!(eval_with_context("a = 5", & context), Err(EvalexprError::ContextNotManipulable));
assert_eq!(eval_empty_with_context_mut("a = 5", & mut context), Ok(EMPTY_VALUE));
assert_eq!(eval_empty_with_context_mut("a = 5.0", & mut context), Err(EvalexprError::expected_int(5.0.into())));
assert_eq!(eval_int_with_context("a", & context), Ok(5));
assert_eq!(context.get_value("a"), Some(5.into()).as_ref());
```
#### The Expression Chaining Operator
The expression chaining operator works as one would expect from programming languages that use the semicolon to end statements, like `Rust` , `C` or `Java` .
It has the special feature that it returns the value of the last expression in the expression chain.
If the last expression is terminated by a semicolon as well, then `Value::Empty` is returned.
Expression chaining is useful together with assignment to create small scripts.
```rust
use evalexpr::*;
let mut context = HashMapContext::new();
assert_eq!(eval("1;2;3;4;"), Ok(Value::Empty));
assert_eq!(eval("1;2;3;4"), Ok(4.into()));
// Initialization of variables via script.
assert_eq!(eval_empty_with_context_mut("hp = 1; max_hp = 5; heal_amount = 3;", & mut context), Ok(EMPTY_VALUE));
// Precompile healing script.
let healing_script = build_operator_tree("hp = min(hp + heal_amount, max_hp); hp").unwrap(); // Do proper error handling here
// Execute precompiled healing script.
assert_eq!(healing_script.eval_int_with_context_mut(& mut context), Ok(4));
assert_eq!(healing_script.eval_int_with_context_mut(& mut context), Ok(5));
```
2019-03-19 18:12:19 +00:00
### Builtin Functions
This crate offers a set of builtin functions.
2019-04-13 16:27:59 +00:00
| Identifier | Argument Amount | Argument Types | Description |
|------------|-----------------|----------------|-------------|
| `min` | >= 1 | Numeric | Returns the minimum of the arguments |
| `max` | >= 1 | Numeric | Returns the maximum of the arguments |
| `len` | 1 | String | Returns the character length of a string |
| `str::regex_matches` | 2 | String, String | Returns true if the first argument matches the regex in the second argument |
| `str::regex_replace` | 3 | String, String, String | Returns the first argument with all matches of the regex in the second argument replaced by the third argument |
| `str::to_lowercase` | 1 | String | Returns the lower-case version of the string |
| `str::to_uppercase` | 1 | String | Returns the upper-case version of the string |
| `str::trim` | 1 | String | Strips whitespace from the start and the end of the string |
2019-03-19 18:12:19 +00:00
The `min` and `max` functions can deal with a mixture of integer and floating point arguments.
2019-04-13 16:27:59 +00:00
If the maximum or minimum is an integer, then an integer is returned.
Otherwise, a float is returned.
The regex functions require the feature flag `regex_support` .
2019-03-19 18:12:19 +00:00
2019-03-19 10:01:06 +00:00
### Values
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
Operators take values as arguments and produce values as results.
2019-03-30 10:54:19 +00:00
Values can be boolean, integer or floating point numbers, strings, tuples or the empty type.
2019-03-19 10:01:06 +00:00
Values are denoted as displayed in the following table.
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
| Value type | Example |
|------------|---------|
2019-03-30 10:54:19 +00:00
| `Value::String` | `"abc"` , `""` , `"a\"b\\c"` |
2019-03-19 10:01:06 +00:00
| `Value::Boolean` | `true` , `false` |
| `Value::Int` | `3` , `-9` , `0` , `135412` |
| `Value::Float` | `3.` , `.35` , `1.00` , `0.5` , `123.554` |
2019-03-28 09:37:43 +00:00
| `Value::Tuple` | `(3, 55.0, false, ())` , `(1, 2)` |
| `Value::Empty` | `()` |
2019-03-19 10:01:06 +00:00
Integers are internally represented as `i64` , and floating point numbers are represented as `f64` .
2019-03-28 09:37:43 +00:00
Tuples are represented as `Vec<Value>` and empty values are not stored, but represented by rust's unit type `()` where necessary.
There exist type aliases for some of the types.
They include `IntType` , `FloatType` , `TupleType` and `EmptyType` .
2019-03-20 15:30:37 +00:00
Values can be constructed either directly or using the `From` trait.
Values can be decomposed using the `Value::as_[type]` methods.
The type of a value can be checked using the `Value::is_[type]` methods.
**Examples for constructing a value:**
| Code | Result |
|------|--------|
| `Value::from(4)` | `Value::Int(4)` |
| `Value::from(4.4)` | `Value::Float(4.4)` |
| `Value::from(true)` | `Value::Boolean(true)` |
| `Value::from(vec![Value::from(3)])` | `Value::Tuple(vec![Value::Int(3)])` |
**Examples for deconstructing a value:**
| Code | Result |
|------|--------|
| `Value::from(4).as_int()` | `Ok(4)` |
| `Value::from(4.4).as_float()` | `Ok(4.4)` |
| `Value::from(true).as_int()` | `Err(Error::ExpectedInt {actual: Value::Boolean(true)})` |
2019-03-19 10:01:06 +00:00
Operators that take numbers as arguments can either take integers or floating point numbers.
If one of the arguments is a floating point number, all others are converted to floating point numbers as well, and the resulting value is a floating point number as well.
Otherwise, the result is an integer.
2019-03-19 16:49:59 +00:00
An exception to this is the exponentiation operator that always returns a floating point number.
2019-03-19 10:01:06 +00:00
2019-03-19 10:22:06 +00:00
Values have a precedence of 200.
2019-03-19 10:01:06 +00:00
### Variables
This crate allows to compile parameterizable formulas by using variables.
A variable is a literal in the formula, that does not contain whitespace or can be parsed as value.
The user needs to provide bindings to the variables for evaluation.
2019-03-27 17:09:20 +00:00
This is done with the `Context` trait.
2019-03-19 10:01:06 +00:00
Two structs implementing this trait are predefined.
2019-03-27 17:09:20 +00:00
There is `EmptyContext` , that returns `None` for each request, and `HashMapContext` , that stores mappings from literals to variables in a hash map.
2019-03-19 10:01:06 +00:00
2019-03-28 07:41:40 +00:00
Variables do not have fixed types in the expression itself, but are typed by the context.
2019-03-27 17:09:20 +00:00
The `Context` trait contains a function that takes a string literal and returns a `Value` enum.
2019-03-19 10:01:06 +00:00
The variant of this enum decides the type on evaluation.
2019-03-19 10:22:06 +00:00
Variables have a precedence of 200.
2019-03-19 18:12:19 +00:00
### User-Defined Functions
2019-03-19 10:01:06 +00:00
This crate also allows to define arbitrary functions to be used in parsed expressions.
A function is defined as a `Function` instance.
It contains two properties, the `argument_amount` and the `function` .
2019-03-27 18:08:47 +00:00
The `function` is a boxed `Fn(&[Value]) -> EvalexprResult<Value, Error>` .
2019-03-19 16:58:53 +00:00
The `argument_amount` determines the length of the slice that is passed to `function` if it is `Some(_)` , otherwise the function is defined to take an arbitrary amount of arguments.
2019-03-19 10:22:06 +00:00
It is verified on execution by the crate and does not need to be verified by the `function` .
2019-03-19 17:05:21 +00:00
Functions with no arguments are not allowed.
Use variables instead.
2019-03-19 10:22:06 +00:00
Be aware that functions need to verify the types of values that are passed to them.
The `error` module contains some shortcuts for verification, and error types for passing a wrong value type.
Also, most numeric functions need to differentiate between being called with integers or floating point numbers, and act accordingly.
Functions are identified by literals, like variables as well.
A literal identifies a function, if it is followed by an opening brace `(` , another literal, or a value.
2019-03-27 17:09:20 +00:00
Same as variables, function bindings are provided by the user via a `Context` .
2019-03-19 10:22:06 +00:00
Functions have a precedence of 190.
### Examplary variables and functions in expressions:
| Expression | Valid? | Explanation |
|------------|--------|-------------|
| `a` | yes | |
| `abc` | yes | |
| `a<b` | no | Expression is interpreted as variable `a` , operator `<` and variable `b` |
| `a b` | no | Expression is interpreted as function `a` applied to argument `b` |
| `123` | no | Expression is interpreted as `Value::Int` |
| `true` | no | Expression is interpreted as `Value::Bool` |
| `.34` | no | Expression is interpreted as `Value::Float` |
2019-03-19 08:43:52 +00:00
2019-03-27 15:16:59 +00:00
### [Serde](https://serde.rs)
2019-03-23 13:34:05 +00:00
2019-03-28 14:39:50 +00:00
To use this crate with serde, the `serde_support` feature flag has to be set.
2019-03-27 17:34:49 +00:00
This can be done like this in the `Cargo.toml` :
```toml
[dependencies]
2019-04-13 16:27:59 +00:00
evalexpr = {version = "5", features = ["serde_support"]}
2019-03-27 17:34:49 +00:00
```
2019-03-23 13:34:05 +00:00
This crate implements `serde::de::Deserialize` for its type `Node` that represents a parsed expression tree.
2019-03-27 15:16:59 +00:00
The implementation expects a [serde `string` ](https://serde.rs/data-model.html ) as input.
2019-03-23 13:34:05 +00:00
Example parsing with [ron format ](docs.rs/ron ):
```rust
extern crate ron;
use evalexpr::*;
2019-04-26 15:33:59 +00:00
let mut context = context_map!{
"five" => 5
}.unwrap(); // Do proper error handling here
2019-03-23 13:34:05 +00:00
// In ron format, strings are surrounded by "
let serialized_free = "\"five * five\"";
match ron::de::from_str::< Node > (serialized_free) {
2019-03-27 17:09:20 +00:00
Ok(free) => assert_eq!(free.eval_with_context(& context), Ok(Value::from(25))),
2019-03-23 13:34:05 +00:00
Err(error) => {
2019-03-27 17:09:20 +00:00
() // Handle error
2019-03-23 13:34:05 +00:00
},
}
```
With `serde` , expressions can be integrated into arbitrarily complex data.
2019-03-28 14:39:50 +00:00
The crate also implements `Serialize` and `Deserialize` for the `HashMapContext` .
But note that only the variables get serialized, not the functions.
2019-03-19 10:01:06 +00:00
## License
2019-03-19 08:43:52 +00:00
2019-03-19 10:01:06 +00:00
This crate is primarily distributed under the terms of the MIT license.
See [LICENSE ](LICENSE ) for details.
2019-03-19 08:43:52 +00:00
<!-- cargo - sync - readme end -->
2019-03-19 14:47:17 +00:00
2019-03-20 10:18:25 +00:00
## No Panicking
2019-03-20 10:52:07 +00:00
This crate makes extensive use of the `Result` pattern and is intended to never panic.
The *exception* are panics caused by *failed allocations* .
2019-03-20 10:18:25 +00:00
But unfortunately, Rust does not provide any features to prove this behavior.
The developer of this crate has not found a good solution to ensure no-panic behavior in any way.
2019-03-20 13:17:06 +00:00
Please report a panic in this crate immediately as issue on [github ](https://github.com/ISibboI/evalexpr/issues ).
2019-03-20 10:18:25 +00:00
Even if the crate itself is panic free, it allows the user to define custom functions that are executed by the crate.
The user needs to ensure that the function he provides to the crate never panic.
2019-03-19 14:47:17 +00:00
## Closing Notes
If you have any ideas for features or see any problems in the code, architecture, interface, algorithmics or documentation, please open an issue on github.
2019-03-19 14:54:52 +00:00
If there is already an issue describing what you want to say, please add a thumbs up or whatever emoji you think fits to the issue, so I know which ones I should prioritize.