evalexpr/lib.rs
1//!
2//! ## Quickstart
3//!
4//! Add `evalexpr` as dependency to your `Cargo.toml`:
5//!
6//! ```toml
7//! [dependencies]
8//! evalexpr = "<desired version>"
9//! ```
10//!
11//! Then you can use `evalexpr` to **evaluate expressions** like this:
12//!
13//! ```rust
14//! use evalexpr::*;
15//!
16//! assert_eq!(eval("1 + 2 + 3"), Ok(Value::from_int(6)));
17//! // `eval` returns a variant of the `Value` enum,
18//! // while `eval_[type]` returns the respective type directly.
19//! // Both can be used interchangeably.
20//! assert_eq!(eval_int("1 + 2 + 3"), Ok(6));
21//! assert_eq!(eval("1 /* inline comments are supported */ - 2 * 3 // as are end-of-line comments"), Ok(Value::from_int(-5)));
22//! assert_eq!(eval("1.0 + 2 * 3"), Ok(Value::from_float(7.0)));
23//! assert_eq!(eval("true && 4 > 2"), Ok(Value::from(true)));
24//! ```
25//!
26//! You can **chain** expressions and **assign** to variables like this:
27//!
28//! ```rust
29//! use evalexpr::*;
30//!
31//! let mut context = HashMapContext::<DefaultNumericTypes>::new();
32//! // Assign 5 to a like this
33//! assert_eq!(eval_empty_with_context_mut("a = 5", &mut context), Ok(EMPTY_VALUE));
34//! // The HashMapContext is type safe, so this will fail now
35//! assert_eq!(eval_empty_with_context_mut("a = 5.0", &mut context),
36//! Err(EvalexprError::expected_int(Value::from_float(5.0))));
37//! // We can check which value the context stores for a like this
38//! assert_eq!(context.get_value("a"), Some(&Value::from_int(5)));
39//! // And use the value in another expression like this
40//! assert_eq!(eval_int_with_context_mut("a = a + 2; a", &mut context), Ok(7));
41//! // It is also possible to save a bit of typing by using an operator-assignment operator
42//! assert_eq!(eval_int_with_context_mut("a += 2; a", &mut context), Ok(9));
43//! ```
44//!
45//! And you can use **variables** and **functions** in expressions like this:
46//!
47//! ```rust
48//! use evalexpr::*;
49//!
50//! let context: HashMapContext<DefaultNumericTypes> = context_map! {
51//! "five" => int 5,
52//! "twelve" => int 12,
53//! "f" => Function::new(|argument| {
54//! if let Ok(int) = argument.as_int() {
55//! Ok(Value::Int(int / 2))
56//! } else if let Ok(float) = argument.as_float() {
57//! Ok(Value::Float(float / 2.0))
58//! } else {
59//! Err(EvalexprError::expected_number(argument.clone()))
60//! }
61//! }),
62//! "avg" => Function::new(|argument| {
63//! let arguments = argument.as_tuple()?;
64//!
65//! if let (Value::Int(a), Value::Int(b)) = (&arguments[0], &arguments[1]) {
66//! Ok(Value::Int((a + b) / 2))
67//! } else {
68//! Ok(Value::Float((arguments[0].as_number()? + arguments[1].as_number()?) / 2.0))
69//! }
70//! })
71//! }.unwrap(); // Do proper error handling here
72//!
73//! assert_eq!(eval_with_context("five + 8 > f(twelve)", &context), Ok(Value::from(true)));
74//! // `eval_with_context` returns a variant of the `Value` enum,
75//! // while `eval_[type]_with_context` returns the respective type directly.
76//! // Both can be used interchangeably.
77//! assert_eq!(eval_boolean_with_context("five + 8 > f(twelve)", &context), Ok(true));
78//! assert_eq!(eval_with_context("avg(2, 4) == 3", &context), Ok(Value::from(true)));
79//! ```
80//!
81//! You can also **precompile** expressions like this:
82//!
83//! ```rust
84//! use evalexpr::*;
85//!
86//! let precompiled = build_operator_tree::<DefaultNumericTypes>("a * b - c > 5").unwrap(); // Do proper error handling here
87//!
88//! let mut context = context_map! {
89//! "a" => int 6,
90//! "b" => int 2,
91//! "c" => int 3,
92//! }.unwrap(); // Do proper error handling here
93//! assert_eq!(precompiled.eval_with_context(&context), Ok(Value::from(true)));
94//!
95//! context.set_value("c".into(), Value::from_int(8)).unwrap(); // Do proper error handling here
96//! assert_eq!(precompiled.eval_with_context(&context), Ok(Value::from(false)));
97//! // `Node::eval_with_context` returns a variant of the `Value` enum,
98//! // while `Node::eval_[type]_with_context` returns the respective type directly.
99//! // Both can be used interchangeably.
100//! assert_eq!(precompiled.eval_boolean_with_context(&context), Ok(false));
101//! ```
102//!
103//! ## CLI
104//!
105//! While primarily meant to be used as a library, `evalexpr` is also available as a command line tool.
106//! It can be installed and used as follows:
107//!
108//! ```bash
109//! cargo install evalexpr
110//! evalexpr 2 + 3 # outputs `5` to stdout.
111//! ```
112//!
113//! ## Features
114//!
115//! ### Operators
116//!
117//! This crate offers a set of binary and unary operators for building expressions.
118//! Operators have a precedence to determine their order of evaluation, where operators of higher precedence are evaluated first.
119//! The precedence should resemble that of most common programming languages, especially Rust.
120//! Variables and values have a precedence of 200, and function literals have 190.
121//!
122//! Supported binary operators:
123//!
124//! | Operator | Precedence | Description |
125//! |----------|------------|-------------|
126//! | ^ | 120 | Exponentiation |
127//! | * | 100 | Product |
128//! | / | 100 | Division (integer if both arguments are integers, otherwise float) |
129//! | % | 100 | Modulo (integer if both arguments are integers, otherwise float) |
130//! | + | 95 | Sum or String Concatenation |
131//! | - | 95 | Difference |
132//! | < | 80 | Lower than |
133//! | \> | 80 | Greater than |
134//! | <= | 80 | Lower than or equal |
135//! | \>= | 80 | Greater than or equal |
136//! | == | 80 | Equal |
137//! | != | 80 | Not equal |
138//! | && | 75 | Logical and |
139//! | || | 70 | Logical or |
140//! | = | 50 | Assignment |
141//! | += | 50 | Sum-Assignment or String-Concatenation-Assignment |
142//! | -= | 50 | Difference-Assignment |
143//! | *= | 50 | Product-Assignment |
144//! | /= | 50 | Division-Assignment |
145//! | %= | 50 | Modulo-Assignment |
146//! | ^= | 50 | Exponentiation-Assignment |
147//! | &&= | 50 | Logical-And-Assignment |
148//! | ||= | 50 | Logical-Or-Assignment |
149//! | , | 40 | Aggregation |
150//! | ; | 0 | Expression Chaining |
151//!
152//! Supported unary operators:
153//!
154//! | Operator | Precedence | Description |
155//! |----------|------------|-------------|
156//! | - | 110 | Negation |
157//! | ! | 110 | Logical not |
158//!
159//! Operators that take numbers as arguments can either take integers or floating point numbers.
160//! 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.
161//! Otherwise, the result is an integer.
162//! An exception to this is the exponentiation operator that always returns a floating point number.
163//! Example:
164//!
165//! ```rust
166//! use evalexpr::*;
167//!
168//! assert_eq!(eval("1 / 2"), Ok(Value::from_int(0)));
169//! assert_eq!(eval("1.0 / 2"), Ok(Value::from_float(0.5)));
170//! assert_eq!(eval("2^2"), Ok(Value::from_float(4.0)));
171//! ```
172//!
173//! #### The Aggregation Operator
174//!
175//! The aggregation operator aggregates a set of values into a tuple.
176//! A tuple can contain arbitrary values, it is not restricted to a single type.
177//! The operator is n-ary, so it supports creating tuples longer than length two.
178//! Example:
179//!
180//! ```rust
181//! use evalexpr::*;
182//!
183//! assert_eq!(eval("1, \"b\", 3"),
184//! Ok(Value::from(vec![Value::from_int(1), Value::from("b"), Value::from_int(3)])));
185//! ```
186//!
187//! To create nested tuples, use parentheses:
188//!
189//! ```rust
190//! use evalexpr::*;
191//!
192//! assert_eq!(eval("1, 2, (true, \"b\")"), Ok(Value::from(vec![
193//! Value::from_int(1),
194//! Value::from_int(2),
195//! Value::from(vec![
196//! Value::from(true),
197//! Value::from("b")
198//! ])
199//! ])));
200//! ```
201//!
202//! #### The Assignment Operator
203//!
204//! This crate features the assignment operator, that allows expressions to store their result in a variable in the expression context.
205//! If an expression uses the assignment operator, it must be evaluated with a mutable context.
206//!
207//! Note that assignments are type safe when using the `HashMapContext`.
208//! That means that if an identifier is assigned a value of a type once, it cannot be assigned a value of another type.
209//!
210//! ```rust
211//! use evalexpr::*;
212//!
213//! let mut context = HashMapContext::<DefaultNumericTypes>::new();
214//! assert_eq!(eval_with_context("a = 5", &context), Err(EvalexprError::ContextNotMutable));
215//! assert_eq!(eval_empty_with_context_mut("a = 5", &mut context), Ok(EMPTY_VALUE));
216//! assert_eq!(eval_empty_with_context_mut("a = 5.0", &mut context),
217//! Err(EvalexprError::expected_int(Value::from_float(5.0))));
218//! assert_eq!(eval_int_with_context("a", &context), Ok(5));
219//! assert_eq!(context.get_value("a"), Some(Value::from_int(5)).as_ref());
220//! ```
221//!
222//! For each binary operator, there exists an equivalent operator-assignment operator.
223//! Here are some examples:
224//!
225//! ```rust
226//! use evalexpr::*;
227//!
228//! assert_eq!(eval_int("a = 2; a *= 2; a += 2; a"), Ok(6));
229//! assert_eq!(eval_float("a = 2.2; a /= 2.0 / 4 + 1; a"), Ok(2.2 / (2.0 / 4.0 + 1.0)));
230//! assert_eq!(eval_string("a = \"abc\"; a += \"def\"; a"), Ok("abcdef".to_string()));
231//! assert_eq!(eval_boolean("a = true; a &&= false; a"), Ok(false));
232//! ```
233//!
234//! #### The Expression Chaining Operator
235//!
236//! The expression chaining operator works as one would expect from programming languages that use the semicolon to end statements, like `Rust`, `C` or `Java`.
237//! It has the special feature that it returns the value of the last expression in the expression chain.
238//! If the last expression is terminated by a semicolon as well, then `Value::Empty` is returned.
239//! Expression chaining is useful together with assignment to create small scripts.
240//!
241//! ```rust
242//! use evalexpr::*;
243//!
244//! let mut context = HashMapContext::<DefaultNumericTypes>::new();
245//! assert_eq!(eval("1;2;3;4;"), Ok(Value::Empty));
246//! assert_eq!(eval("1;2;3;4"), Ok(Value::from_int(4)));
247//!
248//! // Initialization of variables via script
249//! assert_eq!(eval_empty_with_context_mut("hp = 1; max_hp = 5; heal_amount = 3;", &mut context),
250//! Ok(EMPTY_VALUE));
251//! // Precompile healing script
252//! let healing_script = build_operator_tree("hp = min(hp + heal_amount, max_hp); hp").unwrap(); // Do proper error handling here
253//! // Execute precompiled healing script
254//! assert_eq!(healing_script.eval_int_with_context_mut(&mut context), Ok(4));
255//! assert_eq!(healing_script.eval_int_with_context_mut(&mut context), Ok(5));
256//! ```
257//!
258//! ### Contexts
259//!
260//! An expression evaluator that just evaluates expressions would be useful already, but this crate can do more.
261//! It allows using [*variables*](#variables), [*assignments*](#the-assignment-operator), [*statement chaining*](#the-expression-chaining-operator) and [*user-defined functions*](#user-defined-functions) within an expression.
262//! When assigning to variables, the assignment is stored in a context.
263//! When the variable is read later on, it is read from the context.
264//! Contexts can be preserved between multiple calls to eval by creating them yourself.
265//! Here is a simple example to show the difference between preserving and not preserving context between evaluations:
266//!
267//! ```rust
268//! use evalexpr::*;
269//!
270//! assert_eq!(eval("a = 5;"), Ok(Value::from(())));
271//! // The context is not preserved between eval calls
272//! assert_eq!(eval("a"), Err(EvalexprError::VariableIdentifierNotFound("a".to_string())));
273//!
274//! let mut context = HashMapContext::<DefaultNumericTypes>::new();
275//! assert_eq!(eval_with_context_mut("a = 5;", &mut context), Ok(Value::from(())));
276//! // Assignments require mutable contexts
277//! assert_eq!(eval_with_context("a = 6", &context), Err(EvalexprError::ContextNotMutable));
278//! // The HashMapContext is type safe
279//! assert_eq!(eval_with_context_mut("a = 5.5", &mut context),
280//! Err(EvalexprError::ExpectedInt { actual: Value::from_float(5.5) }));
281//! // Reading a variable does not require a mutable context
282//! assert_eq!(eval_with_context("a", &context), Ok(Value::from_int(5)));
283//!
284//! ```
285//!
286//! Note that the assignment is forgotten between the two calls to eval in the first example.
287//! In the second part, the assignment is correctly preserved.
288//! Note as well that to assign to a variable, the context needs to be passed as a mutable reference.
289//! When passed as an immutable reference, an error is returned.
290//!
291//! Also, the `HashMapContext` is type safe.
292//! This means that assigning to `a` again with a different type yields an error.
293//! Type unsafe contexts may be implemented if requested.
294//! For reading `a`, it is enough to pass an immutable reference.
295//!
296//! Contexts can also be manipulated in code.
297//! Take a look at the following example:
298//!
299//! ```rust
300//! use evalexpr::*;
301//!
302//! let mut context = HashMapContext::<DefaultNumericTypes>::new();
303//! // We can set variables in code like this...
304//! context.set_value("a".into(), Value::from_int(5));
305//! // ...and read from them in expressions
306//! assert_eq!(eval_int_with_context("a", &context), Ok(5));
307//! // We can write or overwrite variables in expressions...
308//! assert_eq!(eval_with_context_mut("a = 10; b = 1.0;", &mut context), Ok(().into()));
309//! // ...and read the value in code like this
310//! assert_eq!(context.get_value("a"), Some(&Value::from_int(10)));
311//! assert_eq!(context.get_value("b"), Some(&Value::from_float(1.0)));
312//! ```
313//!
314//! Contexts are also required for user-defined functions.
315//! Those can be passed one by one with the `set_function` method, but it might be more convenient to use the `context_map!` macro instead:
316//!
317//! ```rust
318//! use evalexpr::*;
319//!
320//! let context: HashMapContext<DefaultNumericTypes> = context_map!{
321//! "f" => Function::new(|args| Ok(Value::from_int(args.as_int()? + 5))),
322//! }.unwrap_or_else(|error| panic!("Error creating context: {}", error));
323//! assert_eq!(eval_int_with_context("f 5", &context), Ok(10));
324//! ```
325//!
326//! For more information about user-defined functions, refer to the respective [section](#user-defined-functions).
327//!
328//! ### Builtin Functions
329//!
330//! This crate offers a set of builtin functions (see below for a full list).
331//! They can be disabled if needed as follows:
332//!
333//! ```rust
334//! use evalexpr::*;
335//! let mut context = HashMapContext::<DefaultNumericTypes>::new();
336//! assert_eq!(eval_with_context("max(1,3)",&context),Ok(Value::from_int(3)));
337//! context.set_builtin_functions_disabled(true).unwrap(); // Do proper error handling here
338//! assert_eq!(eval_with_context("max(1,3)",&context),Err(EvalexprError::FunctionIdentifierNotFound(String::from("max"))));
339//! ```
340//!
341//! Not all contexts support enabling or disabling builtin functions.
342//! Specifically the `EmptyContext` has builtin functions disabled by default, and they cannot be enabled.
343//! Symmetrically, the `EmptyContextWithBuiltinFunctions` has builtin functions enabled by default, and they cannot be disabled.
344//!
345//! | Identifier | Argument Amount | Argument Types | Description |
346//! |----------------------|-----------------|-------------------------------|-------------|
347//! | `min` | >= 1 | Numeric | Returns the minimum of the arguments |
348//! | `max` | >= 1 | Numeric | Returns the maximum of the arguments |
349//! | `len` | 1 | String/Tuple | Returns the character length of a string, or the amount of elements in a tuple (not recursively) |
350//! | `floor` | 1 | Numeric | Returns the largest integer less than or equal to a number |
351//! | `round` | 1 | Numeric | Returns the nearest integer to a number. Rounds half-way cases away from 0.0 |
352//! | `ceil` | 1 | Numeric | Returns the smallest integer greater than or equal to a number |
353//! | `if` | 3 | Boolean, Any, Any | If the first argument is true, returns the second argument, otherwise, returns the third |
354//! | `contains` | 2 | Tuple, any non-tuple | Returns true if second argument exists in first tuple argument. |
355//! | `contains_any` | 2 | Tuple, Tuple of any non-tuple | Returns true if one of the values in the second tuple argument exists in first tuple argument. |
356//! | `typeof` | 1 | Any | returns "string", "float", "int", "boolean", "tuple", or "empty" depending on the type of the argument |
357//! | `math::is_nan` | 1 | Numeric | Returns true if the argument is the floating-point value NaN, false if it is another floating-point value, and throws an error if it is not a number |
358//! | `math::is_finite` | 1 | Numeric | Returns true if the argument is a finite floating-point number, false otherwise |
359//! | `math::is_infinite` | 1 | Numeric | Returns true if the argument is an infinite floating-point number, false otherwise |
360//! | `math::is_normal` | 1 | Numeric | Returns true if the argument is a floating-point number that is neither zero, infinite, [subnormal](https://en.wikipedia.org/wiki/Subnormal_number), or NaN, false otherwise |
361//! | `math::ln` | 1 | Numeric | Returns the natural logarithm of the number |
362//! | `math::log` | 2 | Numeric, Numeric | Returns the logarithm of the number with respect to an arbitrary base |
363//! | `math::log2` | 1 | Numeric | Returns the base 2 logarithm of the number |
364//! | `math::log10` | 1 | Numeric | Returns the base 10 logarithm of the number |
365//! | `math::exp` | 1 | Numeric | Returns `e^(number)`, (the exponential function) |
366//! | `math::exp2` | 1 | Numeric | Returns `2^(number)` |
367//! | `math::pow` | 2 | Numeric, Numeric | Raises a number to the power of the other number |
368//! | `math::cos` | 1 | Numeric | Computes the cosine of a number (in radians) |
369//! | `math::acos` | 1 | Numeric | Computes the arccosine of a number. The return value is in radians in the range [0, pi] or NaN if the number is outside the range [-1, 1] |
370//! | `math::cosh` | 1 | Numeric | Hyperbolic cosine function |
371//! | `math::acosh` | 1 | Numeric | Inverse hyperbolic cosine function |
372//! | `math::sin` | 1 | Numeric | Computes the sine of a number (in radians) |
373//! | `math::asin` | 1 | Numeric | Computes the arcsine of a number. The return value is in radians in the range [-pi/2, pi/2] or NaN if the number is outside the range [-1, 1] |
374//! | `math::sinh` | 1 | Numeric | Hyperbolic sine function |
375//! | `math::asinh` | 1 | Numeric | Inverse hyperbolic sine function |
376//! | `math::tan` | 1 | Numeric | Computes the tangent of a number (in radians) |
377//! | `math::atan` | 1 | Numeric | Computes the arctangent of a number. The return value is in radians in the range [-pi/2, pi/2] |
378//! | `math::atan2` | 2 | Numeric, Numeric | Computes the four quadrant arctangent in radians |
379//! | `math::tanh` | 1 | Numeric | Hyperbolic tangent function |
380//! | `math::atanh` | 1 | Numeric | Inverse hyperbolic tangent function. |
381//! | `math::sqrt` | 1 | Numeric | Returns the square root of a number. Returns NaN for a negative number |
382//! | `math::cbrt` | 1 | Numeric | Returns the cube root of a number |
383//! | `math::hypot` | 2 | Numeric | Calculates the length of the hypotenuse of a right-angle triangle given legs of length given by the two arguments |
384//! | `math::abs` | 1 | Numeric | Returns the absolute value of a number, returning an integer if the argument was an integer, and a float otherwise |
385//! | `str::regex_matches` | 2 | String, String | Returns true if the first argument matches the regex in the second argument (Requires `regex_support` feature flag) |
386//! | `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 (Requires `regex_support` feature flag) |
387//! | `str::to_lowercase` | 1 | String | Returns the lower-case version of the string |
388//! | `str::to_uppercase` | 1 | String | Returns the upper-case version of the string |
389//! | `str::trim` | 1 | String | Strips whitespace from the start and the end of the string |
390//! | `str::from` | >= 0 | Any | Returns passed value as string |
391//! | `str::substring` | 3 | String, Int, Int | Returns a substring of the first argument, starting at the second argument and ending at the third argument. If the last argument is omitted, the substring extends to the end of the string |
392//! | `bitand` | 2 | Int | Computes the bitwise and of the given integers |
393//! | `bitor` | 2 | Int | Computes the bitwise or of the given integers |
394//! | `bitxor` | 2 | Int | Computes the bitwise xor of the given integers |
395//! | `bitnot` | 1 | Int | Computes the bitwise not of the given integer |
396//! | `shl` | 2 | Int | Computes the given integer bitwise shifted left by the other given integer |
397//! | `shr` | 2 | Int | Computes the given integer bitwise shifted right by the other given integer |
398//! | `random` | 0 | Empty | Return a random float between 0 and 1. Requires the `rand` feature flag. |
399//!
400//! The `min` and `max` functions can deal with a mixture of integer and floating point arguments.
401//! If the maximum or minimum is an integer, then an integer is returned.
402//! Otherwise, a float is returned.
403//!
404//! The regex functions require the feature flag `regex_support`.
405//!
406//! ### Values
407//!
408//! Operators take values as arguments and produce values as results.
409//! Values can be booleans, integer or floating point numbers, strings, tuples or the empty type.
410//! Values are denoted as displayed in the following table.
411//!
412//! | Value type | Example |
413//! |------------|---------|
414//! | `Value::String` | `"abc"`, `""`, `"a\"b\\c"` |
415//! | `Value::Boolean` | `true`, `false` |
416//! | `Value::Int` | `3`, `-9`, `0`, `135412`, `0xfe02`, `-0x1e` |
417//! | `Value::Float` | `3.`, `.35`, `1.00`, `0.5`, `123.554`, `23e4`, `-2e-3`, `3.54e+2` |
418//! | `Value::Tuple` | `(3, 55.0, false, ())`, `(1, 2)` |
419//! | `Value::Empty` | `()` |
420//!
421//! By default, integers are internally represented as `i64`, and floating point numbers are represented as `f64`.
422//! The numeric types are defined by the `Context` trait and can for example be customised by implementing a custom context.
423//! Alternatively, for example the standard `HashMapContext` type takes the numeric types as type parameters, so it works with arbitrary numeric types.
424//! Tuples are represented as `Vec<Value>` and empty values are not stored, but represented by Rust's unit type `()` where necessary.
425//!
426//! There exist type aliases for some of the types.
427//! They include `IntType`, `FloatType`, `TupleType` and `EmptyType`.
428//!
429//! Values can be constructed either directly or using `from` functions.
430//! For integers and floats, the `from` functions are `from_int` and `from_float`, and all others use the `From` trait.
431//! See the examples below for further details.
432//! Values can also be decomposed using the `Value::as_[type]` methods.
433//! The type of a value can be checked using the `Value::is_[type]` methods.
434//!
435//! **Examples for constructing a value:**
436//!
437//! | Code | Result |
438//! |------|--------|
439//! | `Value::from_int(4)` | `Value::Int(4)` |
440//! | `Value::from_float(4.4)` | `Value::Float(4.4)` |
441//! | `Value::from(true)` | `Value::Boolean(true)` |
442//! | `Value::from(vec![Value::from_int(3)])` | `Value::Tuple(vec![Value::Int(3)])` |
443//!
444//! **Examples for deconstructing a value:**
445//!
446//! | Code | Result |
447//! |------|--------|
448//! | `Value::from_int(4).as_int()` | `Ok(4)` |
449//! | `Value::from_float(4.4).as_float()` | `Ok(4.4)` |
450//! | `Value::from(true).as_int()` | `Err(Error::ExpectedInt {actual: Value::Boolean(true)})` |
451//!
452//! Values have a precedence of 200.
453//!
454//! ### Variables
455//!
456//! This crate allows to compile parameterizable formulas by using variables.
457//! A variable is a literal in the formula, that does not contain whitespace or can be parsed as value.
458//! For working with variables, a [context](#contexts) is required.
459//! It stores the mappings from variables to their values.
460//!
461//! Variables do not have fixed types in the expression itself, but are typed by the context.
462//! Once a variable is assigned a value of a specific type, it cannot be assigned a value of another type.
463//! This might change in the future and can be changed by using a type-unsafe context (not provided by this crate as of now).
464//!
465//! Here are some examples and counter-examples on expressions that are interpreted as variables:
466//!
467//! | Expression | Variable? | Explanation |
468//! |------------|--------|-------------|
469//! | `a` | yes | |
470//! | `abc` | yes | |
471//! | `a<b` | no | Expression is interpreted as variable `a`, operator `<` and variable `b` |
472//! | `a b` | no | Expression is interpreted as function `a` applied to argument `b` |
473//! | `123` | no | Expression is interpreted as `Value::Int` |
474//! | `true` | no | Expression is interpreted as `Value::Bool` |
475//! | `.34` | no | Expression is interpreted as `Value::Float` |
476//!
477//! Variables have a precedence of 200.
478//!
479//! ### User-Defined Functions
480//!
481//! This crate allows to define arbitrary functions to be used in parsed expressions.
482//! A function is defined as a `Function` instance, wrapping an `fn(&Value) -> EvalexprResult<Value>`.
483//! The definition needs to be included in the [`Context`](#contexts) that is used for evaluation.
484//! As of now, functions cannot be defined within the expression, but that might change in the future.
485//!
486//! The function gets passed what ever value is directly behind it, be it a tuple or a single values.
487//! If there is no value behind a function, it is interpreted as a variable instead.
488//! More specifically, a function needs to be followed by either an opening brace `(`, another literal, or a value.
489//! While not including special support for multi-valued functions, they can be realized by requiring a single tuple argument.
490//!
491//! Be aware that functions need to verify the types of values that are passed to them.
492//! The `error` module contains some shortcuts for verification, and error types for passing a wrong value type.
493//! Also, most numeric functions need to distinguish between being called with integers or floating point numbers, and act accordingly.
494//!
495//! Here are some examples and counter-examples on expressions that are interpreted as function calls:
496//!
497//! | Expression | Function? | Explanation |
498//! |------------|--------|-------------|
499//! | `a v` | yes | |
500//! | `x 5.5` | yes | |
501//! | `a (3, true)` | yes | |
502//! | `a b 4` | yes | Call `a` with the result of calling `b` with `4` |
503//! | `5 b` | no | Error, value cannot be followed by a literal |
504//! | `12 3` | no | Error, value cannot be followed by a value |
505//! | `a 5 6` | no | Error, function call cannot be followed by a value |
506//!
507//! Functions have a precedence of 190.
508//!
509//! ### Comments
510//!
511//! Evalexpr supports C-style inline comments and end-of-line comments.
512//! Inline comments are started with a `/*` and terminated with a `*/`.
513//! End-of-line comments are started with a `//` and terminated with a newline character.
514//! For example:
515//!
516//! ```rust
517//! use evalexpr::*;
518//!
519//! assert_eq!(
520//! eval(
521//! "
522//! // input
523//! a = 1; // assignment
524//! // output
525//! 2 * a /* first double a */ + 2 // then add 2"
526//! ),
527//! Ok(Value::Int(4))
528//! );
529//! ```
530//!
531//! ### [Serde](https://serde.rs)
532//!
533//! To use this crate with serde, the `serde_support` feature flag has to be set.
534//! This can be done like this in the `Cargo.toml`:
535//!
536//! ```toml
537//! [dependencies]
538//! evalexpr = {version = "<desired version>", features = ["serde_support"]}
539//! ```
540//!
541//! This crate implements `serde::de::Deserialize` for its type `Node` that represents a parsed expression tree.
542//! The implementation expects a [serde `string`](https://serde.rs/data-model.html) as input.
543//! Example parsing with [ron format](https://docs.rs/ron):
544//!
545//! ```rust
546//! # #[cfg(feature = "serde_support")] {
547//! extern crate ron;
548//! use evalexpr::*;
549//!
550//! let mut context = context_map!{
551//! "five" => 5
552//! }.unwrap(); // Do proper error handling here
553//!
554//! // In ron format, strings are surrounded by "
555//! let serialized_free = "\"five * five\"";
556//! match ron::de::from_str::<Node>(serialized_free) {
557//! Ok(free) => assert_eq!(free.eval_with_context(&context), Ok(Value::from_int(25))),
558//! Err(error) => {
559//! () // Handle error
560//! }
561//! }
562//! # }
563//! ```
564//!
565//! With `serde`, expressions can be integrated into arbitrarily complex data.
566//!
567//! The crate also implements `Serialize` and `Deserialize` for the `HashMapContext`,
568//! but note that only the variables get (de)serialized, not the functions.
569//!
570//! ## Licensing
571//!
572//! This crate is primarily distributed under the terms of the AGPL3 license.
573//! See [LICENSE](/LICENSE) for details.
574//! If you require a different licensing option for your project, contact me at `isibboi at gmail.com`.
575//!
576//! Contributions to this crate are assumed to be licensed under the [MIT License](https://opensource.org/license/mit).
577//!
578
579#![deny(missing_docs)]
580#![forbid(unsafe_code)]
581#![allow(clippy::get_first)]
582
583pub use crate::{
584 context::{
585 Context, ContextWithMutableFunctions, ContextWithMutableVariables, EmptyContext,
586 EmptyContextWithBuiltinFunctions, HashMapContext, IterateVariablesContext,
587 },
588 error::{EvalexprError, EvalexprResult},
589 function::Function,
590 interface::*,
591 operator::Operator,
592 token::PartialToken,
593 tree::Node,
594 value::{
595 numeric_types::{
596 default_numeric_types::DefaultNumericTypes, EvalexprFloat, EvalexprInt,
597 EvalexprNumericTypes,
598 },
599 value_type::ValueType,
600 EmptyType, TupleType, Value, EMPTY_VALUE,
601 },
602};
603
604mod context;
605pub mod error;
606#[cfg(feature = "serde")]
607mod feature_serde;
608mod function;
609mod interface;
610mod operator;
611mod token;
612mod tree;
613mod value;
614
615// Exports