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
use crate::err::longer;
use crate::iter::LCChars;
use crate::ptrait::*;

#[derive(Clone)]
pub struct Exact<A: Parser> {
    n: usize,
    a: A,
}

/// ```
/// use gobble::*;
/// let it = LCChars::str("hello fish car cat");
/// let (_,v,_) = do_exact(&it,&common_ident.then_ig(" "),3).unwrap();
/// assert_eq!(v,vec!["hello","fish","car"]);
///
/// ```
pub fn do_exact<'a, A: Parser>(it: &LCChars<'a>, a: &A, n: usize) -> ParseRes<'a, Vec<A::Out>> {
    let mut i = it.clone();
    let mut res = Vec::new();
    for _ in 0..n {
        match a.parse(&i) {
            Ok((it2, pres, _)) => {
                res.push(pres);
                i = it2;
            }
            Err(e) => return Err(e.wrap(i.err_p(a))),
        }
    }
    return Ok((i, res, None));
}

impl<A: Parser> Parser for Exact<A> {
    type Out = Vec<A::Out>;
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, Vec<A::Out>> {
        do_exact(it, &self.a, self.n)
    }
}

pub struct Reflect<A, B, C> {
    a: A,
    b: B,
    c: C,
}
impl<A, B, C> Parser for Reflect<A, B, C>
where
    A: Parser,
    B: Parser,
    C: Parser,
{
    type Out = (Vec<A::Out>, B::Out, Vec<C::Out>);
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
        let (ni, (va, b), _) = do_repeat_until(it, &self.a, &self.b)?;
        let (fi, vc, _) = do_exact(&ni, &self.c, va.len())?;
        Ok((fi, (va, b, vc), None))
    }
}

/// A function for making sure number match on both sides of an equals
///
/// ```rust
/// use gobble::*;
/// let p = reflect(s_("("),Alpha.min_n(1),s_(")"));
///
/// let (av,b,cv) =p.parse_s("(((help)))").unwrap();
///
/// assert_eq!(av,vec!["(","(","("]);
/// assert_eq!(b,"help".to_string());
/// assert_eq!(cv,vec![")",")",")"]);
///
/// let r2 = p.parse_s("(((no))");
/// assert!(r2.is_err());
/// ```
///
pub fn reflect<A, B, C>(a: A, b: B, c: C) -> Reflect<A, B, C>
where
    A: Parser,
    B: Parser,
    C: Parser,
{
    Reflect { a, b, c }
}

/// Repeat an exact number of times
///
/// ```
/// use gobble::*;
/// let p = repeat_n(common_int.then_ig(","),5);
/// let v = p.parse_s("7,6,5,4,3,2,1").unwrap();
/// assert_eq!(v,vec![7,6,5,4,3]);
/// ```
#[deprecated(since = "0.4.0", note = "Use 'exact' instead")]
pub fn repeat_n<A: Parser>(a: A, n: usize) -> Exact<A> {
    Exact { a, n }
}

pub fn exact<A: Parser>(a: A, n: usize) -> Exact<A> {
    Exact { a, n }
}

fn do_sep<'a, A: Parser, B: Parser>(
    i: &LCChars<'a>,
    a: &A,
    b: &B,
    min: usize,
) -> ParseRes<'a, Vec<A::Out>> {
    let mut res = Vec::new();
    let mut ri = i.clone();
    loop {
        ri = match a.parse(&ri) {
            Ok((r, v, _)) => {
                res.push(v);
                r
            }
            Err(_) => {
                if res.len() == 0 && min == 0 {
                    let eo = ri.err_p_o(a);
                    return Ok((ri, res, eo));
                }
                return i.err_p_r(a);
            }
        };
        //try sep if not found, return
        ri = match b.parse(&ri) {
            Ok((r, _, _)) => r,
            Err(e) => {
                if res.len() < min {
                    return ri.err_p_r(b);
                } else {
                    return Ok((ri, res, Some(e)));
                }
            }
        };
    }
}

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

impl<A, B> Parser for SepStar<A, B>
where
    A: Parser,
    B: Parser,
{
    type Out = Vec<A::Out>;
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
        do_sep(it, &self.a, &self.b, 0)
    }
}

pub fn sep<A: Parser, B: Parser>(a: A, b: B) -> SepStar<A, B> {
    SepStar { a, b }
}
pub fn sep_plus<A: Parser, B: Parser>(a: A, b: B) -> SepPlus<A, B> {
    SepPlus { a, b }
}

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

