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
pub use token_parser_derive::*;

#[derive(Debug)]
pub enum Error {
    NotEnoughElements(usize),
    TooManyElements(usize),
    ListNotAllowed,
    SymbolNotAllowed,
    StringParsing,
    InvalidElement,
}

pub type Result<T> = std::result::Result<T, Error>;

pub enum Unit<I: Iterator>
where
    I::Item: Into<Unit<I>>,
{
    Symbol(String),
    Parser(Parser<I>),
}

impl<I: Iterator> Unit<I>
where
    I::Item: Into<Unit<I>>,
{
    pub fn symbol(self) -> Result<String> {
        use Unit::*;
        match self {
            Symbol(name) => Ok(name),
            Parser(_) => Err(Error::ListNotAllowed),
        }
    }

    pub fn parser(self) -> Result<Parser<I>> {
        use Unit::*;
        match self {
            Symbol(_) => Err(Error::SymbolNotAllowed),
            Parser(parser) => Ok(parser),
        }
    }
}

pub trait Parsable<C>: Sized {
    fn parse_symbol(_name: String, _context: &C) -> Result<Self> {
        Err(Error::SymbolNotAllowed)
    }

    fn parse_list<I: Iterator>(_parser: &mut Parser<I>, _context: &C) -> Result<Self>
    where
        I::Item: Into<Unit<I>>,
    {
        Err(Error::ListNotAllowed)
    }
}

fn parse<C, P: Parsable<C>, I: Iterator>(unit: Unit<I>, context: &C) -> Result<P>
where
    I::Item: Into<Unit<I>>,
{
    use Unit::*;
    match unit {
        Symbol(name) => Parsable::parse_symbol(name, context),
        Parser(mut parser) => parser.parse_rest(context),
    }
}

impl<C, T: Parsable<C>> Parsable<C> for Box<T> {
    fn parse_symbol(name: String, context: &C) -> Result<Self> {
        Ok(Box::new(Parsable::parse_symbol(name, context)?))
    }

    fn parse_list<I: Iterator>(parser: &mut Parser<I>, context: &C) -> Result<Self>
    where
        I::Item: Into<Unit<I>>,
    {
        Ok(Box::new(parser.parse_list(context)?))
    }
}

impl<C, T: Parsable<C>> Parsable<C> for Vec<T> {
    fn parse_list<I: Iterator>(parser: &mut Parser<I>, context: &C) -> Result<Self>
    where
        I::Item: Into<Unit<I>>,
    {
        let Parser { form, count } = parser;
        let result = form
            .map(|token| {
                *count += 1;
                parse(token.into(), context)
            })
            .collect();
        result
    }
}

impl<C> Parsable<C> for String {
    fn parse_symbol(name: String, _context: &C) -> Result<Self> {
        Ok(name)
    }
}

#[macro_export]
macro_rules! derive_symbol_parsable {
    ($t:ty) => {
        impl<C> Parsable<C> for $t {
            fn parse_symbol(name: String, _context: &C) -> Result<Self> {
                if let Some(value) = name.parse().ok() {
                    Ok(value)
                } else {
                    Err(Error::StringParsing)
                }
            }
        }
    };
    ($t:ty, $($rest:ty),+) => {
        derive_symbol_parsable!($t);
        derive_symbol_parsable!($($rest),+);
    };
}

derive_symbol_parsable!(i8, i16, i32, i64, i128);
derive_symbol_parsable!(u8, u16, u32, u64, u128);
derive_symbol_parsable!(f32, f64);
derive_symbol_parsable!(usize);
derive_symbol_parsable!(bool);

pub struct Parser<I: Iterator> {
    form: I,
    count: usize,
}

impl<I: Iterator> Parser<I>
where
    I::Item: Into<Unit<I>>,
{
    pub fn new(form: I) -> Self {
        Self { form, count: 0 }
    }

    pub fn parse_next<C, T: Parsable<C>>(&mut self, context: &C) -> Result<T> {
        self.count += 1;
        if let Some(token) = self.form.next() {
            parse(token.into(), context)
        } else {
            Result::Err(Error::NotEnoughElements(self.count))
        }
    }

    pub fn parse_rest<C, T: Parsable<C>>(&mut self, context: &C) -> Result<T> {
        let result = self.parse_list(context);
        if let Some(_) = self.form.next() {
            let mut count = 1;
            while let Some(_) = self.form.next() {
                count += 1;
            }
            Err(Error::TooManyElements(count))
        } else {
            result
        }
    }

    pub fn parse_list<C, T: Parsable<C>>(&mut self, context: &C) -> Result<T> {
        Parsable::parse_list(self, context)
    }
}

impl<I: Iterator> Iterator for Parser<I>
where
    I::Item: Into<Unit<I>>,
{
    type Item = Result<Parser<I>>;

    fn next(&mut self) -> Option<Result<Parser<I>>> {
        self.count += 1;
        let unit: Unit<I> = self.form.next()?.into();
        Some(unit.parser())
    }
}