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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use crate::err::*;
use crate::iter::*;
use crate::parser::*;

//use crate::reader::*;

pub trait CharBool: Sized {
    fn char_bool(&self, c: char) -> bool;
    fn expected(&self) -> Expected {
        Expected::Str(std::any::type_name::<Self>())
    }
    fn one(self) -> OneChar<Self> {
        OneChar { cb: self }
    }
    fn star(self) -> CharStar<Self> {
        CharStar { cb: self }
    }
    /// min_n not min to avoid ambiguity with std::cmp::Ord
    fn min_n(self, min: usize) -> CharMin<Self> {
        CharMin { cb: self, min }
    }

    fn plus(self) -> CharPlus<Self> {
        CharPlus { cb: self }
    }

    fn istar(self) -> ICharStar<Self> {
        ICharStar { cb: self }
    }
    fn iplus(self) -> ICharPlus<Self> {
        ICharPlus { cb: self }
    }

    fn iexact(self, n: usize) -> ICharExact<Self> {
        ICharExact { cb: self, n }
    }

    ///```rust
    /// use bogobble::*;
    /// assert_eq!(
    ///     Any.except("_").min_n(4).parse_s("asedf_wes"),
    ///     Ok("asedf")
    ///     );
    ///```
    fn except<E: CharBool>(self, e: E) -> CharsExcept<Self, E> {
        CharsExcept { a: self, e }
    }

    fn exact(self, n: usize) -> CharExact<Self> {
        CharExact { cb: self, n }
    }

    fn until<'a, P: Parser<'a>>(self, end: P) -> CharUntil<Self, P> {
        CharUntil { a: self, end }
    }
}

pub struct CharNot<C: CharBool> {
    c: C,
}

pub fn not<C: CharBool>(c: C) -> CharNot<C> {
    CharNot { c }
}

impl<C: CharBool> CharBool for CharNot<C> {
    fn char_bool(&self, c: char) -> bool {
        !self.c.char_bool(c)
    }
    fn expected(&self) -> Expected {
        Expected::Not(Box::new(self.c.expected()))
    }
}

pub fn is_alpha(c: char) -> bool {
    (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
}
char_bool!(Alpha, is_alpha);

pub fn is_num(c: char) -> bool {
    c >= '0' && c <= '9'
}
char_bool!(NumDigit, is_num);

char_bool!(Any, |_| true);

pub fn is_hex(c: char) -> bool {
    is_num(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
char_bool!(HexDigit, is_hex);

char_bool!(WS, "\t ");
char_bool!(WSL, " \t\n\r");

impl CharBool for char {
    fn char_bool(&self, c: char) -> bool {
        *self == c
    }
    fn expected(&self) -> Expected {
        Expected::Char(*self)
    }
}

impl CharBool for &'static str {
    fn char_bool(&self, c: char) -> bool {
        self.contains(c)
    }
    fn expected(&self) -> Expected {
        Expected::CharIn(self)
    }
}

impl<F: Fn(char) -> bool> CharBool for F {
    fn char_bool(&self, c: char) -> bool {
        (self)(c)
    }
}

impl<A: CharBool, B: CharBool> CharBool for (A, B) {
    fn char_bool(&self, c: char) -> bool {
        self.0.char_bool(c) || self.1.char_bool(c)
    }
    fn expected(&self) -> Expected {
        Expected::OneOf(vec![self.0.expected(), self.1.expected()])
    }
}

impl<A: CharBool, B: CharBool, C: CharBool> CharBool for (A, B, C) {
    fn char_bool(&self, c: char) -> bool {
        self.0.char_bool(c) || self.1.char_bool(c) || self.2.char_bool(c)
    }
    fn expected(&self) -> Expected {
        Expected::OneOf(vec![
            self.0.expected(),
            self.1.expected(),
            self.2.expected(),
        ])
    }
}

impl<A, B, C, D> CharBool for (A, B, C, D)
where
    A: CharBool,
    B: CharBool,
    C: CharBool,
    D: CharBool,
{
    fn char_bool(&self, c: char) -> bool {
        self.0.char_bool(c) || self.1.char_bool(c) || self.2.char_bool(c) || self.3.char_bool(c)
    }
    fn expected(&self) -> Expected {
        Expected::OneOf(vec![
            self.0.expected(),
            self.1.expected(),
            self.2.expected(),
            self.3.expected(),
        ])
    }
}

impl<A, B, C, D, E> CharBool for (A, B, C, D, E)
where
    A: CharBool,
    B: CharBool,
    C: CharBool,
    D: CharBool,
    E: CharBool,
{
    fn char_bool(&self, c: char) -> bool {
        self.0.char_bool(c)
            || self.1.char_bool(c)
            || self.2.char_bool(c)
            || self.3.char_bool(c)
            || self.4.char_bool(c)
    }
    fn expected(&self) -> Expected {
        Expected::OneOf(vec![
            self.0.expected(),
            self.1.expected(),
            self.2.expected(),
            self.3.expected(),
            self.4.expected(),
        ])
    }
}

impl<A, B, C, D, E, F> CharBool for (A, B, C, D, E, F)
where
    A: CharBool,
    B: CharBool,
    C: CharBool,
    D: CharBool,
    E: CharBool,
    F: CharBool,
{
    fn char_bool(&self, c: char) -> bool {
        self.0.char_bool(c)
            || self.1.char_bool(c)
            || self.2.char_bool(c)
            || self.3.char_bool(c)
            || self.4.char_bool(c)
            || self.5.char_bool(c)
    }
    fn expected(&self) -> Expected {
        Expected::OneOf(vec![
            self.0.expected(),
            self.1.expected(),
            self.2.expected(),
            self.3.expected(),
            self.4.expected(),
            self.5.expected(),
        ])
    }
}
pub struct CharsExcept<A: CharBool, E: CharBool> {
    a: A,
    e: E,
}

impl<A: CharBool, E: CharBool> CharBool for CharsExcept<A, E> {
    fn char_bool(&self, c: char) -> bool {
        self.a.char_bool(c) && !self.e.char_bool(c)
    }
    fn expected(&self) -> Expected {
        self.a
            .expected()
            .join(Expected::Not(Box::new(self.e.expected())))
    }
}

pub fn do_one_char<'a, CB: CharBool>(i: &PIter<'a>, cb: &CB) -> ParseRes<'a, char> {
    let mut i2 = i.clone();
    let ic = i2.next().ok_or(i2.err(cb.expected()))?;
    if cb.char_bool(ic) {
        Ok((i2, ic, None))
    } else {
        i.err_r(cb.expected())
    }
}

