s_expr/
printer.rs

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
use super::data::GroupKind;

/// Simple printer
#[derive(Clone)]
pub struct Printer {
    buf: String,
    prev: PrinterState,
}

#[derive(Clone, PartialEq, Eq)]
pub enum PrinterState {
    Group,
    Text,
}

impl Default for Printer {
    fn default() -> Self {
        Self {
            buf: String::new(),
            prev: PrinterState::Group,
        }
    }
}

impl Printer {
    /// Create a new group
    pub fn open(&mut self, grp: GroupKind) {
        if self.prev == PrinterState::Text {
            self.buf.push(' ');
        }
        let c = match grp {
            GroupKind::Paren => '(',
            GroupKind::Bracket => '[',
            GroupKind::Brace => '{',
        };
        self.prev = PrinterState::Group;
        self.buf.push(c);
    }

    /// Close a group
    pub fn close(&mut self, grp: GroupKind) {
        let c = match grp {
            GroupKind::Paren => ')',
            GroupKind::Bracket => ']',
            GroupKind::Brace => '}',
        };
        self.prev = PrinterState::Group;
        self.buf.push(c);
    }

    /// Add text
    pub fn text(&mut self, s: &str) {
        if self.prev == PrinterState::Text {
            self.buf.push(' ');
        }
        self.prev = PrinterState::Text;
        self.buf.push_str(s)
    }

    pub fn to_string(self) -> String {
        self.buf
    }
}

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

    #[test]
    fn t1() {
        let mut p = Printer::default();
        p.open(GroupKind::Paren);
        p.close(GroupKind::Paren);
        let out = p.to_string();
        assert_eq!(out, "()");
    }

    #[test]
    fn t2() {
        let mut p = Printer::default();
        p.open(GroupKind::Paren);
        p.text("let");
        p.text("x");
        p.text("=");
        p.text("1");
        p.close(GroupKind::Paren);
        let out = p.to_string();
        assert_eq!(out, "(let x = 1)");
    }

    #[test]
    fn t3() {
        let mut p = Printer::default();
        p.open(GroupKind::Paren);
        p.text("let");
        p.text("x");
        p.text("=");
        p.open(GroupKind::Paren);
        p.text("+");
        p.text("1");
        p.text("0xabc");
        p.close(GroupKind::Paren);
        p.close(GroupKind::Paren);
        let out = p.to_string();
        assert_eq!(out, "(let x = (+ 1 0xabc))");
    }
}