pub struct ExprParser { /* private fields */ }
Expand description
Main struct for parsing and evaluating expr programs
Example:
use std::collections::HashMap;
use expr::ExprParser;
let ctx = HashMap::from([("foo", 1), ("bar", 2)]);
let p = ExprParser::new(ctx);
assert_eq!(p.eval("foo + bar").unwrap().to_string(), "3");
Implementations§
Source§impl ExprParser
impl ExprParser
Sourcepub fn new<K, V>(ctx: impl IntoIterator<Item = (K, V)>) -> Self
pub fn new<K, V>(ctx: impl IntoIterator<Item = (K, V)>) -> Self
Create a new parser with a context struct containing variables
Sourcepub fn add_function(
&mut self,
name: &str,
f: fn(_: Vec<ExprValue>) -> ExprValue,
)
pub fn add_function( &mut self, name: &str, f: fn(_: Vec<ExprValue>) -> ExprValue, )
Add a function for expr programs to call
Example:
use expr::{ExprParser, ExprValue};
let mut p = ExprParser::default();
p.add_function("add", |args| {
let mut sum = 0;
for arg in args {
if let ExprValue::Number(n) = arg {
sum += n;
} else {
panic!("Invalid argument: {arg:?}");
}
}
sum.into()
});
assert_eq!(p.eval("add(1, 2, 3)").unwrap().to_string(), "6");
Sourcepub fn compile(&self, code: &str) -> Result<ExprProgram, ExprError>
pub fn compile(&self, code: &str) -> Result<ExprProgram, ExprError>
Parse an expr program to be run later
Trait Implementations§
Source§impl Clone for ExprParser
impl Clone for ExprParser
Source§fn clone(&self) -> ExprParser
fn clone(&self) -> ExprParser
Returns a copy of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moreSource§impl Debug for ExprParser
impl Debug for ExprParser
Source§impl Default for ExprParser
impl Default for ExprParser
Source§fn default() -> ExprParser
fn default() -> ExprParser
Returns the “default value” for a type. Read more
Auto Trait Implementations§
impl Freeze for ExprParser
impl RefUnwindSafe for ExprParser
impl Send for ExprParser
impl Sync for ExprParser
impl Unpin for ExprParser
impl UnwindSafe for ExprParser
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more