{"id":16287838,"url":"https://github.com/isibboi/evalexpr","last_synced_at":"2025-05-14T07:10:49.287Z","repository":{"id":41677471,"uuid":"176485437","full_name":"ISibboI/evalexpr","owner":"ISibboI","description":"A powerful expression evaluation crate 🦀.","archived":false,"fork":false,"pushed_at":"2024-12-29T10:21:27.000Z","size":647,"stargazers_count":354,"open_issues_count":48,"forks_count":57,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-22T11:42:16.309Z","etag":null,"topics":["expression-evaluator","rust"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"agpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ISibboI.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-03-19T10:23:13.000Z","updated_at":"2025-04-16T14:43:16.000Z","dependencies_parsed_at":"2024-06-18T21:25:44.720Z","dependency_job_id":"a775c936-f62a-4d25-b6eb-d0cfb185bb29","html_url":"https://github.com/ISibboI/evalexpr","commit_stats":{"total_commits":466,"total_committers":16,"mean_commits":29.125,"dds":0.1566523605150214,"last_synced_commit":"f2263bd21853892fa3cebecdde1304998b27ba6f"},"previous_names":[],"tags_count":65,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ISibboI%2Fevalexpr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ISibboI%2Fevalexpr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ISibboI%2Fevalexpr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ISibboI%2Fevalexpr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ISibboI","download_url":"https://codeload.github.com/ISibboI/evalexpr/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254092798,"owners_count":22013292,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["expression-evaluator","rust"],"created_at":"2024-10-10T19:46:27.351Z","updated_at":"2025-05-14T07:10:44.277Z","avatar_url":"https://github.com/ISibboI.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# evalexpr\n\n[![Version](https://img.shields.io/crates/v/evalexpr.svg)](https://crates.io/crates/evalexpr)\n[![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0)\n[![Downloads](https://img.shields.io/crates/d/evalexpr.svg)](https://crates.io/crates/evalexpr)\n[![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)\n[![Coverage Status](https://coveralls.io/repos/github/ISibboI/evalexpr/badge.svg?branch=main)](https://coveralls.io/github/ISibboI/evalexpr?branch=main)\n[![](http://meritbadge.herokuapp.com/evalexpr)](https://crates.io/crates/evalexpr)\n[![](https://docs.rs/evalexpr/badge.svg)](https://docs.rs/evalexpr)\n\nEvalexpr is an expression evaluator and tiny scripting language in Rust.\nIt has a small and easy to use interface and can be easily integrated into any application.\nIt is very lightweight and comes with no further dependencies.\nEvalexpr is [available on crates.io](https://crates.io/crates/evalexpr), and its [API Documentation is available on docs.rs](https://docs.rs/evalexpr).\n\n\n**Minimum Supported Rust Version:** 1.65.0\n\n\u003c!-- cargo-sync-readme start --\u003e\n\n\n## Quickstart\n\nAdd `evalexpr` as dependency to your `Cargo.toml`:\n\n```toml\n[dependencies]\nevalexpr = \"\u003cdesired version\u003e\"\n```\n\nThen you can use `evalexpr` to **evaluate expressions** like this:\n\n```rust\nuse evalexpr::*;\n\nassert_eq!(eval(\"1 + 2 + 3\"), Ok(Value::from_int(6)));\n// `eval` returns a variant of the `Value` enum,\n// while `eval_[type]` returns the respective type directly.\n// Both can be used interchangeably.\nassert_eq!(eval_int(\"1 + 2 + 3\"), Ok(6));\nassert_eq!(eval(\"1 /* inline comments are supported */ - 2 * 3 // as are end-of-line comments\"), Ok(Value::from_int(-5)));\nassert_eq!(eval(\"1.0 + 2 * 3\"), Ok(Value::from_float(7.0)));\nassert_eq!(eval(\"true \u0026\u0026 4 \u003e 2\"), Ok(Value::from(true)));\n```\n\nYou can **chain** expressions and **assign** to variables like this:\n\n```rust\nuse evalexpr::*;\n\nlet mut context = HashMapContext::\u003cDefaultNumericTypes\u003e::new();\n// Assign 5 to a like this\nassert_eq!(eval_empty_with_context_mut(\"a = 5\", \u0026mut context), Ok(EMPTY_VALUE));\n// The HashMapContext is type safe, so this will fail now\nassert_eq!(eval_empty_with_context_mut(\"a = 5.0\", \u0026mut context),\n           Err(EvalexprError::expected_int(Value::from_float(5.0))));\n// We can check which value the context stores for a like this\nassert_eq!(context.get_value(\"a\"), Some(\u0026Value::from_int(5)));\n// And use the value in another expression like this\nassert_eq!(eval_int_with_context_mut(\"a = a + 2; a\", \u0026mut context), Ok(7));\n// It is also possible to save a bit of typing by using an operator-assignment operator\nassert_eq!(eval_int_with_context_mut(\"a += 2; a\", \u0026mut context), Ok(9));\n```\n\nAnd you can use **variables** and **functions** in expressions like this:\n\n```rust\nuse evalexpr::*;\n\nlet context: HashMapContext\u003cDefaultNumericTypes\u003e = context_map! {\n    \"five\" =\u003e int 5,\n    \"twelve\" =\u003e int 12,\n    \"f\" =\u003e Function::new(|argument| {\n        if let Ok(int) = argument.as_int() {\n            Ok(Value::Int(int / 2))\n        } else if let Ok(float) = argument.as_float() {\n            Ok(Value::Float(float / 2.0))\n        } else {\n            Err(EvalexprError::expected_number(argument.clone()))\n        }\n    }),\n    \"avg\" =\u003e Function::new(|argument| {\n        let arguments = argument.as_tuple()?;\n\n        if let (Value::Int(a), Value::Int(b)) = (\u0026arguments[0], \u0026arguments[1]) {\n            Ok(Value::Int((a + b) / 2))\n        } else {\n            Ok(Value::Float((arguments[0].as_number()? + arguments[1].as_number()?) / 2.0))\n        }\n    })\n}.unwrap(); // Do proper error handling here\n\nassert_eq!(eval_with_context(\"five + 8 \u003e f(twelve)\", \u0026context), Ok(Value::from(true)));\n// `eval_with_context` returns a variant of the `Value` enum,\n// while `eval_[type]_with_context` returns the respective type directly.\n// Both can be used interchangeably.\nassert_eq!(eval_boolean_with_context(\"five + 8 \u003e f(twelve)\", \u0026context), Ok(true));\nassert_eq!(eval_with_context(\"avg(2, 4) == 3\", \u0026context), Ok(Value::from(true)));\n```\n\nYou can also **precompile** expressions like this:\n\n```rust\nuse evalexpr::*;\n\nlet precompiled = build_operator_tree::\u003cDefaultNumericTypes\u003e(\"a * b - c \u003e 5\").unwrap(); // Do proper error handling here\n\nlet mut context = context_map! {\n    \"a\" =\u003e int 6,\n    \"b\" =\u003e int 2,\n    \"c\" =\u003e int 3,\n}.unwrap(); // Do proper error handling here\nassert_eq!(precompiled.eval_with_context(\u0026context), Ok(Value::from(true)));\n\ncontext.set_value(\"c\".into(), Value::from_int(8)).unwrap(); // Do proper error handling here\nassert_eq!(precompiled.eval_with_context(\u0026context), Ok(Value::from(false)));\n// `Node::eval_with_context` returns a variant of the `Value` enum,\n// while `Node::eval_[type]_with_context` returns the respective type directly.\n// Both can be used interchangeably.\nassert_eq!(precompiled.eval_boolean_with_context(\u0026context), Ok(false));\n```\n\n## CLI\n\nWhile primarily meant to be used as a library, `evalexpr` is also available as a command line tool.\nIt can be installed and used as follows:\n\n```bash\ncargo install evalexpr\nevalexpr 2 + 3 # outputs `5` to stdout.\n```\n\n## Features\n\n### Operators\n\nThis crate offers a set of binary and unary operators for building expressions.\nOperators have a precedence to determine their order of evaluation, where operators of higher precedence are evaluated first.\nThe precedence should resemble that of most common programming languages, especially Rust.\nVariables and values have a precedence of 200, and function literals have 190.\n\nSupported binary operators:\n\n| Operator | Precedence | Description |\n|----------|------------|-------------|\n| ^ | 120 | Exponentiation |\n| * | 100 | Product |\n| / | 100 | Division (integer if both arguments are integers, otherwise float) |\n| % | 100 | Modulo (integer if both arguments are integers, otherwise float) |\n| + | 95 | Sum or String Concatenation |\n| - | 95 | Difference |\n| \u003c | 80 | Lower than |\n| \\\u003e | 80 | Greater than |\n| \u003c= | 80 | Lower than or equal |\n| \\\u003e= | 80 | Greater than or equal |\n| == | 80 | Equal |\n| != | 80 | Not equal |\n| \u0026\u0026 | 75 | Logical and |\n| \u0026#124;\u0026#124; | 70 | Logical or |\n| = | 50 | Assignment |\n| += | 50 | Sum-Assignment or String-Concatenation-Assignment |\n| -= | 50 | Difference-Assignment |\n| *= | 50 | Product-Assignment |\n| /= | 50 | Division-Assignment |\n| %= | 50 | Modulo-Assignment |\n| ^= | 50 | Exponentiation-Assignment |\n| \u0026\u0026= | 50 | Logical-And-Assignment |\n| \u0026#124;\u0026#124;= | 50 | Logical-Or-Assignment |\n| , | 40 | Aggregation |\n| ; | 0 | Expression Chaining |\n\nSupported unary operators:\n\n| Operator | Precedence | Description |\n|----------|------------|-------------|\n| - | 110 | Negation |\n| ! | 110 | Logical not |\n\nOperators that take numbers as arguments can either take integers or floating point numbers.\nIf 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.\nOtherwise, the result is an integer.\nAn exception to this is the exponentiation operator that always returns a floating point number.\nExample:\n\n```rust\nuse evalexpr::*;\n\nassert_eq!(eval(\"1 / 2\"), Ok(Value::from_int(0)));\nassert_eq!(eval(\"1.0 / 2\"), Ok(Value::from_float(0.5)));\nassert_eq!(eval(\"2^2\"), Ok(Value::from_float(4.0)));\n```\n\n#### The Aggregation Operator\n\nThe aggregation operator aggregates a set of values into a tuple.\nA tuple can contain arbitrary values, it is not restricted to a single type.\nThe operator is n-ary, so it supports creating tuples longer than length two.\nExample:\n\n```rust\nuse evalexpr::*;\n\nassert_eq!(eval(\"1, \\\"b\\\", 3\"),\n           Ok(Value::from(vec![Value::from_int(1), Value::from(\"b\"), Value::from_int(3)])));\n```\n\nTo create nested tuples, use parentheses:\n\n```rust\nuse evalexpr::*;\n\nassert_eq!(eval(\"1, 2, (true, \\\"b\\\")\"), Ok(Value::from(vec![\n    Value::from_int(1),\n    Value::from_int(2),\n    Value::from(vec![\n        Value::from(true),\n        Value::from(\"b\")\n    ])\n])));\n```\n\n#### The Assignment Operator\n\nThis crate features the assignment operator, that allows expressions to store their result in a variable in the expression context.\nIf an expression uses the assignment operator, it must be evaluated with a mutable context.\n\nNote that assignments are type safe when using the `HashMapContext`.\nThat means that if an identifier is assigned a value of a type once, it cannot be assigned a value of another type.\n\n```rust\nuse evalexpr::*;\n\nlet mut context = HashMapContext::\u003cDefaultNumericTypes\u003e::new();\nassert_eq!(eval_with_context(\"a = 5\", \u0026context), Err(EvalexprError::ContextNotMutable));\nassert_eq!(eval_empty_with_context_mut(\"a = 5\", \u0026mut context), Ok(EMPTY_VALUE));\nassert_eq!(eval_empty_with_context_mut(\"a = 5.0\", \u0026mut context),\n           Err(EvalexprError::expected_int(Value::from_float(5.0))));\nassert_eq!(eval_int_with_context(\"a\", \u0026context), Ok(5));\nassert_eq!(context.get_value(\"a\"), Some(Value::from_int(5)).as_ref());\n```\n\nFor each binary operator, there exists an equivalent operator-assignment operator.\nHere are some examples:\n\n```rust\nuse evalexpr::*;\n\nassert_eq!(eval_int(\"a = 2; a *= 2; a += 2; a\"), Ok(6));\nassert_eq!(eval_float(\"a = 2.2; a /= 2.0 / 4 + 1; a\"), Ok(2.2 / (2.0 / 4.0 + 1.0)));\nassert_eq!(eval_string(\"a = \\\"abc\\\"; a += \\\"def\\\"; a\"), Ok(\"abcdef\".to_string()));\nassert_eq!(eval_boolean(\"a = true; a \u0026\u0026= false; a\"), Ok(false));\n```\n\n#### The Expression Chaining Operator\n\nThe expression chaining operator works as one would expect from programming languages that use the semicolon to end statements, like `Rust`, `C` or `Java`.\nIt has the special feature that it returns the value of the last expression in the expression chain.\nIf the last expression is terminated by a semicolon as well, then `Value::Empty` is returned.\nExpression chaining is useful together with assignment to create small scripts.\n\n```rust\nuse evalexpr::*;\n\nlet mut context = HashMapContext::\u003cDefaultNumericTypes\u003e::new();\nassert_eq!(eval(\"1;2;3;4;\"), Ok(Value::Empty));\nassert_eq!(eval(\"1;2;3;4\"), Ok(Value::from_int(4)));\n\n// Initialization of variables via script\nassert_eq!(eval_empty_with_context_mut(\"hp = 1; max_hp = 5; heal_amount = 3;\", \u0026mut context),\n           Ok(EMPTY_VALUE));\n// Precompile healing script\nlet healing_script = build_operator_tree(\"hp = min(hp + heal_amount, max_hp); hp\").unwrap(); // Do proper error handling here\n// Execute precompiled healing script\nassert_eq!(healing_script.eval_int_with_context_mut(\u0026mut context), Ok(4));\nassert_eq!(healing_script.eval_int_with_context_mut(\u0026mut context), Ok(5));\n```\n\n### Contexts\n\nAn expression evaluator that just evaluates expressions would be useful already, but this crate can do more.\nIt allows using [variables](#variables), [assignments](#the-assignment-operator), [statement chaining](#the-expression-chaining-operator) and [user-defined functions](#user-defined-functions) within an expression.\nWhen assigning to variables, the assignment is stored in a context.\nWhen the variable is read later on, it is read from the context.\nContexts can be preserved between multiple calls to eval by creating them yourself.\nHere is a simple example to show the difference between preserving and not preserving context between evaluations:\n\n```rust\nuse evalexpr::*;\n\nassert_eq!(eval(\"a = 5;\"), Ok(Value::from(())));\n// The context is not preserved between eval calls\nassert_eq!(eval(\"a\"), Err(EvalexprError::VariableIdentifierNotFound(\"a\".to_string())));\n\nlet mut context = HashMapContext::\u003cDefaultNumericTypes\u003e::new();\nassert_eq!(eval_with_context_mut(\"a = 5;\", \u0026mut context), Ok(Value::from(())));\n// Assignments require mutable contexts\nassert_eq!(eval_with_context(\"a = 6\", \u0026context), Err(EvalexprError::ContextNotMutable));\n// The HashMapContext is type safe\nassert_eq!(eval_with_context_mut(\"a = 5.5\", \u0026mut context),\n           Err(EvalexprError::ExpectedInt { actual: Value::from_float(5.5) }));\n// Reading a variable does not require a mutable context\nassert_eq!(eval_with_context(\"a\", \u0026context), Ok(Value::from_int(5)));\n\n```\n\nNote that the assignment is forgotten between the two calls to eval in the first example.\nIn the second part, the assignment is correctly preserved.\nNote as well that to assign to a variable, the context needs to be passed as a mutable reference.\nWhen passed as an immutable reference, an error is returned.\n\nAlso, the `HashMapContext` is type safe.\nThis means that assigning to `a` again with a different type yields an error.\nType unsafe contexts may be implemented if requested.\nFor reading `a`, it is enough to pass an immutable reference.\n\nContexts can also be manipulated in code.\nTake a look at the following example:\n\n```rust\nuse evalexpr::*;\n\nlet mut context = HashMapContext::\u003cDefaultNumericTypes\u003e::new();\n// We can set variables in code like this...\ncontext.set_value(\"a\".into(), Value::from_int(5));\n// ...and read from them in expressions\nassert_eq!(eval_int_with_context(\"a\", \u0026context), Ok(5));\n// We can write or overwrite variables in expressions...\nassert_eq!(eval_with_context_mut(\"a = 10; b = 1.0;\", \u0026mut context), Ok(().into()));\n// ...and read the value in code like this\nassert_eq!(context.get_value(\"a\"), Some(\u0026Value::from_int(10)));\nassert_eq!(context.get_value(\"b\"), Some(\u0026Value::from_float(1.0)));\n```\n\nContexts are also required for user-defined functions.\nThose can be passed one by one with the `set_function` method, but it might be more convenient to use the `context_map!` macro instead:\n\n```rust\nuse evalexpr::*;\n\nlet context: HashMapContext\u003cDefaultNumericTypes\u003e = context_map!{\n    \"f\" =\u003e Function::new(|args| Ok(Value::from_int(args.as_int()? + 5))),\n}.unwrap_or_else(|error| panic!(\"Error creating context: {}\", error));\nassert_eq!(eval_int_with_context(\"f 5\", \u0026context), Ok(10));\n```\n\nFor more information about user-defined functions, refer to the respective [section](#user-defined-functions).\n\n### Builtin Functions\n\nThis crate offers a set of builtin functions (see below for a full list).\nThey can be disabled if needed as follows:\n\n```rust\nuse evalexpr::*;\nlet mut context = HashMapContext::\u003cDefaultNumericTypes\u003e::new();\nassert_eq!(eval_with_context(\"max(1,3)\",\u0026context),Ok(Value::from_int(3)));\ncontext.set_builtin_functions_disabled(true).unwrap(); // Do proper error handling here\nassert_eq!(eval_with_context(\"max(1,3)\",\u0026context),Err(EvalexprError::FunctionIdentifierNotFound(String::from(\"max\"))));\n```\n\nNot all contexts support enabling or disabling builtin functions.\nSpecifically the `EmptyContext` has builtin functions disabled by default, and they cannot be enabled.\nSymmetrically, the `EmptyContextWithBuiltinFunctions` has builtin functions enabled by default, and they cannot be disabled.\n\n| Identifier           | Argument Amount | Argument Types                | Description |\n|----------------------|-----------------|-------------------------------|-------------|\n| `min`                | \u003e= 1            | Numeric                       | Returns the minimum of the arguments |\n| `max`                | \u003e= 1            | Numeric                       | Returns the maximum of the arguments |\n| `len`                | 1               | String/Tuple                  | Returns the character length of a string, or the amount of elements in a tuple (not recursively) |\n| `floor`              | 1               | Numeric                       | Returns the largest integer less than or equal to a number |\n| `round`              | 1               | Numeric                       | Returns the nearest integer to a number. Rounds half-way cases away from 0.0 |\n| `ceil`               | 1               | Numeric                       | Returns the smallest integer greater than or equal to a number |\n| `if`                 | 3               | Boolean, Any, Any             | If the first argument is true, returns the second argument, otherwise, returns the third  |\n| `contains`           | 2               | Tuple, any non-tuple          | Returns true if second argument exists in first tuple argument. |\n| `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. |\n| `typeof`             | 1               | Any                           | returns \"string\", \"float\", \"int\", \"boolean\", \"tuple\", or \"empty\" depending on the type of the argument  |\n| `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  |\n| `math::is_finite`    | 1               | Numeric                       | Returns true if the argument is a finite floating-point number, false otherwise  |\n| `math::is_infinite`  | 1               | Numeric                       | Returns true if the argument is an infinite floating-point number, false otherwise  |\n| `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  |\n| `math::ln`           | 1               | Numeric                       | Returns the natural logarithm of the number |\n| `math::log`          | 2               | Numeric, Numeric              | Returns the logarithm of the number with respect to an arbitrary base |\n| `math::log2`         | 1               | Numeric                       | Returns the base 2 logarithm of the number |\n| `math::log10`        | 1               | Numeric                       | Returns the base 10 logarithm of the number |\n| `math::exp`          | 1               | Numeric                       | Returns `e^(number)`, (the exponential function) |\n| `math::exp2`         | 1               | Numeric                       | Returns `2^(number)` |\n| `math::pow`          | 2               | Numeric, Numeric              | Raises a number to the power of the other number |\n| `math::cos`          | 1               | Numeric                       | Computes the cosine of a number (in radians) |\n| `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] |\n| `math::cosh`         | 1               | Numeric                       | Hyperbolic cosine function |\n| `math::acosh`        | 1               | Numeric                       | Inverse hyperbolic cosine function |\n| `math::sin`          | 1               | Numeric                       | Computes the sine of a number (in radians) |\n| `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] |\n| `math::sinh`         | 1               | Numeric                       | Hyperbolic sine function |\n| `math::asinh`        | 1               | Numeric                       | Inverse hyperbolic sine function |\n| `math::tan`          | 1               | Numeric                       | Computes the tangent of a number (in radians) |\n| `math::atan`         | 1               | Numeric                       | Computes the arctangent of a number. The return value is in radians in the range [-pi/2, pi/2] |\n| `math::atan2`        | 2               | Numeric, Numeric              | Computes the four quadrant arctangent in radians |\n| `math::tanh`         | 1               | Numeric                       | Hyperbolic tangent function |\n| `math::atanh`        | 1               | Numeric                       | Inverse hyperbolic tangent function. |\n| `math::sqrt`         | 1               | Numeric                       | Returns the square root of a number. Returns NaN for a negative number |\n| `math::cbrt`         | 1               | Numeric                       | Returns the cube root of a number |\n| `math::hypot`        | 2               | Numeric                       | Calculates the length of the hypotenuse of a right-angle triangle given legs of length given by the two arguments |\n| `math::abs`          | 1               | Numeric                       | Returns the absolute value of a number, returning an integer if the argument was an integer, and a float otherwise |\n| `str::regex_matches` | 2               | String, String                | Returns true if the first argument matches the regex in the second argument (Requires `regex_support` feature flag) |\n| `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) |\n| `str::to_lowercase`  | 1               | String                        | Returns the lower-case version of the string |\n| `str::to_uppercase`  | 1               | String                        | Returns the upper-case version of the string |\n| `str::trim`          | 1               | String                        | Strips whitespace from the start and the end of the string |\n| `str::from`          | \u003e= 0            | Any                           | Returns passed value as string |\n| `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 |\n| `bitand`             | 2               | Int                           | Computes the bitwise and of the given integers |\n| `bitor`              | 2               | Int                           | Computes the bitwise or of the given integers |\n| `bitxor`             | 2               | Int                           | Computes the bitwise xor of the given integers |\n| `bitnot`             | 1               | Int                           | Computes the bitwise not of the given integer |\n| `shl`                | 2               | Int                           | Computes the given integer bitwise shifted left by the other given integer |\n| `shr`                | 2               | Int                           | Computes the given integer bitwise shifted right by the other given integer |\n| `random`             | 0               | Empty                         | Return a random float between 0 and 1. Requires the `rand` feature flag. |\n\nThe `min` and `max` functions can deal with a mixture of integer and floating point arguments.\nIf the maximum or minimum is an integer, then an integer is returned.\nOtherwise, a float is returned.\n\nThe regex functions require the feature flag `regex_support`.\n\n### Values\n\nOperators take values as arguments and produce values as results.\nValues can be booleans, integer or floating point numbers, strings, tuples or the empty type.\nValues are denoted as displayed in the following table.\n\n| Value type | Example |\n|------------|---------|\n| `Value::String` | `\"abc\"`, `\"\"`, `\"a\\\"b\\\\c\"` |\n| `Value::Boolean` | `true`, `false` |\n| `Value::Int` | `3`, `-9`, `0`, `135412`, `0xfe02`, `-0x1e` |\n| `Value::Float` | `3.`, `.35`, `1.00`, `0.5`, `123.554`, `23e4`, `-2e-3`, `3.54e+2` |\n| `Value::Tuple` | `(3, 55.0, false, ())`, `(1, 2)` |\n| `Value::Empty` | `()` |\n\nBy default, integers are internally represented as `i64`, and floating point numbers are represented as `f64`.\nThe numeric types are defined by the `Context` trait and can for example be customised by implementing a custom context.\nAlternatively, for example the standard `HashMapContext` type takes the numeric types as type parameters, so it works with arbitrary numeric types.\nTuples are represented as `Vec\u003cValue\u003e` and empty values are not stored, but represented by Rust's unit type `()` where necessary.\n\nThere exist type aliases for some of the types.\nThey include `IntType`, `FloatType`, `TupleType` and `EmptyType`.\n\nValues can be constructed either directly or using `from` functions.\nFor integers and floats, the `from` functions are `from_int` and `from_float`, and all others use the `From` trait.\nSee the examples below for further details.\nValues can also be decomposed using the `Value::as_[type]` methods.\nThe type of a value can be checked using the `Value::is_[type]` methods.\n\n**Examples for constructing a value:**\n\n| Code | Result |\n|------|--------|\n| `Value::from_int(4)` | `Value::Int(4)` |\n| `Value::from_float(4.4)` | `Value::Float(4.4)` |\n| `Value::from(true)` | `Value::Boolean(true)` |\n| `Value::from(vec![Value::from_int(3)])` | `Value::Tuple(vec![Value::Int(3)])` |\n\n**Examples for deconstructing a value:**\n\n| Code | Result |\n|------|--------|\n| `Value::from_int(4).as_int()` | `Ok(4)` |\n| `Value::from_float(4.4).as_float()` | `Ok(4.4)` |\n| `Value::from(true).as_int()` | `Err(Error::ExpectedInt {actual: Value::Boolean(true)})` |\n\nValues have a precedence of 200.\n\n### Variables\n\nThis crate allows to compile parameterizable formulas by using variables.\nA variable is a literal in the formula, that does not contain whitespace or can be parsed as value.\nFor working with variables, a [context](#contexts) is required.\nIt stores the mappings from variables to their values.\n\nVariables do not have fixed types in the expression itself, but are typed by the context.\nOnce a variable is assigned a value of a specific type, it cannot be assigned a value of another type.\nThis might change in the future and can be changed by using a type-unsafe context (not provided by this crate as of now).\n\nHere are some examples and counter-examples on expressions that are interpreted as variables:\n\n| Expression | Variable? | Explanation |\n|------------|--------|-------------|\n| `a` | yes | |\n| `abc` | yes | |\n| `a\u003cb` | no | Expression is interpreted as variable `a`, operator `\u003c` and variable `b` |\n| `a b` | no | Expression is interpreted as function `a` applied to argument `b` |\n| `123` | no | Expression is interpreted as `Value::Int` |\n| `true` | no | Expression is interpreted as `Value::Bool` |\n| `.34` | no | Expression is interpreted as `Value::Float` |\n\nVariables have a precedence of 200.\n\n### User-Defined Functions\n\nThis crate allows to define arbitrary functions to be used in parsed expressions.\nA function is defined as a `Function` instance, wrapping an `fn(\u0026Value) -\u003e EvalexprResult\u003cValue\u003e`.\nThe definition needs to be included in the [`Context`](#contexts) that is used for evaluation.\nAs of now, functions cannot be defined within the expression, but that might change in the future.\n\nThe function gets passed what ever value is directly behind it, be it a tuple or a single values.\nIf there is no value behind a function, it is interpreted as a variable instead.\nMore specifically, a function needs to be followed by either an opening brace `(`, another literal, or a value.\nWhile not including special support for multi-valued functions, they can be realized by requiring a single tuple argument.\n\nBe aware that functions need to verify the types of values that are passed to them.\nThe `error` module contains some shortcuts for verification, and error types for passing a wrong value type.\nAlso, most numeric functions need to distinguish between being called with integers or floating point numbers, and act accordingly.\n\nHere are some examples and counter-examples on expressions that are interpreted as function calls:\n\n| Expression | Function? | Explanation |\n|------------|--------|-------------|\n| `a v` | yes | |\n| `x 5.5` | yes | |\n| `a (3, true)` | yes | |\n| `a b 4` | yes | Call `a` with the result of calling `b` with `4` |\n| `5 b` | no | Error, value cannot be followed by a literal |\n| `12 3` | no | Error, value cannot be followed by a value |\n| `a 5 6` | no | Error, function call cannot be followed by a value |\n\nFunctions have a precedence of 190.\n\n### Comments\n\nEvalexpr supports C-style inline comments and end-of-line comments.\nInline comments are started with a `/*` and terminated with a `*/`.\nEnd-of-line comments are started with a `//` and terminated with a newline character.\nFor example:\n\n```rust\nuse evalexpr::*;\n\nassert_eq!(\n    eval(\n        \"\n        // input\n        a = 1;  // assignment\n        // output\n        2 * a /* first double a */ + 2 // then add 2\"\n    ),\n    Ok(Value::Int(4))\n);\n```\n\n### [Serde](https://serde.rs)\n\nTo use this crate with serde, the `serde_support` feature flag has to be set.\nThis can be done like this in the `Cargo.toml`:\n\n```toml\n[dependencies]\nevalexpr = {version = \"\u003cdesired version\u003e\", features = [\"serde_support\"]}\n```\n\nThis crate implements `serde::de::Deserialize` for its type `Node` that represents a parsed expression tree.\nThe implementation expects a [serde `string`](https://serde.rs/data-model.html) as input.\nExample parsing with [ron format](https://docs.rs/ron):\n\n```rust\nextern crate ron;\nuse evalexpr::*;\n\nlet mut context = context_map!{\n    \"five\" =\u003e 5\n}.unwrap(); // Do proper error handling here\n\n// In ron format, strings are surrounded by \"\nlet serialized_free = \"\\\"five * five\\\"\";\nmatch ron::de::from_str::\u003cNode\u003e(serialized_free) {\n    Ok(free) =\u003e assert_eq!(free.eval_with_context(\u0026context), Ok(Value::from_int(25))),\n    Err(error) =\u003e {\n        () // Handle error\n    }\n}\n```\n\nWith `serde`, expressions can be integrated into arbitrarily complex data.\n\nThe crate also implements `Serialize` and `Deserialize` for the `HashMapContext`,\nbut note that only the variables get (de)serialized, not the functions.\n\n## Licensing\n\nThis crate is primarily distributed under the terms of the AGPL3 license.\nSee [LICENSE](/LICENSE) for details.\nIf you require a different licensing option for your project, contact me at `isibboi at gmail.com`.\n\nContributions to this crate are assumed to be licensed under the [MIT License](https://opensource.org/license/mit).\n\n\n\u003c!-- cargo-sync-readme end --\u003e\n\n## No Panicking\n\nThis crate makes extensive use of the `Result` pattern and is intended to never panic.\nThe *exception* are panics caused by *failed allocations*.\nBut unfortunately, Rust does not provide any features to prove this behavior.\nThe developer of this crate has not found a good solution to ensure no-panic behavior in any way.\nPlease report a panic in this crate immediately as issue on [github](https://github.com/ISibboI/evalexpr/issues).\n\nEven if the crate itself is panic free, it allows the user to define custom functions that are executed by the crate.\nThe user needs to ensure that the functions they provide to the crate never panic.\n\n## Untrusted input\n\nThis crate was not built with untrusted input in mind, but due to its simplicity and freedom of panics it is likely secure, keeping the following in mind:\n * Limit the length of the untrusted input.\n * If a mutable context is maintained between evaluations of untrusted input, the untrusted input might fill it gradually until the application runs out of memory.\n * If no context is provided, a temporary mutable context is implicitly provided. This is freed after evaluation of every single string, so gradual filling cannot happen.\n * If no context or a mutable context is provided, and the `regex_support` feature is activated, the `regex_replace` builtin function can be used to build an exponentially sized string.\n\n## Contribution\n\nIf you have any ideas for features or see any problems in the code, architecture, interface, algorithmics or documentation, please open an issue on [github](https://github.com/ISibboI/evalexpr/issues).\nIf 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.\n\n**Notes for contributors:**\n\n * This crate uses the [`sync-readme`](https://github.com/phaazon/cargo-sync-readme) cargo subcommand to keep the documentation in `src/lib.rs` and `README.md` in sync.\n   The subcommand only syncs from the documentation in `src/lib.rs` to `README.md`.\n   So please alter the documentation in the `src/lib.rs` rather than altering anything in between `\u003c!-- cargo-sync-readme start --\u003e` and `\u003c!-- cargo-sync-readme end --\u003e` in the `README.md`.\n * Your contributions are assumed to be licensed under the [MIT License](https://opensource.org/license/mit). I relicense them under the [AGPL3 license](/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fisibboi%2Fevalexpr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fisibboi%2Fevalexpr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fisibboi%2Fevalexpr/lists"}