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

//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 }
    }
    #[deprecated(since = "0.4.0", note = "Use 'star' instead")]
    fn any(self) -> CharStar<Self> {
        CharStar { 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 skip_star(self) -> skip::CharSkip<Self> {
        skip::CharSkip { cb: self }
    }

    fn skip_plus(self) -> skip::CharSkipPlus<Self> {
        skip::CharSkipPlus { cb: self }
    }

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

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

/// [a-z][A-Z]
/// ```rust
/// use gobble::*;
/// assert_eq!(Alpha.min_n(4).parse_s("hello_"),Ok("hello".to_string()));
/// assert!(Alpha.min_n(6).parse_s("hello_").is_err());
/// ```
#[derive(Clone, Copy)]
pub struct Alpha;
pub fn is_alpha(c: char) -> bool {
    (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
}
impl CharBool for Alpha {
    fn char_bool(&self, c: char) -> bool {
        is_alpha(c)
    }
    fn expected(&self) -> Expected {
        Expected::CharIn("[a-z][A-Z]")
    }
}

///0..9
#[derive(Clone, Copy)]
pub struct NumDigit;
pub fn is_num(c: char) -> bool {
    c >= '0' && c <= '9'
}
impl CharBool for NumDigit {
    fn char_bool(&self, c: char) -> bool {
        is_num(c)
    }
    fn expected(&self) -> Expected {
        Expected::CharIn("[0-9]")
    }
}

#[derive(Clone, Copy)]
pub struct Any;
impl CharBool for Any {
    fn char_bool(&self, _: char) -> bool {
        true
    }
    fn expected(&self) -> Expected {
        Expected::CharIn("anything")
    }
}

///a-f,A-F,0-9
#[derive(Clone, Copy)]
pub struct HexDigit;
pub fn is_hex(c: char) -> bool {
    is_num(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
impl CharBool for HexDigit {
    fn char_bool(&self, c: char) -> bool {
        is_hex(c)
    }
    fn expected(&self) -> Expected {
        Expected::CharIn("[0-9][a-f][A-F]")
    }
}

///Whitespace
pub struct WS;
impl CharBool for WS {
    fn char_bool(&self, c: char) -> bool {
        " \t".char_bool(c)
    }
}
///Whitespace and newlines
pub struct WSL;
impl CharBool for WSL {
    fn char_bool(&self, c: char) -> bool {
        " \t\n\r".char_bool(c)
    }
}

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 fn do_one_char<'a, CB: CharBool>(i: &LCChars<'a>, cb: &CB) -> ParseRes<'a, char> {
    let mut i2 = i.clone();
    let ic = i2.next().ok_or(i2.err_ex(cb.expected()))?;
    if cb.char_bool(ic) {
        Ok((i2, ic, None))
    } else {
        i.err_ex_r(cb.expected())
    }
}

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

impl<CB: CharBool> Parser for OneChar<CB> {
    type Out = char;
    fn parse<'a>(&self, it: &LCChars<'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>(
    it: &LCChars<'a>,
    cb: &CB,
    min: usize,
    exact: bool,
) -> ParseRes<'a, String> {
    let mut res = String::new();
    let mut it = it.clone();
    loop {
        let it2 = it.clone();
        match it.next() {
            Some(c) if cb.char_bool(c) => {
                res.push(c);
            }
            Some(_) | None => {
                if res.len() >= min {
                    let eo = it2.err_cb_o(cb);
                    return Ok((it2, res, eo));
                } else {
                    return it2.err_ex_r(cb.expected());
                }
            }
        }
        if res.len() == min && exact {
            return Ok((it, res, None));
        }
    }
}
#[derive(Clone)]
pub struct CharStar<C: CharBool> {
    cb: C,
}

impl<CB: CharBool> Parser for CharStar<CB> {
    type Out = String;
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, String> {
        do_chars(it, &self.cb, 0, false)
    }
}

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

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

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().or(Expected::except(self.e.expected()))
    }
}

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

impl<A: CharBool> Parser for CharExact<A> {
    type Out = String;
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, String> {
        do_chars(it, &self.a, self.n, true)
    }
}

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

impl<A: CharBool> Parser for CharMin<A> {
    type Out = String;
    fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, String> {
        do_chars(it, &self.cb, self.min, false)
    }
}

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