1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//! # Eval
//!
//! The main functions for evaluating a function or variable.
//!
use super::{Ast, Node};
use crate::error::EvalResult;
use std::collections;
impl Node {
/// Evaluate the given `functions` calling `resolve_fn` upon each occurence to render a
/// replacement. Unlike variable resolution, we can't produce the values up front because the
/// resolution function requires being called with the `arguments` at the call site.
pub(crate) fn eval_functions(
&self,
functions: &[String],
resolve_fn: impl Fn(&str, &[Ast]) -> EvalResult<Ast>,
) -> EvalResult<Node> {
let mut evaled_ast = self.clone();
for fn_name in functions {
evaled_ast = evaled_ast.call_function(fn_name, &resolve_fn)?;
}
Ok(evaled_ast)
}
/// Use the mapping in `variable_values` to replace each variable referenced in the AST with
/// it's given replacement.
pub(crate) fn eval_variables(
&self,
variable_values: collections::HashMap<String, Ast>,
) -> EvalResult<Node> {
let mut evaled_ast = self.clone();
for (var_id, replacement) in variable_values {
evaled_ast = evaled_ast.replace_variable(&var_id, replacement);
}
Ok(evaled_ast)
}
/// Do a depth-first-search on the AST, "calling" the function wherever we see a
/// `Node::FunctionCall` with the matching name. Calling a function can result in two main
/// paths:
///
/// * We get a `Node::Function` back. This means we're calling a user defined function. To
/// handle this take each of the args, find the corresponding arg in the calling site and
/// replace it in the `body`. Then return that resulting body.
///
/// * We get any other kind of `Node` back. This will happen if a builtin function is called -
/// in this case just replace the calling site with that value.
///
/// Anything else in the AST just gets left alone and included in the final output as-is.
fn call_function(
&self,
fn_id: &str,
resolve_fn: &impl Fn(&str, &[Ast]) -> EvalResult<Ast>,
) -> EvalResult<Self> {
match self {
// handle a function that we're calling
Self::FunctionCall { args, name } if name == fn_id =>
// call the resolve function which will either give us the result of a builtin
// (typically a terminal node) or a user-defined function (always a
// `Node::Function`)
{
match *resolve_fn(fn_id, args)? {
// when we get a `Node::Function`, take the body and replace each of it's
// arguments in the body. For example:
//
// fn foo(a, b) a + b
//
// called as:
//
// foo(1, 2)
//
// will evaluate to:
//
// (1 + 2)
Self::Function {
args: resolved_args,
body,
..
} => {
let mut evaled_body = *body;
for (i, resolved_arg) in resolved_args.iter().enumerate() {
evaled_body =
evaled_body.replace_variable(resolved_arg, args[i].clone());
}
Ok(evaled_body)
}
// otherwise the function resolved to a non-function. just treat that as
// terminal and return it. typically when a builtin is called it will hit this
// path because they (at least most of them) return `Node::Reference`s
node => Ok(node),
}
}
// it's a function call but not the one we're looking for - recurse through the
// arguments
Self::FunctionCall { args, name } => {
let mut called_args = vec![];
for arg in args {
called_args.push(arg.call_function(fn_id, resolve_fn)?);
}
Ok(Node::fn_call(name, &called_args))
}
// also recurse for infix functions
Self::InfixFunctionCall {
left,
operator,
right,
} => Ok(Node::infix_fn_call(
left.call_function(fn_id, resolve_fn)?,
operator,
right.call_function(fn_id, resolve_fn)?,
)),
// otherwise just don't modify it
_ => Ok(self.clone()),
}
}
/// Depth-first-search replacing `Node::Reference`s of `var_id` with `replacement`.
fn replace_variable(&self, var_id: &str, replacement: Ast) -> Self {
match self {
Node::FunctionCall { args, name } => {
// recursively call for each arg to a function
let mut replaced_args = vec![];
for arg in args {
replaced_args.push(arg.replace_variable(var_id, replacement.clone()));
}
Node::fn_call(name, &replaced_args)
}
Node::InfixFunctionCall {
left,
operator,
right,
} => Node::infix_fn_call(
left.replace_variable(var_id, replacement.clone()),
operator,
right.replace_variable(var_id, replacement.clone()),
),
// a reference matching our variable - take the replacement
Node::Reference(r) if var_id == r => *replacement,
// otherwise keep the Node unmodified
_ => self.clone(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn eval_functions_nomatch() {
let ast = Box::new(Node::reference("foo"));
assert_eq!(
ast,
Box::new(
ast.eval_functions(&["bar".to_owned(), "baz".to_owned()], |_fn_id, _args| {
Ok(Box::new(42.into()))
})
.unwrap()
)
);
}
#[test]
fn eval_functions_builtin() {
let ast = Box::new(Node::fn_call("foo_builtin", &[]));
assert_eq!(
Box::new(42.into()),
Box::new(
ast.eval_functions(&["foo_builtin".to_owned()], |_fn_id, _args| {
Ok(Box::new(42.into()))
})
.unwrap()
)
);
}
#[test]
fn eval_functions_user_defined() {
let ast = Box::new(Node::fn_call("my_func", &[1.into(), 2.into()]));
assert_eq!(
Box::new(Node::infix_fn_call(1.into(), "+", 2.into())),
Box::new(
ast.eval_functions(&["my_func".to_owned()], |_fn_id, _args| {
Ok(Box::new(Node::fn_def(
"my_func",
&["a", "b"],
Node::infix_fn_call(Node::reference("a"), "+", Node::reference("b")),
)))
})
.unwrap()
)
);
}
#[test]
fn eval_variables_nomatch() {
let ast = Box::new(Node::reference("foo"));
let mut values = collections::HashMap::new();
values.insert("bar".to_string(), Box::new(1.into()));
assert_eq!(Box::new(ast.eval_variables(values).unwrap()), ast);
}
#[test]
fn eval_variables_replaced() {
let ast = Box::new(Node::reference("foo"));
let mut values = collections::HashMap::new();
values.insert("foo".to_string(), Box::new(1.into()));
assert_eq!(
Box::new(ast.eval_variables(values).unwrap()),
Box::new(1.into())
);
}
#[test]
fn eval_variables_multiple() {
let ast = Box::new(Node::fn_call(
"my_func",
&[Node::reference("foo"), Node::reference("bar")],
));
let mut values = collections::HashMap::new();
values.insert("foo".to_string(), Box::new(1.into()));
values.insert("bar".to_string(), Box::new(2.into()));
assert_eq!(
Box::new(ast.eval_variables(values).unwrap()),
Box::new(Node::fn_call("my_func", &[1.into(), 2.into()]))
);
}
#[test]
fn eval_variables_nested_fn_call() {
let ast = Box::new(Node::fn_call(
"outer_func",
&[Node::fn_call(
"my_func",
&[Node::reference("foo"), Node::reference("bar")],
)],
));
let mut values = collections::HashMap::new();
values.insert("foo".to_string(), Box::new(1.into()));
values.insert("bar".to_string(), Box::new(2.into()));
assert_eq!(
Box::new(ast.eval_variables(values).unwrap()),
Box::new(Node::fn_call(
"outer_func",
&[Node::fn_call("my_func", &[1.into(), 2.into()])]
))
);
}
#[test]
fn eval_variables_nested_infix_fn_call() {
let ast = Box::new(Node::infix_fn_call(
Node::fn_call("my_func", &[Node::reference("foo"), Node::reference("bar")]),
"*",
5.into(),
));
let mut values = collections::HashMap::new();
values.insert("foo".to_string(), Box::new(3.into()));
values.insert("bar".to_string(), Box::new(4.into()));
assert_eq!(
Box::new(ast.eval_variables(values).unwrap()),
Box::new(Node::infix_fn_call(
Node::fn_call("my_func", &[3.into(), 4.into()]),
"*",
5.into()
))
);
}
}