pub struct OneChar<CB: CharBool> {
    cb: CB,
}

impl<'a, CB: CharBool> Parser<'a> for OneChar<CB> {
    type Out = char;
    fn parse(&self, it: &PIter<'a>) -> ParseRes<'a, char> {
        do_one_char(it, &self.cb)
    }
}

pub fn one_char<C: CharBool>(cb: C) -> OneChar<C> {
    OneChar { cb }
}

pub fn do_chars<'a, CB: CharBool>(
    i: &PIter<'a>,
    cb: &CB,
    min: usize,
    exact: bool,
) -> ParseRes<'a, ()> {
    let mut it = i.clone();
    let mut done = 0;
    loop {
        let it2 = it.clone();
        match it.next() {
            Some(c) if cb.char_bool(c) => {
                //println!("do_chars CHAR = {}", c);
                done += 1;
                if done == min && exact {
                    return Ok((it, (), None));
                }
            }
            Some(_) | None => {
                if done >= min {
                    let eo = Some(it2.err(cb.expected()));
                    return Ok((it2, (), eo));
                } else {
                    return it2.err_r(cb.expected());
                }
            }
        }
    }
}

pub struct ICharStar<C: CharBool> {
    cb: C,
}
impl<'a, CB: CharBool> Parser<'a> for ICharStar<CB> {
    type Out = ();
    fn parse(&self, i: &PIter<'a>) -> ParseRes<'a, Self::Out> {
        do_chars(i, &self.cb, 0, false)
    }
}

pub struct ICharPlus<C: CharBool> {
    cb: C,
}
impl<'a, CB: CharBool> Parser<'a> for ICharPlus<CB> {
    type Out = ();
    fn parse(&self, i: &PIter<'a>) -> ParseRes<'a, Self::Out> {
        do_chars(i, &self.cb, 1, false)
    }
}

pub struct ICharExact<C: CharBool> {
    cb: C,
    n: usize,
}
impl<'a, CB: CharBool> Parser<'a> for ICharExact<CB> {
    type Out = ();
    fn parse(&self, i: &PIter<'a>) -> ParseRes<'a, Self::Out> {
        do_chars(i, &self.cb, self.n, true)
    }
}
#[derive(Clone)]
pub struct CharStar<C: CharBool> {
    cb: C,
}

impl<'a, CB: CharBool> Parser<'a> for CharStar<CB> {
    type Out = &'a str;
    fn parse(&self, i: &PIter<'a>) -> ParseRes<'a, Self::Out> {
        do_chars(i, &self.cb, 0, false).map_str(i)
    }
}

#[derive(Clone)]
pub struct CharPlus<C: CharBool> {
    cb: C,
}

impl<'a, CB: CharBool> Parser<'a> for CharPlus<CB> {
    type Out = &'a str;
    fn parse(&self, i: &PIter<'a>) -> ParseRes<'a, &'a str> {
        do_chars(i, &self.cb, 1, false).map_str(i)
    }
}

#[derive(Clone)]
pub struct CharExact<CB: CharBool> {
    cb: CB,
    n: usize,
}

impl<'a, A: CharBool> Parser<'a> for CharExact<A> {
    type Out = &'a str;
    fn parse(&self, i: &PIter<'a>) -> ParseRes<'a, Self::Out> {
        do_chars(i, &self.cb, self.n, true).map_str(i)
    }
}

#[derive(Clone)]
pub struct CharMin<A: CharBool> {
    cb: A,
    min: usize,
}

impl<'a, A: CharBool> Parser<'a> for CharMin<A> {
    type Out = &'a str;
    fn parse(&self, i: &PIter<'a>) -> ParseRes<'a, Self::Out> {
        do_chars(i, &self.cb, self.min, false).map_str(i)
    }
}

#[derive(Clone)]
pub struct CharUntil<A: CharBool, E> {
    a: A,
    end: E,
}

impl<'a, A: CharBool, E: Parser<'a>> Parser<'a> for CharUntil<A, E> {
    type Out = (&'a str, E::Out);
    fn parse(&self, i_start: &PIter<'a>) -> ParseRes<'a, Self::Out> {
        let mut it = i_start.clone();
        let mut a_stop = it.index();
        loop {
            match self.end.parse(&it) {
                Ok((i, v, e)) => return Ok((i, (i_start.str_to(a_stop), v), e)),
                Err(e1) => match it.next() {
                    Some(c) if self.a.char_bool(c) => a_stop = it.index(),
                    _ => return Err(e1.join(it.err(self.a.expected()))),
                },
            }
        }
    }
}

#[cfg(test)]
pub mod test {
    use super::*;
    #[test]
    pub fn test_alpha_works_as_struct() {
        assert_eq!(Alpha.char_bool('a'), true)
    }
}