EvalEx is a powerful expression evaluation library for Elixir, based on evalexpr using rustler.
EvalEx evaluates expressions in Elixir, leveraging the evalexpr crate tiny scripting language.
Please refer to the evalexpr documentation for extended information about the language.
Add :evalex
to the list of dependencies in mix.exs
:
def deps do
[
{:evalex, "~> 0.1.1"}
]
end
iex> EvalEx.eval("1 + 1")
{:ok, 2}
iex> EvalEx.eval("a * b", %{"a" => 10, "b" => 10})
{:ok, 100}
iex> EvalEx.eval("a == b", %{"a" => "tonio", "b" => "wanda"})
{:ok, false}
iex> EvalEx.eval("a != b", %{"a" => "tonio", "b" => "wanda"})
{:ok, true}
iex> EvalEx.eval("len(a)", %{"a" => [1, 2, 3]})
{:ok, 3}
iex> EvalEx.eval("a + b", %{"a" => 10})
{:error,
{:variable_identifier_not_found,
"Variable identifier is not bound to anything by context: \"b\"."}}
EvalEx allows you to precompile expressions to speed up the evaluation.
iex> {:ok, precompiled_expression} = EvalEx.precompile_expression("1 + 1")
{:ok,
%EvalEx.PrecompiledExpression{
reference: #Reference<0.2278913865.304611331.189837>,
resource: #Reference<0.2278913865.304742403.189834>
}}
iex> EvalEx.eval(precompiled_expression)
{:ok, 2}
Elixir Types are converted to EvalEx types (and back) as follows:
Elixir | EvalEx |
---|---|
integer() | Int |
float() | Float |
bool() | Boolean |
String.t() | String |
list() | Tuple |
tuple() | Tuple |
nil() | Empty |
pid() | Empty (not supported) |
ref() | Empty (not supported) |
fun() | Empty (not supported) |
map() | Empty (not supported) |
By default, you don't need the Rust toolchain installed because the lib will try to download
a precompiled NIF file.
In case you want to force compilation set the
EVALEX_FORCE_BUILD
environment variable to true
or 1
.
Precompiled NIFs are available for the following platforms:
- aarch64-apple-darwin
- x86_64-apple-darwin
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- arm-unknown-linux-gnueabihf
- aarch64-unknown-linux-gnu
- aarch64-unknown-linux-musl
- x86_64-pc-windows-msvc
- x86_64-pc-windows-gnu
This library is licensed under Apache 2.0 License. See LICENSE for details.
- evalexpr The Rust crate doing most of the dirty work.
- RustlerPrecompiled Use precompiled NIFs from trusted sources in your Elixir code.
- NimbleLZ4 Major inspiration for the RustlerPrecompiled GitHub actions workflow and general setup.