summaryrefslogtreecommitdiff
path: root/lisp/src/eval.rs
blob: 2afe0494e211d9d75f16db368dad1a985654e723 (plain)
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
use crate::ast::Val;

pub fn eval_f(f: &str, args: &[Val]) -> Val {
    match f {
        "quote" if args.len() == 1 => args[0].clone(),
        _ => Val::Atom("error".to_string()),
    }
}

pub fn eval(v: &Val) -> Val {
    match v {
        v @ Val::Atom(_) => v.clone(),
        v @ Val::I64(_) => v.clone(),
        v @ Val::String(_) => v.clone(),
        v @ Val::List(vs) => {
            if vs.is_empty() {
                return v.clone();
            }
            match &vs[0] {
                Val::Atom(f) => eval_f(&f, &vs[1..]),
                _ => v.clone(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn eval_atom() {
        assert_eq!(
            eval(&Val::Atom("x".to_string())),
            Val::Atom("x".to_string())
        );
    }
    #[test]
    fn eval_i64() {
        assert_eq!(eval(&Val::I64(1)), Val::I64(1));
    }
    #[test]
    fn eval_string() {
        assert_eq!(
            eval(&Val::String("hello".to_string())),
            Val::String("hello".to_string())
        );
    }
    #[test]
    fn eval_quote() {
        assert_eq!(
            eval(&Val::List(vec!(
                Val::Atom("quote".to_string()),
                Val::Atom("x".to_string())
            ))),
            Val::Atom("x".to_string())
        );
    }
}