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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
pub mod functions;
pub mod value;
pub mod stack;
use self::value::Value;
use super::parse::ast::{Node, AddOp, MulOp, CompOp};
use super::turtle;
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct RuntimeError(String);
impl ::std::fmt::Display for RuntimeError {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
fmt.pad(&self.0)
}
}
impl ::std::error::Error for RuntimeError {
fn description(&self) -> &str {
"runtime error"
}
}
pub type ResultType = Result<Value, RuntimeError>;
pub type FuncType = fn(&mut Environment, &[Value]) -> ResultType;
pub enum Function {
Defined(Node),
Native(i32, FuncType),
}
impl Clone for Function {
fn clone(&self) -> Function {
use self::Function::*;
match *self {
Defined(ref node) => Defined(node.clone()),
Native(arg_count, function) => Native(arg_count, function),
}
}
}
pub struct Environment {
functions: HashMap<String, Function>,
stack: Vec<stack::Frame>,
turtle: turtle::Turtle,
}
impl Environment {
pub fn new(turtle: turtle::Turtle) -> Environment {
Environment {
functions: functions::default_functions(),
stack: stack::new_stack(),
turtle: turtle,
}
}
pub fn get_turtle(&mut self) -> &mut turtle::Turtle {
&mut self.turtle
}
pub fn function_arg_count(&self) -> HashMap<String, i32> {
let mut result = HashMap::new();
for (name, function) in self.functions.iter() {
let count = match *function {
Function::Native(i, _) => i,
Function::Defined(ref node) => {
match *node {
Node::LearnStatement(_, ref args, _) => args.len() as i32,
_ => panic!("Function node is not a LearnStatement"),
}
},
};
result.insert(name.clone(), count);
}
result
}
pub fn eval_source(&mut self, source: &str) -> Result<Value, Box<::std::error::Error>> {
use super::lex;
use super::parse;
let tokens = match lex::tokenize(source) {
Ok(t) => t,
Err(e) => return Err(Box::new(e)),
};
let mut parser = parse::Parser::new(tokens, self.function_arg_count());
let tree = match parser.parse() {
Ok(n) => n.flatten(),
Err(e) => return Err(Box::new(e)),
};
match self.eval(&tree) {
Ok(v) => return Ok(v),
Err(e) => return Err(Box::new(e)),
};
}
pub fn eval(&mut self, node: &Node) -> ResultType {
use super::parse::ast::Node::*;
if self.current_frame().should_return {
return Ok(Value::Nothing);
}
match *node {
StatementList(ref nodes) =>
self.eval_statement_list(nodes),
IfStatement(ref condition, ref true_body, ref false_body) =>
self.eval_if_statement(condition, true_body, false_body),
RepeatStatement(ref num, ref body) =>
self.eval_repeat_statement(num, body),
WhileStatement(ref condition, ref body) =>
self.eval_while_statement(condition, body),
ref learn_statement @ LearnStatement(..) =>
self.eval_learn_statement(learn_statement),
Comparison(ref a, op, ref b) =>
self.eval_comparison(a, op, b),
Addition(ref start, ref values) =>
self.eval_addition(start, values),
Multiplication(ref start, ref values) =>
self.eval_multiplication(start, values),
FuncCall(ref name, ref args) =>
self.eval_func_call(name, args),
ReturnStatement(ref value) =>
self.eval_return_statement(value),
TryStatement(ref normal, ref exception) =>
self.eval_try_statement(normal, exception),
List(ref elements) =>
self.eval_list(elements),
StringLiteral(ref string) =>
Ok(Value::String(string.clone())),
Number(num) =>
Ok(Value::Number(num)),
Variable(ref name) =>
self.eval_variable(name),
}
}
fn eval_statement_list(&mut self, statements: &Vec<Node>) -> ResultType {
for statement in statements {
try!(self.eval(statement));
}
Ok(Value::Nothing)
}
fn eval_if_statement(&mut self, condition: &Node, true_body: &Node,
false_body: &Option<Box<Node>>)
-> ResultType
{
let value = try!(self.eval(condition));
if value.boolean() {
try!(self.eval(true_body));
} else if let &Some(ref false_body) = false_body {
try!(self.eval(false_body));
}
Ok(Value::Nothing)
}
fn eval_repeat_statement(&mut self, num: &Node, body: &Node) -> ResultType {
let num = try!(self.eval(num));
if let Value::Number(num) = num {
for _ in (0..num as i32) {
try!(self.eval(body));
}
Ok(Value::Nothing)
} else {
Err(RuntimeError("repeat count has to be a number".to_string()))
}
}
fn eval_while_statement(&mut self, condition: &Node, body: &Node) -> ResultType {
while try!(self.eval(condition)).boolean() {
try!(self.eval(body));
}
Ok(Value::Nothing)
}
fn eval_learn_statement(&mut self, statement: &Node) -> ResultType {
if let Node::LearnStatement(ref name, _, _) = *statement {
self.functions.insert(name.clone(), Function::Defined(statement.clone()));
Ok(Value::Nothing)
} else {
panic!("{:?} is not a LearnStatement", statement);
}
}
fn eval_try_statement(&mut self, normal: &Node, exception: &Node) -> ResultType {
let result = self.eval(normal);
match result {
Ok(_) => Ok(Value::Nothing),
Err(_) => self.eval(exception),
}
}
fn eval_comparison(&mut self, a: &Node, op: CompOp, b: &Node) -> ResultType {
let value_a = try!(self.eval(a));
let value_b = try!(self.eval(b));
let compare = value_a.partial_cmp(&value_b);
match compare {
Some(ordering) => Ok(Value::Number({
if op.matches(&ordering) { 1.0 } else { 0.0 }
})),
None => Err(RuntimeError(format!("Can't compare {} and {}",
value_a.type_string(), value_b.type_string()))),
}
}
fn eval_addition(&mut self, start: &Node, values: &Vec<(AddOp, Node)>) -> ResultType {
let mut accum = try!(self.eval(start));
for &(op, ref value) in values.iter() {
let value = try!(self.eval(value));
let result = match op {
AddOp::Add => &accum + &value,
AddOp::Sub => &accum - &value,
};
accum = match result {
Some(v) => v,
None => return Err(RuntimeError(
format!("Can't add/subtract {} and {}",
accum.type_string(), value.type_string()))),
}
}
Ok(accum)
}
fn eval_multiplication(&mut self, start: &Node, values: &Vec<(MulOp, Node)>) -> ResultType {
let mut accum = try!(self.eval(start));
for &(op, ref value) in values.iter() {
let value = try!(self.eval(value));
let result = match op {
MulOp::Mul => &accum * &value,
MulOp::Div => &accum / &value,
};
accum = match result {
Some(v) => v,
None => return Err(RuntimeError(
format!("Can't multiply/divide {} and {}",
accum.type_string(), value.type_string()))),
}
}
Ok(accum)
}
fn eval_func_call(&mut self, name: &String, arg_nodes: &Vec<Node>) -> ResultType {
let function = match self.functions.get(&name.to_uppercase()) {
Some(f) => f.clone(),
None => return Err(RuntimeError(format!("function {} not found", name))),
};
let args: Vec<Value> = try!(arg_nodes.iter().map(|a| self.eval(a)).collect());
match function {
Function::Native(_, ref f) => {
f(self, &args)
},
Function::Defined(ref node) => {
match *node {
Node::LearnStatement(ref name, ref arg_names, ref body) =>
self.call_defined_function(name, arg_names, args, body),
_ => panic!("Defined function is no LearnStatement"),
}
}
}
}
fn call_defined_function(&mut self, name: &String, arg_names: &Vec<String>,
args: Vec<Value>, body: &Node)
-> ResultType
{
let mut frame = stack::Frame::default();
frame.fn_name = name.clone();
for (name, value) in arg_names.iter().zip(args) {
frame.locals.insert(name.clone(), value);
}
self.stack.push(frame);
try!(self.eval(body));
frame = self.stack.pop().unwrap();
match frame.return_value {
Some(value) => Ok(value),
None => Ok(Value::Nothing),
}
}
fn eval_return_statement(&mut self, value: &Node) -> ResultType {
if self.current_frame().is_global {
return Err(RuntimeError("Return not in a function".to_string()));
}
let value = try!(self.eval(value));
self.current_frame().return_value = Some(value);
self.current_frame().should_return = true;
Ok(Value::Nothing)
}
fn eval_list(&mut self, elements: &Vec<Node>) -> ResultType {
let mut result = Vec::new();
for node in elements {
result.push(try!(self.eval(node)));
}
Ok(Value::List(result))
}
fn eval_variable(&mut self, name: &String) -> ResultType {
match self.get_variable(name) {
Some(value) => Ok(value),
None => Err(RuntimeError(format!("Variable {} not found", name))),
}
}
pub fn current_frame(&mut self) -> &mut stack::Frame {
let len = self.stack.len();
&mut self.stack[len - 1]
}
pub fn global_frame(&mut self) -> &mut stack::Frame {
&mut self.stack[0]
}
pub fn get_variable(&mut self, name: &str) -> Option<Value> {
{
let local_frame = self.current_frame();
match local_frame.locals.get(name) {
Some(value) => return Some(value.clone()),
None => (),
}
}
let global_frame = self.global_frame();
global_frame.locals.get(name).map(|v| v.clone())
}
}