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
use std::collections::HashMap;
use ast::Expression;
use error::{Error, ErrorKind, ErrorLevel};
use to_javascript::ToJavaScript;
type BuiltinMap = HashMap<&'static str, fn(&Vec<Box<Expression>>) -> Result<String, Error>>;
lazy_static! {
pub static ref BUILTINS: BuiltinMap = {
let mut map: BuiltinMap = HashMap::new();
map.insert("if", builtin_if);
map
};
}
pub fn builtin_if(args: &Vec<Box<Expression>>) -> Result<String, Error> {
match args.len() {
0 => {
Err(Error(ErrorLevel::Error,
ErrorKind::TooFewArguments,
"Too few Arguments applied for if"))
}
1 => {
Err(Error(ErrorLevel::Error,
ErrorKind::TooFewArguments,
"No expression applied for condition"))
}
2 => {
Ok(format!("if ({}) {{ {} }}",
args[0].eval().unwrap(),
args[1].eval().unwrap()))
}
3 => {
Ok(format!("if ({}) {{ {} }} else {{ {} }}",
args[0].eval().unwrap(),
args[1].eval().unwrap(),
args[2].eval().unwrap()))
}
_ => panic!("Unknown number of arguments supplied to if-statement"),
}
}