expr/
eval.rs

1use crate::ast::node::Node;
2use crate::ast::program::Program;
3use crate::functions::{array, string, ExprCall, Function};
4use crate::{bail, Context, Result, Value};
5use crate::parser::compile;
6use indexmap::IndexMap;
7use once_cell::sync::Lazy;
8use std::fmt;
9use std::fmt::{Debug, Formatter};
10
11/// Run a compiled expr program, using the default environment
12pub fn run(program: Program, ctx: &Context) -> Result<Value> {
13    DEFAULT_ENVIRONMENT.run(program, ctx)
14}
15
16/// Compile and run an expr program in one step, using the default environment.
17///
18/// Example:
19/// ```
20/// use expr::{Context, eval};
21/// let ctx = Context::default();
22/// assert_eq!(eval("1 + 2", &ctx).unwrap().to_string(), "3");
23/// ```
24pub fn eval(code: &str, ctx: &Context) -> Result<Value> {
25    DEFAULT_ENVIRONMENT.eval(code, ctx)
26}
27
28/// Struct containing custom environment setup for expr evaluation (e.g. custom
29/// function definitions)
30///
31/// Example:
32///
33/// ```
34/// use expr::{Context, Environment, Value};
35/// let mut env = Environment::new();
36/// let ctx = Context::default();
37/// env.add_function("add", |c| {
38///   let mut sum = 0;
39///     for arg in c.args {
40///       if let Value::Number(n) = arg {
41///         sum += n;
42///        } else {
43///          panic!("Invalid argument: {arg:?}");
44///        }
45///     }
46///   Ok(sum.into())
47/// });
48/// assert_eq!(env.eval("add(1, 2, 3)", &ctx).unwrap().to_string(), "6");
49/// ```
50#[derive(Default)]
51pub struct Environment<'a> {
52    pub(crate) functions: IndexMap<String, Function<'a>>,
53}
54
55impl Debug for Environment<'_> {
56    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
57        f.debug_struct("ExprEnvironment").finish()
58    }
59}
60
61impl<'a> Environment<'a> {
62    /// Create a new environment with default set of functions
63    pub fn new() -> Self {
64        let mut p = Self {
65            functions: IndexMap::new(),
66        };
67        string::add_string_functions(&mut p);
68        array::add_array_functions(&mut p);
69        p
70    }
71
72    /// Add a function for expr programs to call
73    ///
74    /// Example:
75    /// ```
76    /// use expr::{Context, Environment, Value};
77    /// let mut env = Environment::new();
78    /// let ctx = Context::default();
79    /// env.add_function("add", |c| {
80    ///   let mut sum = 0;
81    ///     for arg in c.args {
82    ///       if let Value::Number(n) = arg {
83    ///         sum += n;
84    ///        } else {
85    ///          panic!("Invalid argument: {arg:?}");
86    ///        }
87    ///     }
88    ///   Ok(sum.into())
89    /// });
90    /// assert_eq!(env.eval("add(1, 2, 3)", &ctx).unwrap().to_string(), "6");
91    /// ```
92    pub fn add_function<F>(&mut self, name: &str, f: F)
93    where
94        F: Fn(ExprCall) -> Result<Value> + 'a + Sync + Send,
95    {
96        self.functions.insert(name.to_string(), Box::new(f));
97    }
98
99    /// Run a compiled expr program
100    pub fn run(&self, program: Program, ctx: &Context) -> Result<Value> {
101        let mut ctx = ctx.clone();
102        ctx.insert("$env".to_string(), Value::Map(ctx.0.clone()));
103        for (id, expr) in program.lines {
104            ctx.insert(id, self.eval_expr(&ctx, expr)?);
105        }
106        self.eval_expr(&ctx, program.expr)
107    }
108
109    /// Compile and run an expr program in one step
110    ///
111    /// Example:
112    /// ```
113    /// use std::collections::HashMap;
114    /// use expr::{Context, Environment};
115    /// let env = Environment::new();
116    /// let ctx = Context::default();
117    /// assert_eq!(env.eval("1 + 2", &ctx).unwrap().to_string(), "3");
118    /// ```
119    pub fn eval(&self, code: &str, ctx: &Context) -> Result<Value> {
120        let program = compile(code)?;
121        self.run(program, ctx)
122    }
123
124    pub fn eval_expr(&self, ctx: &Context, node: Node) -> Result<Value> {
125        let value = match node {
126            Node::Value(value) => value,
127            Node::Ident(id) => {
128                if let Some(value) = ctx.get(&id) {
129                    value.clone()
130                } else if let Some(item) = ctx
131                    .get("#")
132                    .and_then(|o| o.as_map())
133                    .and_then(|m| m.get(&id))
134                {
135                    item.clone()
136                } else {
137                    bail!("unknown variable: {id}")
138                }
139            }
140            Node::Func {
141                ident,
142                args,
143                predicate,
144            } => {
145                let args = args
146                    .into_iter()
147                    .map(|e| self.eval_expr(ctx, e))
148                    .collect::<Result<_>>()?;
149                self.eval_func(ctx, ident, args, predicate.map(|l| *l))?
150            },
151            Node::Operation {
152                left,
153                operator,
154                right,
155            } => self.eval_operator(ctx, operator, *left, *right)?,
156            Node::Unary { operator, node } => self.eval_unary_operator(ctx, operator, *node)?,
157            Node::Postfix { operator, node } => self.eval_postfix_operator(ctx, operator, *node)?,
158            Node::Array(a) => Value::Array(
159                a.into_iter()
160                    .map(|e| self.eval_expr(ctx, e))
161                    .collect::<Result<_>>()?,
162            ), // node => bail!("unexpected node: {node:?}"),
163            Node::Range(start, end) => match (self.eval_expr(ctx, *start)?, self.eval_expr(ctx, *end)?) {
164                (Value::Number(start), Value::Number(end)) => {
165                    Value::Array((start..=end).map(Value::Number).collect())
166                }
167                (start, end) => bail!("invalid range: {start:?}..{end:?}"),
168            }
169        };
170        Ok(value)
171    }
172}
173
174pub(crate) static DEFAULT_ENVIRONMENT: Lazy<Environment> = Lazy::new(|| {
175    Environment::new()
176});