#expr #context #parser #language

expr-lang

Implementation of expr language in Rust

9 releases

new 0.2.1 Nov 29, 2024
0.2.0 Nov 29, 2024
0.1.6 Nov 25, 2024

#2233 in Parser implementations

Download history 535/week @ 2024-11-19 1552/week @ 2024-11-26

2,092 downloads per month
Used in mise

MIT license

61KB
1.5K SLoC

expr-lang

Implementation of expr in rust.

Usage

use expr::{Context, Parser};

fn main() {
    let mut p = Parser::new();

    let mut ctx = Context::default();
    ctx.insert("two".to_string(), 2);

    let three: i64 = p.eval("1 + two", &ctx).unwrap().as_number().unwrap();
    assert_eq!(three, 3);

    p.add_function("add", |c| {
        let mut sum = 0;
        for arg in c.args {
            sum += arg.as_number().unwrap();
        }
        Ok(sum.into())
    });

    let six: i64 = p.eval("add(1, two, 3)", &ctx).unwrap().as_number().unwrap();
    assert_eq!(six, 6);
}

lib.rs:

Example:

use expr::{Context, Parser};

let mut p = Parser::new();

let mut ctx = Context::default();
ctx.insert("two".to_string(), 2);

let three: i64 = p.eval("1 + two", &ctx).unwrap().as_number().unwrap();
assert_eq!(three, 3);

p.add_function("add", |c| {
  let mut sum = 0;
  for arg in c.args {
    sum += arg.as_number().unwrap();
  }
  Ok(sum.into())
});

let six: i64 = p.eval("add(1, two, 3)", &ctx).unwrap().as_number().unwrap();
assert_eq!(six, 6);

Dependencies

~5–7MB
~128K SLoC