impl<A, B> Parser for SepPlus<A, B>
where
    A: Parser,
    B: Parser,
{
    type Out = Vec<A::Out>;
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
        do_sep(it, &self.a, &self.b, 1)
    }
}

pub fn do_rep<'a, A: Parser>(i: &LCChars<'a>, a: &A, min: usize) -> ParseRes<'a, Vec<A::Out>> {
    let mut ri = i.clone();
    let mut res = Vec::new();
    loop {
        ri = match a.parse(&ri) {
            Ok((r, v, _)) => {
                res.push(v);
                r
            }
            Err(_) => {
                if res.len() < min {
                    return i.err_p_r(a);
                } else {
                    let eo = ri.err_p_o(a);
                    return Ok((ri, res, eo));
                }
            }
        }
    }
}

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

impl<A: Parser> Parser for RepStar<A> {
    type Out = Vec<A::Out>;
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
        do_rep(i, &self.a, 0)
    }
}

pub fn rep<A: Parser>(a: A) -> RepStar<A> {
    RepStar { a }
}

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

impl<A: Parser> Parser for RepPlus<A> {
    type Out = Vec<A::Out>;
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
        do_rep(i, &self.a, 1)
    }
}

pub fn rep_plus<A: Parser>(a: A) -> RepPlus<A> {
    RepPlus { a }
}

fn do_repeat_until<'a, A: Parser, B: Parser>(
    it: &LCChars<'a>,
    a: &A,
    b: &B,
) -> ParseRes<'a, (Vec<A::Out>, B::Out)> {
    let mut ri = it.clone();
    let mut res = Vec::new();
    loop {
        let b_err = match b.parse(&ri) {
            Ok((r, v, _)) => return Ok((r, (res, v), None)),
            Err(e) => e,
        };
        ri = match a.parse(&ri) {
            Ok((r, v, _)) => {
                res.push(v);
                r
            }
            Err(e) => return Err(longer(e, b_err).wrap(ri.err("Repeat"))),
        }
    }
}

pub struct RepUntil<A, B> {
    a: A,
    b: B,
}

impl<A: Parser, B: Parser> Parser for RepUntil<A, B> {
    type Out = (Vec<A::Out>, B::Out);
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
        do_repeat_until(i, &self.a, &self.b)
    }
}

///Repeats the first parser until the second parser.
///returns a vec of the first parsers results
pub fn repeat_until<A: Parser, B: Parser>(a: A, b: B) -> RepUntil<A, B> {
    RepUntil { a, b }
}

pub fn repeat_until_ig<A: Parser, B: Parser>(a: A, b: B) -> impl Parser<Out = Vec<A::Out>> {
    repeat_until(a, b).map(|(a, _)| a)
}

pub struct SepUntil<A, B, C> {
    a: A,
    b: B,
    c: C,
}

impl<A, B, C> Parser for SepUntil<A, B, C>
where
    A: Parser,
    B: Parser,
    C: Parser,
{
    type Out = Vec<A::Out>;
    fn parse<'a>(&self, i: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
        let mut ri = i.clone();
        let mut res = Vec::new();
        match self.c.parse(&ri) {
            Ok((r, _, _)) => return Ok((r, res, None)),
            Err(_) => {}
        }
        loop {
            ri = match self.a.parse(&ri) {
                Ok((r, v, _)) => {
                    res.push(v);
                    r
                }
                Err(e) => return Err(e),
            };
            let c_err = match self.c.parse(&ri) {
                Ok((r, _, _)) => return Ok((r, res, None)),
                Err(e) => e,
            };
            ri = match self.b.parse(&ri) {
                Ok((r, _, _)) => r,
                Err(e) => return Err(longer(e, c_err).wrap(ri.err_p(self))),
            }
        }
    }
}

///Allows for better errors looping until a specific finish. It does not return the close or the
///seperators the
///close is expected to be some kind of closer like '}'
///If you need the close you will have to use sep(..).then(..) though the errors will be less
///nice
pub fn sep_until<A, B, C>(a: A, b: B, c: C) -> SepUntil<A, B, C>
where
    A: Parser,
    B: Parser,
    C: Parser,
{
    SepUntil { a, b, c }
}

#[cfg(test)]
pub mod test {
    use super::*;
    //use crate::ptrait::*;
    use crate::*;
    #[test]
    pub fn test_reflecter() {
        let (av, b, cv) = reflect(s_("("), (Alpha, NumDigit).plus(), s_(")"))
            .parse_s("(((help)))")
            .unwrap();

        assert_eq!(av, vec!["(", "(", "("]);
        assert_eq!(b, "help".to_string());
        assert_eq!(cv, vec![")", ")", ")"]);
    }
}