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
291
292
293
294
295
296
//! # Eval
//!
//! The main functions for evaluating a function or variable.
//!
use super::references::{AstReferences, ReferencesIter};
use super::{Ast, Node, VariableValue, Variables};
use crate::{EvalError, EvalResult, Scope};
use std::collections;
impl Ast {
/// The idea here is just to keep looping as long as we are making progress eval()ing. Where
/// progress means that `.extract_references()` returns a different, non-empty result each
/// time.
pub(crate) fn eval(
self,
scope: &Scope,
position: Option<a1_notation::Address>,
) -> EvalResult<Self> {
let mut evaled_ast = self;
let mut last_round_refs = AstReferences::default();
loop {
let refs = evaled_ast.extract_references(scope);
if refs.is_empty() || refs == last_round_refs {
break;
}
last_round_refs = refs.clone();
evaled_ast = evaled_ast
.eval_variables(Self::resolve_variables(
scope,
refs.variables.into_iter(),
position,
))
.eval_functions(refs.functions.into_iter(), scope)?;
}
Ok(evaled_ast)
}
/// Variables can all be resolved in one go - we just loop them by name and resolve the ones
/// that we can and leave the rest alone.
fn resolve_variables(
scope: &Scope,
var_names: ReferencesIter,
position: Option<a1_notation::Address>,
) -> collections::HashMap<String, Self> {
let mut resolved_vars: Variables = collections::HashMap::default();
for var_name in var_names {
if let Some(value) = scope.variables.get(&var_name) {
let value_from_var = match &**value {
Node::Variable { value, .. } => value.clone().into_ast(position),
n => n.clone().into(),
};
resolved_vars.insert(var_name.to_string(), value_from_var);
}
}
resolved_vars
}
/// 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.
fn eval_functions(self, fns_to_resolve: ReferencesIter, scope: &Scope) -> EvalResult<Self> {
let mut evaled_ast = self;
for fn_name in fns_to_resolve {
if let Some(fn_ast) = scope.functions.get(&fn_name) {
evaled_ast = evaled_ast.call_function(&fn_name, fn_ast)?;
} else {
// TODO: log a warning that we tried to resolve an unknown function
// this is one of those things that should never happen (since `fns_to_resolve`
// is only comprised of functions we know about)
}
}
Ok(evaled_ast)
}
/// Use the mapping in `variable_values` to replace each variable referenced in the AST with
/// it's given replacement.
fn eval_variables(&self, variable_values: Variables) -> Self {
let mut evaled_ast = self.clone();
for (var_id, replacement) in variable_values {
evaled_ast = evaled_ast.replace_variable(&var_id, replacement);
}
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:
fn call_function(self, fn_id: &str, fn_ast: &Self) -> EvalResult<Self> {
let inner = self.into_inner();
Ok(match inner {
Node::FunctionCall { args, name } if name == fn_id => {
match (*fn_ast).clone().into_inner() {
// 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)
Node::Function {
args: resolved_args,
body,
..
} => {
if args.len() != resolved_args.len() {
return Err(EvalError::new(
fn_ast.to_string(),
format!(
"Expected {} arguments but received {}",
args.len(),
resolved_args.len()
),
));
}
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());
}
evaled_body
}
// otherwise the function resolved to a non-function. just treat that as
// terminal and return it.
node => node.into(),
}
}
// it's a function call but not the one we're looking for - recurse through the
// arguments
Node::FunctionCall { args, name } => {
let mut called_args = vec![];
for arg in args {
called_args.push(arg.call_function(fn_id, fn_ast)?);
}
Node::FunctionCall {
name,
args: called_args,
}
.into()
}
// also recurse for infix functions
Node::InfixFunctionCall {
left,
operator,
right,
} => Node::InfixFunctionCall {
left: left.call_function(fn_id, fn_ast)?,
operator,
right: right.call_function(fn_id, fn_ast)?,
}
.into(),
Node::Variable {
value: VariableValue::Ast(ast),
name,
} => Node::Variable {
name,
value: VariableValue::Ast(ast.call_function(fn_id, fn_ast)?),
}
.into(),
// otherwise just don't modify it
_ => inner.clone().into(),
})
}
/// Depth-first-search replacing `Node::Reference`s of `var_id` with `replacement`.
fn replace_variable(&self, var_id: &str, replacement: Self) -> Self {
let inner = (**self).clone();
Ast::new(match inner {
Node::FunctionCall { args, name } => {
Node::FunctionCall {
// recursively call for each arg to a function
args: args
.into_iter()
.map(|a| a.replace_variable(var_id, replacement.clone()))
.collect(),
name,
}
}
Node::Function { args, body, name } => Node::Function {
name,
args,
body: body.replace_variable(var_id, replacement.clone()),
},
Node::InfixFunctionCall {
left,
operator,
right,
} => Node::InfixFunctionCall {
left: left.replace_variable(var_id, replacement.clone()),
operator,
right: right.replace_variable(var_id, replacement.clone()),
},
// a reference matching our variable - take the replacement
Node::Reference(r) if var_id == r => replacement.into_inner(),
Node::Variable {
value: VariableValue::Ast(ast),
name,
} => Node::Variable {
name,
value: VariableValue::Ast(ast.replace_variable(var_id, replacement.clone())),
},
// otherwise keep the Node unmodified
_ => inner,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::*;
#[test]
fn eval_unknown_function() {
let ast = Ast::new(Node::fn_call("foo", &[Ast::from(1)]));
assert_eq!(ast.clone().eval(&Scope::default(), None).unwrap(), ast);
}
#[test]
fn eval_known_function() {
let ast = Ast::new(Node::fn_call("foo", &[Ast::from(1), 2.into()]));
let mut scope = Scope::default();
scope.functions.insert(
"foo".to_string(),
Node::fn_def("foo", &["a", "b"], Ast::from(1)).into(),
);
assert_eq!(ast.clone().eval(&scope, None).unwrap(), 1.into());
}
#[test]
fn eval_known_function_wrong_number_of_args() {
let ast = Ast::new(Node::fn_call("foo", &[Ast::from(1)]));
let mut scope = Scope::default();
scope.functions.insert(
"foo".to_string(),
Node::fn_def("foo", &["a", "b"], Ast::from(1)).into(),
);
assert!(ast.clone().eval(&scope, None).is_err());
}
#[test]
fn eval_variable() {
let ast = Ast::new(Node::reference("foo"));
let mut scope = Scope::default();
scope.variables.insert(
"foo".to_string(),
Node::var("foo", VariableValue::Ast(1.into())).into(),
);
assert_eq!(ast.clone().eval(&scope, None).unwrap(), 1.into());
}
#[test]
fn eval_variable_in_variable_value() {
let ast = Ast::new(Node::var(
"bar",
VariableValue::Ast(Node::reference("foo").into()),
));
let mut scope = Scope::default();
scope.variables.insert(
"foo".to_string(),
Node::var("foo", VariableValue::Ast(1.into())).into(),
);
assert_eq!(
ast.clone().eval(&scope, None).unwrap(),
Node::var("bar", VariableValue::Ast(1.into())).into()
);
}
}