expr

Struct ExprParser

Source
pub struct ExprParser { /* private fields */ }
Expand description

Main struct for parsing and evaluating expr programs

Implementations§

Source§

impl ExprParser

Source

pub fn new<K, V>(ctx: impl IntoIterator<Item = (K, V)>) -> Self
where K: AsRef<str>, V: Into<ExprValue>,

Create a new parser with a context struct containing variables

Source

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");
Source

pub fn compile(&self, code: &str) -> Result<ExprProgram, ExprError>

Parse an expr program to be run later

Source

pub fn run(&self, program: ExprProgram) -> Result<ExprValue, ExprError>

Run a compiled expr program

Source

pub fn eval(&self, code: &str) -> Result<ExprValue, ExprError>

Compile and run an expr program in one step

Example:

use expr::ExprParser;
let p = ExprParser::default();
assert_eq!(p.eval("1 + 2").unwrap().to_string(), "3");

Trait Implementations§

Source§

impl Default for ExprParser

Source§

fn default() -> ExprParser

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.