summaryrefslogtreecommitdiff
path: root/lisp/src/ast.rs
blob: 929383f0c21454c60d0465a0584e490568fb9c57 (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
60
61
62
63
64
use std::fmt;

#[derive(Clone, PartialEq, Eq)]
pub enum Val {
    Atom(String),
    List(Vec<Self>),
    I64(i64),
    String(String),
}

impl fmt::Debug for Val {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Val::Atom(v) => write!(f, "{v}"),
            Val::List(vs) => {
                f.write_str("(")?;
                for (i, v) in vs.iter().enumerate() {
                    if i != 0 {
                        f.write_str(" ")?;
                    }
                    v.fmt(f)?;
                }
                f.write_str(")")?;
                Ok(())
            }
            Val::I64(v) => v.fmt(f),
            Val::String(s) => s.fmt(f),
        }
    }
}

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

    #[test]
    fn print_string() {
        assert_eq!(
            format!("{:?}", Val::String("Hello, World!".to_string())),
            "\"Hello, World!\"".to_string()
        );
    }
    #[test]
    fn print_atom() {
        assert_eq!(
            format!("{:?}", Val::Atom("boo-guff".to_string())),
            "boo-guff".to_string()
        );
    }
    #[test]
    fn print_i64() {
        assert_eq!(
            format!("{:?}", Val::I64(1234)),
            "1234".to_string()
        );
    }
    #[test]
    fn print_list() {
        assert_eq!(
            format!("{:?}", Val::List(vec!(Val::Atom("a".to_string()), Val::Atom("b".to_string())))),
            "(a b)".to_string()
        );
    }
}