aboutsummaryrefslogtreecommitdiff
path: root/src/sexp/display.rs
blob: e6dbb7ce401b1646bb50acbd68eec9d958406944 (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

use std::fmt;
use crate::sexp::{SLeaf, SExp, SLeaf::*, SExp::*, util::*};


impl fmt::Display for SLeaf {

    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", match self {
            Add    => "+".to_string(),
            Sub    => "-".to_string(),
            Mul    => "*".to_string(),
            Div    => "/".to_string(),
            Int(x) => x.to_string(),
            Var(s) => s.to_string(),
            Quote  => "quote".to_string(),
            Nil    => "()".to_string(),
        })
    }

}


impl fmt::Display for SExp {

    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Atom(leaf) => write!(f, "{}", leaf.to_string()),
            SCons(a, b) => {
                match scons(a.clone(), b.clone()).into_vec() {
                    Ok(l) => write!(
                        f,
                        "({})",
                        l.into_iter()
                         .map(|x| x.to_string())
                         .collect::<Vec<String>>()
                         .join(" ")
                    ),
                    Err(_) => write!(f, "({} {})", *a, *b),
                }
            }
        }
    }

}