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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use super::atom::Atom;
use super::parser;
use super::token::{Token, Tokenizer};
use std::collections::BTreeMap;
use std::fmt;
use std::io;

#[derive(Debug, PartialEq, Clone)]
pub enum Sexp {
    Atom(Atom),

    // ( ... )
    Tuple(Vec<Sexp>),

    // [ ... ]
    Array(Vec<Sexp>),

    // { key val ... }
    Map(Vec<(Sexp, Sexp)>),
}

impl Sexp {
    pub fn is_atom(&self) -> bool {
        match self {
            &Sexp::Atom(..) => true,
            _ => false,
        }
    }

    pub fn is_flat(&self) -> bool {
        match self {
            &Sexp::Atom(..) => true,
            &Sexp::Tuple(ref vec) => vec.iter().all(Sexp::is_atom),
            &Sexp::Array(ref vec) => vec.iter().all(Sexp::is_atom),
            &Sexp::Map(ref vec) => vec.iter().all(|e| e.0.is_atom() && e.1.is_atom()),
        }
    }

    /// Converts a Sexp::Map into a BTreeMap<String, Sexp> if possible.
    pub fn into_map(self) -> Result<BTreeMap<String, Sexp>, &'static str> {
        match self {
            Sexp::Map(pairs) => {
                let mut map = BTreeMap::new();
                for (key, val) in pairs {
                    match key {
                        Sexp::Atom(Atom::Str(s)) => {
                            if map.insert(s, val).is_some() {
                                return Err("duplicate key");
                            }
                        }
                        _ => return Err("key has to be a string"),
                    }
                }
                return Ok(map);
            }
            _ => Err("expr is not a Sexp::Map"),
        }
    }

    pub fn get_uint(&self) -> Option<u64> {
        match self {
            &Sexp::Atom(Atom::UInt(u)) => Some(u),
            _ => None,
        }
    }

    pub fn get_int(&self) -> Option<i64> {
        match self {
            &Sexp::Atom(Atom::SInt(s)) => Some(s),
            _ => None,
        }
    }

    pub fn get_float(&self) -> Option<f64> {
        match self {
            &Sexp::Atom(Atom::Float(f)) => Some(f),
            _ => None,
        }
    }

    pub fn get_str(&self) -> Option<&str> {
        match self {
            &Sexp::Atom(Atom::Str(ref s)) => Some(s),
            _ => None,
        }
    }

    pub fn get_vec<'a, F, R>(&'a self, f: F) -> Option<Vec<R>>
    where
        F: Fn(&'a Sexp) -> Option<R>,
    {
        match self {
            &Sexp::Array(ref ary) => {
                let mut a = Vec::new();
                for elm in ary.iter() {
                    if let Some(u) = f(elm) {
                        a.push(u);
                    } else {
                        return None;
                    }
                }
                Some(a)
            }
            _ => None,
        }
    }

    pub fn get_uint_vec(&self) -> Option<Vec<u64>> {
        self.get_vec(|elm| elm.get_uint())
    }

    pub fn parse_iter<'a, I>(mut iter: I) -> Result<Sexp, ()>
    where
        I: Iterator<Item = Token<'a>>,
    {
        if let Ok(expr) = parser::parse_sexp(&mut iter) {
            if parser::at_end(&mut iter) {
                return Ok(expr);
            }
        }
        Err(())
    }

    pub fn parse(s: &str) -> Result<Sexp, ()> {
        Sexp::parse_iter(Tokenizer::new(s, true))
    }

    pub fn parse_toplevel(s: &str) -> Result<Sexp, ()> {
        Sexp::parse_iter(Tokenizer::new(s, true).with_curly_around())
    }
}

impl<T> From<T> for Sexp
where
    T: Into<Atom>,
{
    fn from(t: T) -> Sexp {
        Sexp::Atom(t.into())
    }
}

impl From<()> for Sexp {
    fn from(_e: ()) -> Sexp {
        Sexp::Tuple(vec![])
    }
}

impl<A> From<(A,)> for Sexp
where
    A: Into<Sexp>,
{
    fn from(e: (A,)) -> Sexp {
        Sexp::Tuple(vec![e.0.into()])
    }
}

impl<A, B> From<(A, B)> for Sexp
where
    A: Into<Sexp>,
    B: Into<Sexp>,
{
    fn from(e: (A, B)) -> Sexp {
        Sexp::Tuple(vec![e.0.into(), e.1.into()])
    }
}

impl<A, B, C> From<(A, B, C)> for Sexp
where
    A: Into<Sexp>,
    B: Into<Sexp>,
    C: Into<Sexp>,
{
    fn from(e: (A, B, C)) -> Sexp {
        Sexp::Tuple(vec![e.0.into(), e.1.into(), e.2.into()])
    }
}

impl<A, B, C, D> From<(A, B, C, D)> for Sexp
where
    A: Into<Sexp>,
    B: Into<Sexp>,
    C: Into<Sexp>,
    D: Into<Sexp>,
{
    fn from(e: (A, B, C, D)) -> Sexp {
        Sexp::Tuple(vec![e.0.into(), e.1.into(), e.2.into(), e.3.into()])
    }
}

impl<A> From<Vec<A>> for Sexp
where
    A: Into<Sexp>,
{
    fn from(arr: Vec<A>) -> Sexp {
        Sexp::Array(arr.into_iter().map(|e| e.into()).collect())
    }
}

