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
use crate::err::{ECode, ParseError};
use crate::iter::LCChars;
use std::cmp::Ordering;
use std::marker::PhantomData;

pub type ParseRes<'a, V> = Result<(LCChars<'a>, V), ParseError>;

/// The core trait for parsing
pub trait Parser<V>: Sized {
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, V>;
    fn parse_s(&self, s: &str) -> Result<V, ParseError> {
        self.parse(&LCChars::str(s)).map(|(_, v)| v)
    }
    fn parse_sn<'a>(&self, s: &'a str) -> Result<(&'a str, V), ParseError> {
        self.parse(&LCChars::str(s)).map(|(i, v)| (i.as_str(), v))
    }
    /// returns a parser that will combine the results of this and the given parser
    /// into a tuple
    fn then<P: Parser<V2>, V2>(self, p: P) -> Then<Self, P> {
        Then { one: self, two: p }
    }

    /// returns a Parser that will require the given parser completes, but ignores its result
    /// useful for dropping brackets and whitespace
    fn then_ig<P: Parser<V2>, V2>(self, p: P) -> ThenIg<Self, P, V, V2> {
        ThenIg {
            one: self,
            two: p,
            pha: PhantomData,
            phb: PhantomData,
        }
    }
    /// returns a Parser that will require this parser completes, but only return the
    /// result of the given parser
    /// useful for dropping brackets and whitespace etc
    fn ig_then<P: Parser<V2>, V2>(self, p: P) -> IgThen<Self, P, V, V2> {
        IgThen {
            one: self,
            two: p,
            pha: PhantomData,
            phb: PhantomData,
        }
    }
    /// Returns a Parser that will try both child parsers, (A first) and return the first successfl
    /// result
    fn or<P: Parser<V>>(self, p: P) -> Or<Self, P> {
        Or { a: self, b: p }
    }

    /// Returns a Parser that converts the result of a successful parse to a different type.
    /// Much like map on iterators and Result
    fn map<F: Fn(V) -> V2, V2>(self, f: F) -> Map<Self, V, V2, F> {
        Map {
            a: self,
            f,
            phav: PhantomData,
            phb: PhantomData,
        }
    }
    /// Returns a Parser that converts the result of a successful parse to a different type.
    /// however the map function can fail and return a result
    /// The Error type should be err::ECode, this does not have line associated. That will
    /// be attacked by the TryMap object
    /// so this will pass that error up correctly
    fn try_map<F: Fn(V) -> Result<V2, ECode>, V2>(self, f: F) -> TryMap<Self, V, V2, F> {
        TryMap {
            a: self,
            f,
            phav: PhantomData,
            phb: PhantomData,
        }
    }
    fn asv<R: Clone>(self, r: R) -> As<Self, V, R> {
        As {
            a: self,
            r,
            pha: PhantomData,
        }
    }

    fn map_err<F: Fn(ECode) -> ECode>(self, f: F) -> MapErr<Self, V, F> {
        MapErr {
            p: self,
            f,
            phv: PhantomData,
        }
    }

    fn brk(self) -> Break<Self, V> {
        Break {
            p: self,
            phv: PhantomData,
        }
    }
}

impl<V, F: for<'a> Fn(&LCChars<'a>) -> ParseRes<'a, V>> Parser<V> for F {
    fn parse<'b>(&self, i: &LCChars<'b>) -> ParseRes<'b, V> {
        self(i)
    }
}

impl Parser<&'static str> for &'static str {
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, &'static str> {
        crate::reader::do_tag(i, self)
    }
}

impl Parser<char> for char {
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, char> {
        let mut i2 = i.clone();
        match i2.next() {
            Some(c) if c == *self => Ok((i2, *self)),
            v => i2.err_cr(ECode::Char(*self, v)),
        }
    }
}

#[derive(Clone)]
pub struct Then<A, B> {
    one: A,
    two: B,
}

impl<A, B, AV, BV> Parser<(AV, BV)> for Then<A, B>
where
    A: Parser<AV>,
    B: Parser<BV>,
{
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, (AV, BV)> {
        let (i, v1) = self.one.parse(i)?;
        let (i, v2) = self.two.parse(&i)?;
        Ok((i, (v1, v2)))
    }
}

#[derive(Clone)]
pub struct ThenIg<A, B, AV, BV> {
    one: A,
    two: B,
    pha: PhantomData<AV>,
    phb: PhantomData<BV>,
}

