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
use super::super::Primitive;
use super::SExp::{self, Atom, Null, Pair};

/// Construct an S-Expression from a list of expressions.
///
/// # Example
/// ```
/// use parsley::{sexp, SExp};
///
/// assert_eq!(
///     sexp![5, "potato", true],
///     SExp::from((5, ("potato", (true, ()))))
/// );
/// ```
#[macro_export]
macro_rules! sexp {
    ( $( $e:expr ),* ) => {{
        $crate::SExp::from(&[ $( $crate::SExp::from($e) ),* ][..])
    }};
}

impl<T> From<T> for SExp
where
    Primitive: From<T>,
{
    fn from(val: T) -> Self {
        Atom(Primitive::from(val))
    }
}

impl From<()> for SExp {
    fn from(_: ()) -> Self {
        Null
    }
}

impl<T> From<(T,)> for SExp
where
    SExp: From<T>,
{
    fn from((v,): (T,)) -> Self {
        Pair {
            head: Box::new(Self::from(v)),
            tail: Box::new(Null),
        }
    }
}

impl<T, U> From<(T, U)> for SExp
where
    SExp: From<T> + From<U>,
{
    fn from((v1, v2): (T, U)) -> Self {
        Pair {
            head: Box::new(Self::from(v1)),
            tail: Box::new(Self::from(v2)),
        }
    }
}

impl<T> From<&[T]> for SExp
where
    T: Into<SExp> + Clone,
{
    fn from(ary: &[T]) -> Self {
        ary.iter().cloned().map(T::into).collect()
    }
}

impl<T> From<Vec<T>> for SExp
where
    T: Into<SExp>,
{
    fn from(ary: Vec<T>) -> Self {
        ary.into_iter().map(T::into).collect()
    }
}