pub fn pp(sexp: &Sexp) -> String {
    let mut buf = Vec::new();
    let _ = prettyprint(sexp, &mut buf, 0, false).unwrap();
    String::from_utf8(buf).unwrap()
}

pub fn prettyprint<W: io::Write>(
    sexp: &Sexp,
    f: &mut W,
    indent: usize,
    newline: bool,
) -> Result<(), io::Error> {
    use std::cmp;

    if newline {
        write!(f, "\n")?;
        for _ in 0..cmp::min(8, indent) {
            write!(f, "{:>4}", "")?;
        }
    }

    match *sexp {
        Sexp::Atom(ref a) => write!(f, "{}", a),
        Sexp::Tuple(ref t) => {
            write!(f, "(")?;
            for (i, expr) in t.iter().enumerate() {
                if i > 0 {
                    write!(f, " ")?;
                }
                prettyprint(expr, f, indent, false)?;
            }
            write!(f, ")")
        }
        Sexp::Array(ref t) => {
            if sexp.is_flat() && t.len() < 5 {
                write!(f, "{}", sexp)
            } else {
                write!(f, "[")?;
                for (_, expr) in t.iter().enumerate() {
                    prettyprint(expr, f, indent + 1, true)?;
                }
                write!(f, "]")
            }
        }
        Sexp::Map(ref t) => {
            write!(f, "{}", "{")?;
            for (_, expr) in t.iter().enumerate() {
                prettyprint(&expr.0, f, indent + 1, true)?;
                write!(f, " ")?;
                prettyprint(&expr.1, f, indent + 1, false)?;
            }
            write!(f, "\n")?;
            for _ in 0..cmp::min(8, indent) {
                write!(f, "{:>4}", "")?;
            }
            write!(f, "{}", "}")
        }
    }
}

impl fmt::Display for Sexp {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            Sexp::Atom(ref a) => write!(f, "{}", a),
            Sexp::Tuple(ref t) => {
                write!(f, "(")?;
                for (i, expr) in t.iter().enumerate() {
                    let space = if i > 0 { " " } else { "" };
                    write!(f, "{}{}", space, expr)?;
                }
                write!(f, ")")
            }
            Sexp::Array(ref t) => {
                write!(f, "[")?;
                for (i, expr) in t.iter().enumerate() {
                    let space = if i > 0 { " " } else { "" };
                    write!(f, "{}{}", space, expr)?;
                }
                write!(f, "]")
            }
            Sexp::Map(ref t) => {
                write!(f, "{}", "{")?;
                for (i, expr) in t.iter().enumerate() {
                    let space = if i > 0 { " " } else { "" };
                    write!(f, "{}{} {}", space, expr.0, expr.1)?;
                }
                write!(f, "{}", "}")
            }
        }
    }
}

#[test]
fn test_display() {
    assert_eq!("12345", &format!("{}", Sexp::Atom(Atom::UInt(12345))));
    assert_eq!("1.0", &format!("{}", Sexp::Atom(Atom::Float(1.0))));

    assert_eq!(
        "(12345)",
        &format!("{}", Sexp::Tuple(vec![Sexp::Atom(Atom::UInt(12345))]))
    );
    assert_eq!(
        "(12345 abc)",
        &format!(
            "{}",
            Sexp::Tuple(vec![
                Sexp::Atom(Atom::UInt(12345)),
                Sexp::Atom(Atom::Str("abc".to_string()))
            ])
        )
    );
    assert_eq!(
        "(12345 (abc))",
        &format!(
            "{}",
            Sexp::Tuple(vec![
                Sexp::Atom(Atom::UInt(12345)),
                Sexp::Tuple(vec![Sexp::Atom(Atom::Str("abc".to_string()))])
            ])
        )
    );
}

#[test]
fn test_from() {
    assert_eq!(Sexp::Atom(Atom::UInt(123)), Sexp::from(123u64));
    assert_eq!(Sexp::Atom(Atom::SInt(123)), Sexp::from(123i64));
    assert_eq!(
        Sexp::Atom(Atom::Str("test".to_string())),
        Sexp::from("test")
    );
    assert_eq!(Sexp::Atom(Atom::Float(123.45)), Sexp::from(123.45));
    assert_eq!(
        Sexp::Tuple(vec![Sexp::Atom(Atom::Float(123.45))]),
        Sexp::from((123.45,))
    );
    assert_eq!(
        Sexp::Array(vec![Sexp::Atom(Atom::Float(123.45))]),
        Sexp::from(vec![123.45])
    );
}

#[test]
fn test_parse() {
    assert_eq!(
        Ok(Sexp::from(("abc", 123u64, ("-", 123.43, 11.0)))),
        Sexp::parse("(abc 123 (- 123.43 11.0))")
    );
}

#[test]
fn test_parse_toplevel() {
    assert_eq!(Sexp::parse("{a 1 b 2}"), Sexp::parse_toplevel("a 1 b 2"));
}

#[test]
fn test_map() {
    let map = Sexp::parse("{a 1 b 2}").unwrap().into_map().unwrap();
    assert_eq!(true, map.contains_key("a"));
    assert_eq!(true, map.contains_key("b"));
    assert_eq!(false, map.contains_key("c"));

    assert_eq!(
        Err("duplicate key"),
        Sexp::parse("{a 1 b 2 a 1}").unwrap().into_map()
    );
    assert_eq!(
        Err("key has to be a string"),
        Sexp::parse("{1 1 b 2 a 1}").unwrap().into_map()
    );
}