impl<A, B, AV, BV> Parser<AV> for ThenIg<A, B, AV, BV>
where
    A: Parser<AV>,
    B: Parser<BV>,
{
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, AV> {
        let (i, v1) = self.one.parse(i)?;
        let (i, _) = self.two.parse(&i)?;
        Ok((i, v1))
    }
}

#[derive(Clone)]
pub struct IgThen<A, B, AV, BV> {
    one: A,
    two: B,
    pha: PhantomData<AV>,
    phb: PhantomData<BV>,
}

impl<A, B, AV, BV> Parser<BV> for IgThen<A, B, AV, BV>
where
    A: Parser<AV>,
    B: Parser<BV>,
{
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, BV> {
        let (i, _) = self.one.parse(i)?;
        let (i, v2) = self.two.parse(&i)?;
        Ok((i, v2))
    }
}

#[derive(Clone)]
pub struct Or<A, B> {
    a: A,
    b: B,
}

impl<A, B, V> Parser<V> for Or<A, B>
where
    A: Parser<V>,
    B: Parser<V>,
{
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, V> {
        match self.a.parse(i) {
            Ok((r, v)) => Ok((r, v)),
            Err(e) if e.is_break() => Err(e),
            Err(e) => match self.b.parse(i) {
                Ok((r, v)) => Ok((r, v)),
                Err(e2) if e2.is_break() => Err(e2),
                Err(e2) => match e.partial_cmp(&e2) {
                    Some(Ordering::Equal) | None => i.err_cr(ECode::Or(Box::new(e), Box::new(e2))),
                    Some(Ordering::Less) => Err(e2),
                    Some(Ordering::Greater) => Err(e),
                },
            },
        }
    }
}

#[derive(Clone)]
pub struct Map<A: Parser<AV>, AV, B, F: Fn(AV) -> B> {
    a: A,
    f: F,
    phb: PhantomData<B>,
    phav: PhantomData<AV>,
}

impl<A: Parser<AV>, AV, B, F: Fn(AV) -> B> Parser<B> for Map<A, AV, B, F> {
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, B> {
        let (ri, v) = self.a.parse(i)?;
        Ok((ri, (self.f)(v)))
    }
}

#[derive(Clone)]
pub struct TryMap<A: Parser<AV>, AV, B, F: Fn(AV) -> Result<B, ECode>> {
    a: A,
    f: F,
    phb: PhantomData<B>,
    phav: PhantomData<AV>,
}

impl<A: Parser<AV>, AV, B, F: Fn(AV) -> Result<B, ECode>> Parser<B> for TryMap<A, AV, B, F> {
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, B> {
        let (ri, v) = self.a.parse(i)?;
        match (self.f)(v) {
            Ok(v2) => Ok((ri, v2)),
            Err(e) => ri.err_cr(e),
        }
    }
}

pub struct As<A: Parser<AV>, AV, R: Clone> {
    a: A,
    pha: PhantomData<AV>,
    r: R,
}
impl<A: Parser<AV>, AV, R: Clone> Parser<R> for As<A, AV, R> {
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, R> {
        let (ri, _) = self.a.parse(it)?;
        Ok((ri, self.r.clone()))
    }
}

pub struct MapErr<P: Parser<V>, V, F: Fn(ECode) -> ECode> {
    p: P,
    f: F,
    phv: PhantomData<V>,
}

impl<P: Parser<V>, V, F: Fn(ECode) -> ECode> Parser<V> for MapErr<P, V, F> {
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, V> {
        match self.p.parse(it) {
            Err(mut e) => {
                e.code = (self.f)(e.code);
                Err(e)
            }
            ov => ov,
        }
    }
}
pub struct Break<P: Parser<V>, V> {
    p: P,
    phv: PhantomData<V>,
}

impl<P: Parser<V>, V> Parser<V> for Break<P, V> {
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, V> {
        match self.p.parse(it) {
            Err(mut e) => {
                e.code = e.code.brk();
                Err(e)
            }
            ov => ov,
        }
    }
}
#[cfg(test)]
pub mod test {
    use super::*;
    use crate::common::*;
    #[test]
    fn test_strs_can_be_parsers() {
        let p = "(((".ig_then(common_int);
        let n = p.parse_s("(((32").unwrap();
        assert_eq!(n, 32);
    }
}