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
11pub fn run(program: Program, ctx: &Context) -> Result<Value> {
13 DEFAULT_ENVIRONMENT.run(program, ctx)
14}
15
16pub fn eval(code: &str, ctx: &Context) -> Result<Value> {
25 DEFAULT_ENVIRONMENT.eval(code, ctx)
26}
27
28#[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 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 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 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 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::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});