syntaxe/src/parsers.rs 37.5 KiB raw
1
//! Core parser types.
2
use std::fmt;
3
use std::iter::FromIterator;
4
use std::marker::PhantomData;
5
use std::num::{ParseFloatError, ParseIntError};
6
use std::ops::Deref;
7
use std::rc::Rc;
8
use std::str;
9
10
use crate::result::{Cursor, Error, ErrorKind, Result};
11
12
/// Either left or right. Used for parsers that can return
13
/// either of two types of output.
14
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
15
pub enum Either<L, R> {
16
    /// The left case.
17
    Left(L),
18
    /// The right case.
19
    Right(R),
20
}
21
22
/// A self-describing parser combinator.
23
pub trait Parser<'a> {
24
    /// The output of the parser, in case of success.
25
    type Output;
26
27
    /// Parse from the given [`Cursor`].
28
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output>;
29
30
    /// Parse an input string and return a result. On success, returns an output, and any leftover
31
    /// input. Otherwise, returns an error.
32
    fn parse(&self, input: &'a str) -> std::result::Result<(Self::Output, &'a str), Error<'a>> {
33
        self.parse_at(Cursor::from(input))
34
            .map(|(out, rest)| (out, rest.input))
35
    }
36
37
    /// Convert this parser into a boxed trait object.
38
    ///
39
    /// This is useful when you need to store parsers of different concrete types
40
    /// in the same collection, or return different parser implementations from a function.
41
    ///
42
    /// ```
43
    /// use syntaxe::prelude::*;
44
    ///
45
    /// let parsers: Vec<Box<dyn Parser<Output = char>>> = vec![
46
    ///     symbol('!').boxed(),
47
    ///     symbol('?').boxed(),
48
    /// ];
49
    /// ```
50
    fn boxed(self) -> Box<dyn Parser<'a, Output = Self::Output>>
51
    where
52
        Self: Sized + 'static,
53
    {
54
        Box::new(self)
55
    }
56
57
    /// Sequence this parser with the next one.
58
    ///
59
    /// ```
60
    /// use syntaxe::*;
61
    ///
62
    /// let p = string("moo").then(symbol('!')).then(symbol('?'));
63
    /// assert!(p.parse("moo!?").is_ok());
64
    /// ```
65
    fn then<P: Parser<'a>>(self, next: P) -> (Self, P)
66
    where
67
        Self: Sized,
68
    {
69
        (self, next)
70
    }
71
72
    /// Apply this parser, then try to apply the other parser.
73
    /// Only the output from this parser is returned.
74
    ///
75
    /// ```
76
    /// use syntaxe::prelude::*;
77
    ///
78
    /// let p = symbol('X').skip(symbol('Y')).then(symbol('Z'));
79
    ///
80
    /// assert_eq!(p.parse("XYZ"), Ok((('X', 'Z'), "")));
81
    /// assert!(p.parse("XZ").is_err());
82
    ///
83
    /// let p = symbol('X').skip(optional(symbol('Y'))).then(symbol('Z'));
84
    ///
85
    /// assert_eq!(p.parse("XYZ"), Ok((('X', 'Z'), "")));
86
    /// assert_eq!(p.parse("XZ"), Ok((('X', 'Z'), "")));
87
    /// ```
88
    fn skip<P: Parser<'a>>(self, skip: P) -> impl Parser<'a, Output = Self::Output>
89
    where
90
        Self: Sized,
91
    {
92
        move |input| {
93
            let (out, rest) = self.parse_at(input)?;
94
            skip.parse_at(rest).map(|(_, skipped)| (out, skipped))
95
        }
96
    }
97
98
    /// If this parser fails, try another one.
99
    ///
100
    /// ```
101
    /// use syntaxe::prelude::*;
102
    ///
103
    /// let p = symbol('!').or(symbol('?'));
104
    ///
105
    /// assert_eq!(p.parse("?"), Ok(('?', "")));
106
    /// ```
107
    fn or<P: Parser<'a, Output = Self::Output>>(
108
        self,
109
        other: P,
110
    ) -> impl Parser<'a, Output = Self::Output>
111
    where
112
        Self: Sized,
113
    {
114
        move |input| match self.parse_at(input) {
115
            Ok(result) => Ok(result),
116
            Err(_) => other.parse_at(input),
117
        }
118
    }
119
120
    /// Modify the parser output if it succeeds, with the provided function.
121
    ///
122
    /// ```
123
    /// use syntaxe::prelude::*;
124
    ///
125
    /// let p = symbol('X').map(|out| (out, out));
126
    ///
127
    /// assert_eq!(p.parse("X"), Ok((('X', 'X'), "")));
128
    /// ```
129
    fn map<F, O>(self, f: F) -> Map<Self, F>
130
    where
131
        Self: Sized,
132
        F: Fn(Self::Output) -> O,
133
    {
134
        Map { parser: self, f }
135
    }
136
137
    /// Modify the parser output if it succeeds, with the provided fallible function.
138
    ///
139
    /// ```
140
    /// use std::io;
141
    /// use syntaxe::prelude::*;
142
    ///
143
    /// let p = symbol('X').try_map::<String, _>(|out|
144
    ///     Err(io::Error::new(io::ErrorKind::Other, format!("failed to parse {out:?}")))
145
    /// );
146
    /// assert!(p.parse("X").is_err())
147
    /// ```
148
    fn try_map<O, E>(
149
        self,
150
        f: impl Fn(Self::Output) -> std::result::Result<O, E>,
151
    ) -> impl Parser<'a, Output = O>
152
    where
153
        E: std::error::Error + 'static,
154
        Self: Sized,
155
    {
156
        move |cursor| {
157
            self.parse_at(cursor).and_then(|(out, rest)| match f(out) {
158
                Ok(result) => Ok((result, rest)),
159
                Err(e) => Err(Error::new(ErrorKind::TryMap(Rc::new(e)), cursor)),
160
            })
161
        }
162
    }
163
164
    /// Modify the parser output if it succeeds, with the provided value.
165
    ///
166
    /// ```
167
    /// use syntaxe::*;
168
    ///
169
    /// let p = symbol('X').value('Y');
170
    ///
171
    /// assert_eq!(p.parse("X"), Ok(('Y', "")));
172
    /// ```
173
    fn value<V: Clone>(self, val: V) -> impl Parser<'a, Output = V>
174
    where
175
        Self: Sized,
176
    {
177
        self.map(move |_| val.clone())
178
    }
179
180
    /// Provide a custom error message in case this parser fails.
181
    /// This is useful for more complex parsers, or when the default error is not adequate.
182
    fn with_err(self, err: ErrorKind<'a>) -> impl Parser<'a, Output = Self::Output>
183
    where
184
        Self: Sized,
185
    {
186
        move |cursor| self.parse_at(cursor).map_err(|e| Error::new(err.clone(), e.cursor))
187
    }
188
189
    /// Try to convert the output of the parser from a string to the specified type.
190
    ///
191
    /// ```
192
    /// use syntaxe::prelude::*;
193
    ///
194
    /// let p = many::<_, String>(digit()).from_str::<u64>();
195
    ///
196
    /// assert_eq!(p.parse("12345"), Ok((12345, "")));
197
    /// assert!(p.parse("abcde").is_err());
198
    ///
199
    /// ```
200
    #[allow(clippy::wrong_self_convention)]
201
    fn from_str<O>(self) -> FromStr<Self, O>
202
    where
203
        Self: Sized,
204
    {
205
        FromStr(self, PhantomData)
206
    }
207
208
    /// Fail this parser if the predicate fails.
209
    ///
210
    /// ```
211
    /// use syntaxe::*;
212
    ///
213
    /// let p = string("moo").followed_by(symbol('.'));
214
    /// assert_eq!(p.parse("moo."), Ok(("moo", ".")));
215
    /// assert!(p.parse("moo").is_err());
216
    /// ```
217
    fn followed_by<P>(self, next: P) -> impl Parser<'a, Output = Self::Output>
218
    where
219
        P: Parser<'a>,
220
        Self: Sized,
221
    {
222
        self.skip(peek(next))
223
    }
224
225
    /// Applies the parser at least once, separating subsequent applications
226
    /// with a separator.
227
    ///
228
    /// ```
229
    /// use syntaxe::*;
230
    ///
231
    /// let p = natural().delimited_by(symbol(','));
232
    /// assert_eq!(p.parse("1,2,3,4"), Ok((vec![1, 2, 3, 4], "")));
233
    /// assert_eq!(p.parse("2"), Ok((vec![2], "")));
234
    /// assert_eq!(p.parse(""), Ok((vec![], "")));
235
    /// assert!(p.parse("1,").is_err());
236
    ///
237
    /// let p = natural().delimited_by(spaces1());
238
    /// assert_eq!(p.parse("1 2 3 4"), Ok((vec![1, 2, 3, 4], "")));
239
    /// ```
240
    fn delimited_by<S>(self, separator: S) -> impl Parser<'a, Output = Vec<Self::Output>>
241
    where
242
        S: Parser<'a>,
243
        Self: Sized,
244
    {
245
        move |cursor| {
246
            // Parse first element if it exists.
247
            let Ok((item, mut cursor)) = self.parse_at(cursor) else {
248
                return Ok((Vec::new(), cursor));
249
            };
250
            let mut results = vec![item];
251
252
            // Keep parsing separator plus item pairs.
253
            while let Ok((_, rest)) = separator.parse_at(cursor) {
254
                let (item, rest) = self.parse_at(rest)?;
255
                if rest.input.len() >= cursor.input.len() {
256
                    break;
257
                }
258
259
                results.push(item);
260
                cursor = rest;
261
            }
262
            Ok((results, cursor))
263
        }
264
    }
265
}
266
267
impl<'a, O> Parser<'a> for Box<dyn Parser<'a, Output = O>> {
268
    type Output = O;
269
270
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
271
        self.deref().parse_at(input)
272
    }
273
}
274
275
impl<'a, F, O> Parser<'a> for F
276
where
277
    F: Fn(Cursor<'a>) -> Result<'a, O>,
278
{
279
    type Output = O;
280
281
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, O> {
282
        self(input)
283
    }
284
}
285
286
impl<'a> Parser<'a> for char {
287
    type Output = char;
288
289
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
290
        Symbol(*self).parse_at(input)
291
    }
292
}
293
294
/// Applies the first parser and if it succeeds, the second.
295
impl<'a, P, Q> Parser<'a> for (P, Q)
296
where
297
    P: Parser<'a>,
298
    Q: Parser<'a>,
299
{
300
    type Output = (P::Output, Q::Output);
301
302
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
303
        self.0
304
            .parse_at(input)
305
            .and_then(|(out0, rest)| self.1.parse_at(rest).map(|(out1, rest)| ((out0, out1), rest)))
306
    }
307
}
308
309
/// A parser that converts its output from a string.
310
#[derive(Copy)]
311
pub struct FromStr<P, O>(P, PhantomData<O>);
312
impl<'a, P, O, S, E> Parser<'a> for FromStr<P, O>
313
where
314
    P: Parser<'a, Output = S>,
315
    S: AsRef<str>,
316
    O: str::FromStr<Err = E>,
317
    E: std::error::Error + 'static,
318
{
319
    type Output = O;
320
321
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
322
        match self.0.parse_at(input) {
323
            Ok((out, rest)) => match out.as_ref().parse::<O>() {
324
                Ok(o) => Ok((o, rest)),
325
                Err(e) => Err(Error::new(ErrorKind::FromStr(Rc::new(e)), rest)),
326
            },
327
            Err(err) => Err(err),
328
        }
329
    }
330
}
331
332
impl<P: Clone, O> Clone for FromStr<P, O> {
333
    fn clone(&self) -> Self {
334
        Self(self.0.clone(), self.1)
335
    }
336
}
337
338
/// A parser that applies a mapping function to transform its output.
339
#[derive(Clone)]
340
pub struct Map<P, F> {
341
    parser: P,
342
    f: F,
343
}
344
345
impl<'a, P, F, O> Parser<'a> for Map<P, F>
346
where
347
    P: Parser<'a>,
348
    F: Fn(P::Output) -> O,
349
{
350
    type Output = O;
351
352
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
353
        self.parser.parse_at(input).map(|(out, rest)| ((self.f)(out), rest))
354
    }
355
}
356
357
/// Try two different parsers and return either result.
358
/// Returns the first successful parse as `Either::Left`, or the second as `Either::Right`.
359
///
360
/// ```
361
/// use syntaxe::prelude::*;
362
///
363
/// let p = either(float(), natural());
364
///
365
/// assert_eq!(p.parse("42"), Ok((Either::Right(42), "")));
366
/// assert_eq!(p.parse("42.912"), Ok((Either::Left(42.912), "")));
367
/// ```
368
pub fn either<'a, L, R>(left: L, right: R) -> impl Parser<'a, Output = Either<L::Output, R::Output>>
369
where
370
    L: Parser<'a>,
371
    R: Parser<'a>,
372
{
373
    move |input| match left.parse_at(input) {
374
        Ok((out, rest)) => Ok((Either::Left(out), rest)),
375
        _ => match right.parse_at(input) {
376
            Ok((out, rest)) => Ok((Either::Right(out), rest)),
377
            Err(err) => Err(err),
378
        },
379
    }
380
}
381
382
/// Parses if the predicate returns `true` on the input's next `char`.
383
#[derive(Clone)]
384
pub struct Satisfy(fn(&char) -> bool);
385
impl<'a> Parser<'a> for Satisfy {
386
    type Output = char;
387
388
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
389
        let predicate = &self.0;
390
391
        match cursor.input.chars().next() {
392
            Some(c) if predicate(&c) => Ok((c, cursor.advance(1))),
393
            Some(c) => Err(Error::new(ErrorKind::UnexpectedChar(c), cursor)),
394
            None => Err(Error::new(ErrorKind::UnexpectedEof, cursor)),
395
        }
396
    }
397
}
398
399
/// Tries to parse a single character.
400
#[derive(Clone, Debug)]
401
pub struct Symbol(char);
402
impl<'a> Parser<'a> for Symbol {
403
    type Output = char;
404
405
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
406
        match cursor.input.chars().next() {
407
            Some(c) if c == self.0 => Ok((c, cursor.advance(1))),
408
            _ => Err(Error::new(ErrorKind::ExpectedChar(self.0), cursor)),
409
        }
410
    }
411
}
412
413
impl fmt::Display for Symbol {
414
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415
        write!(f, "'{}'", self.0)
416
    }
417
}
418
419
/// Parse a string literal.
420
#[derive(Clone, Debug)]
421
pub struct Keyword<'a>(&'a str);
422
impl<'a> Parser<'a> for Keyword<'a> {
423
    type Output = &'a str;
424
425
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
426
        match cursor.input.get(..self.0.len()) {
427
            Some(word) if word == self.0 => Ok((word, cursor.advance(word.chars().count()))),
428
            _ => Err(Error::new(ErrorKind::ExpectedString(self.0), cursor)),
429
        }
430
    }
431
}
432
433
impl fmt::Display for Keyword<'_> {
434
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435
        write!(f, "\"{}\"", self.0)
436
    }
437
}
438
439
impl From<char> for Symbol {
440
    fn from(c: char) -> Self {
441
        symbol(c)
442
    }
443
}
444
445
/// Fail with a message.
446
///
447
/// ```
448
/// use syntaxe::*;
449
/// use syntaxe::result::{Location, Error};
450
///
451
/// let parser = symbol('!').or(fail("only `!` is allowed"));
452
/// let err = parser.parse("?").unwrap_err();
453
///
454
/// assert_eq!(err.to_string(), "only `!` is allowed");
455
/// ```
456
pub fn fail<'a, S: Into<Rc<str>>, U>(err: S) -> impl Parser<'a, Output = U> {
457
    let err = err.into();
458
    move |cursor: Cursor<'a>| Err(Error::new(ErrorKind::Custom(err.clone()), cursor))
459
}
460
461
/// Call the given predicate on the next character. If it returns `true`,
462
/// consume the character.
463
/// Create a parser that matches a single character if it satisfies the predicate function.
464
///
465
/// ```
466
/// use syntaxe::prelude::*;
467
///
468
/// let parser = satisfy(|c| c.is_ascii_uppercase());
469
/// assert_eq!(parser.parse("ABC"), Ok(('A', "BC")));
470
/// assert!(parser.parse("abc").is_err());
471
/// ```
472
pub fn satisfy(predicate: fn(&char) -> bool) -> Satisfy {
473
    Satisfy(predicate)
474
}
475
476
/// Apply *open*, then *between*, then *close*.
477
///
478
/// ```
479
/// use syntaxe::*;
480
///
481
/// let parser = between(symbol('{'), symbol('}'), any::<_, String>(letter()));
482
///
483
/// assert!(parser.parse("{acme}").is_ok());
484
/// assert_eq!(parser.parse("{acme}"), Ok(("acme".to_owned(), "")));
485
/// ```
486
/// Parse content between opening and closing delimiters.
487
///
488
/// ```
489
/// use syntaxe::prelude::*;
490
///
491
/// let parser = between(symbol('['), symbol(']'), many::<_, String>(letter()));
492
/// assert_eq!(parser.parse("[hello]"), Ok(("hello".to_string(), "")));
493
/// assert!(parser.parse("[123]").is_err());
494
/// ```
495
pub fn between<'a, P, R, Q, O>(open: P, close: R, between: Q) -> impl Parser<'a, Output = O>
496
where
497
    P: Parser<'a>,
498
    R: Parser<'a>,
499
    Q: Parser<'a, Output = O>,
500
{
501
    open.then(between).then(close).map(|((_, body), _)| body)
502
}
503
504
/// Try to apply a parser, returning None if it fails without consuming input.
505
///
506
/// ```
507
/// use syntaxe::*;
508
///
509
/// let p = optional(symbol('!'));
510
/// assert_eq!(p.parse("!"), Ok((Some('!'), "")));
511
/// assert_eq!(p.parse("?"), Ok((None, "?")));
512
/// assert_eq!(p.parse(""), Ok((None, "")));
513
/// ```
514
pub fn optional<'a, O: 'a, P>(parser: P) -> impl Parser<'a, Output = Option<P::Output>>
515
where
516
    P: Parser<'a, Output = O>,
517
{
518
    move |input| match parser.parse_at(input) {
519
        Ok((out, rest)) => Ok((Some(out), rest)),
520
        Err(_) => Ok((None, input)),
521
    }
522
}
523
524
/// Apply the parser until the other parser succeeds.
525
///
526
/// ```
527
/// use syntaxe::*;
528
///
529
/// let p = until(symbol('!'));
530
/// let (out, rest) = p.parse("Hello World!").unwrap();
531
///
532
/// assert_eq!(out, "Hello World");
533
/// assert_eq!(rest, "!");
534
///
535
/// assert!(p.parse("!").is_ok());
536
/// assert!(p.parse("Hello World").is_err());
537
/// ```
538
pub fn until<'a, P>(parser: P) -> impl Parser<'a, Output = &'a str>
539
where
540
    P: Parser<'a>,
541
{
542
    move |mut cursor: Cursor<'a>| -> Result<'a, &'a str> {
543
        let input = cursor.input;
544
        let mut chars = input.chars();
545
        let mut error;
546
547
        loop {
548
            match parser.parse_at(cursor) {
549
                Ok((_, _)) => return Ok((&input[..input.len() - cursor.input.len()], cursor)),
550
                Err(e) => error = e,
551
            }
552
            if chars.next().is_some() {
553
                cursor = cursor.advance(1);
554
            } else {
555
                break;
556
            }
557
        }
558
        Err(error)
559
    }
560
}
561
562
/// Succeeds when the input is empty.
563
///
564
/// ```
565
/// use syntaxe::prelude::*;
566
///
567
/// end().parse("").is_ok();
568
/// end().parse("#").is_err();
569
///
570
/// let (out, rest) = until(end()).parse("Hello World!").unwrap();
571
/// assert_eq!(out, String::from("Hello World!"));
572
/// assert_eq!(rest, "");
573
/// ```
574
pub fn end<'a>() -> impl Parser<'a, Output = ()> {
575
    (|cursor: Cursor<'a>| {
576
        if cursor.input.is_empty() {
577
            Ok(((), cursor))
578
        } else {
579
            Err(Error::new(ErrorKind::ExpectedEof, cursor))
580
        }
581
    })
582
    .with_err(ErrorKind::ExpectedEof)
583
}
584
585
/// Parses a single character.
586
pub fn symbol(c: char) -> Symbol {
587
    Symbol(c)
588
}
589
590
/// Parses a single letter.
591
///
592
/// ```
593
/// use syntaxe::prelude::*;
594
///
595
/// let letter = satisfy(char::is_ascii_alphabetic);
596
/// ```
597
pub fn letter<'a>() -> impl Parser<'a, Output = char> {
598
    satisfy(char::is_ascii_alphabetic).with_err(ErrorKind::ExpectedOther("a-Z".into()))
599
}
600
601
/// Parses any character. Always succeeds.
602
/// Parse any single character.
603
///
604
/// ```
605
/// use syntaxe::prelude::*;
606
///
607
/// let parser = character();
608
/// assert_eq!(parser.parse("abc"), Ok(('a', "bc")));
609
/// assert_eq!(parser.parse("123"), Ok(('1', "23")));
610
/// assert!(parser.parse("").is_err());
611
/// ```
612
pub fn character<'a>() -> impl Parser<'a, Output = char> {
613
    satisfy(|_| true)
614
}
615
616
/// Applies the parser any number of times.
617
///
618
/// ```
619
/// use syntaxe::prelude::*;
620
///
621
/// let p = any(symbol('?'));
622
///
623
/// assert_eq!(p.parse("???"), Ok((String::from("???"), "")));
624
/// assert!(p.parse("").is_ok());
625
/// assert!(p.parse("?").is_ok());
626
/// assert!(p.parse("??????").is_ok());
627
/// ```
628
pub fn any<'a, P, U>(parser: P) -> Any<P, U>
629
where
630
    P: Parser<'a>,
631
{
632
    Any(parser, PhantomData)
633
}
634
635
/// Applies the underlying parser zero or more times. Never fails.
636
/// Returns the outputs as a vector.
637
#[derive(Debug)]
638
pub struct Any<P, O>(P, PhantomData<O>);
639
impl<'a, P, O> Parser<'a> for Any<P, O>
640
where
641
    P: 'a + Parser<'a>,
642
    O: 'a + FromIterator<P::Output> + Default + Extend<P::Output>,
643
{
644
    type Output = O;
645
646
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
647
        let mut input = input;
648
        let mut outs = O::default();
649
650
        while let Ok((out, rest)) = self.0.parse_at(input) {
651
            if rest.input.len() >= input.input.len() {
652
                break;
653
            }
654
            outs.extend(std::iter::once(out));
655
            input = rest;
656
        }
657
        Ok((outs, input))
658
    }
659
}
660
661
impl<'a, P: Parser<'a> + Clone, O> Clone for Any<P, O> {
662
    fn clone(&self) -> Self {
663
        Self(self.0.clone(), self.1)
664
    }
665
}
666
667
/// Applies the parser one or more times.
668
///
669
/// ```
670
/// use syntaxe::*;
671
///
672
/// let p = many::<_, String>(symbol('!'));
673
///
674
/// assert!(p.parse("!").is_ok());
675
/// assert!(p.parse("!!").is_ok());
676
/// assert!(p.parse("!!!").is_ok());
677
/// assert!(p.parse("").is_err());
678
/// ```
679
pub fn many<'a, P, O>(parser: P) -> impl Parser<'a, Output = O> + 'a
680
where
681
    P: Parser<'a> + 'a,
682
    O: FromIterator<P::Output> + Default + Extend<P::Output> + 'a,
683
{
684
    move |input| {
685
        let mut input = input;
686
        let mut outs = O::default();
687
688
        let (out, rest) = parser.parse_at(input)?;
689
        outs.extend(std::iter::once(out));
690
        input = rest;
691
692
        while let Ok((out, rest)) = parser.parse_at(input) {
693
            if rest.input.len() >= input.input.len() {
694
                break;
695
            }
696
            outs.extend(std::iter::once(out));
697
            input = rest;
698
        }
699
        Ok((outs, input))
700
    }
701
}
702
703
/// Tries multiple parsers in sequence until one succeeds.
704
/// Returns the first successful parse result.
705
///
706
/// ```
707
/// use syntaxe::*;
708
///
709
/// let p = choice([symbol('?'), symbol('!'), symbol('.')]);
710
///
711
/// assert_eq!(p.parse("?").ok(), Some(('?', "")));
712
/// assert_eq!(p.parse("!").ok(), Some(('!', "")));
713
/// assert_eq!(p.parse(".").ok(), Some(('.', "")));
714
///
715
/// assert!(p.parse("@").is_err());
716
/// assert!(p.parse(",").is_err());
717
/// assert!(p.parse("").is_err());
718
/// ```
719
pub fn choice<'a, P: Parser<'a>>(
720
    parsers: impl IntoIterator<Item = P>,
721
) -> impl Parser<'a, Output = P::Output> {
722
    let parsers: Vec<P> = parsers.into_iter().collect();
723
724
    move |input| {
725
        let mut expected = Vec::new();
726
        for p in &parsers {
727
            match p.parse_at(input) {
728
                Ok(result) => return Ok(result),
729
                Err(e) => {
730
                    if let Some(exp) = e.expected() {
731
                        expected.push(exp)
732
                    }
733
                }
734
            }
735
        }
736
        Err(Error::new(ErrorKind::ExpectedOneOf(expected), input))
737
    }
738
}
739
740
/// Parses a string literal.
741
///
742
/// ```
743
/// use syntaxe::*;
744
/// use syntaxe::result::Error;
745
///
746
/// let p = string("set");
747
///
748
/// assert!(p.parse("set").is_ok());
749
/// assert!(p.parse("").is_err());
750
///
751
/// let err = p.parse("get").unwrap_err();
752
/// assert_eq!(err.to_string(), "expected `set`, got `get`");
753
///
754
/// let p = string("true").from_str::<bool>();
755
/// assert_eq!(p.parse("true!"), Ok((true, "!")));
756
/// ```
757
pub fn string(input: &str) -> Keyword<'_> {
758
    Keyword(input)
759
}
760
761
/// Optional whitespace.
762
///
763
/// ```
764
/// use syntaxe::*;
765
///
766
/// let p = whitespace();
767
///
768
/// assert!(p.parse(" ").is_ok());
769
/// assert!(p.parse("   ").is_ok());
770
/// assert!(p.parse("\t \t").is_ok());
771
/// assert!(p.parse("\n").is_ok());
772
/// assert!(p.parse("").is_ok());
773
/// ```
774
pub fn whitespace<'a>() -> impl Parser<'a, Output = &'a str> {
775
    take_while(char::is_ascii_whitespace)
776
}
777
778
/// Optional spaces.
779
///
780
/// ```
781
/// use syntaxe::*;
782
///
783
/// let p = spaces();
784
///
785
/// assert!(p.parse(" ").is_ok());
786
/// assert!(p.parse("   ").is_ok());
787
/// assert!(p.parse("\t").is_ok());
788
/// assert!(p.parse("").is_ok());
789
/// ```
790
pub fn spaces<'a>() -> impl Parser<'a, Output = &'a str> {
791
    take_while(|c| *c == ' ' || *c == '\t')
792
}
793
794
/// One or more horizontal spaces (space or tab).
795
///
796
/// ```
797
/// use syntaxe::*;
798
///
799
/// let p = spaces1();
800
///
801
/// assert!(p.parse(" ").is_ok());
802
/// assert!(p.parse("   ").is_ok());
803
/// assert!(p.parse("\t").is_ok());
804
/// assert!(p.parse("\t  ").is_ok());
805
/// assert!(p.parse("").is_err());
806
/// ```
807
pub fn spaces1<'a>() -> impl Parser<'a, Output = &'a str> {
808
    take_while1(|c| *c == ' ' || *c == '\t')
809
}
810
811
/// Parses a single line-feed token.
812
///
813
/// ```
814
/// use syntaxe::*;
815
///
816
/// let p = linebreaks();
817
/// assert_eq!(p.parse("\n"), Ok(("\n", "")));
818
/// assert_eq!(p.parse("\r\n"), Ok(("\r\n", "")));
819
/// ```
820
/// Parse zero or more vertical whitespace characters (newline or carriage return).
821
///
822
/// ```
823
/// use syntaxe::prelude::*;
824
///
825
/// let parser = linebreaks();
826
/// assert_eq!(parser.parse("\n\r\n"), Ok(("\n\r\n", "")));
827
/// assert_eq!(parser.parse("abc"), Ok(("", "abc")));
828
/// ```
829
pub fn linebreaks<'a>() -> impl Parser<'a, Output = &'a str> {
830
    take_while(|c| *c == '\n' || *c == '\r')
831
}
832
833
/// Parses a single base ten digit.
834
///
835
/// ```
836
/// use syntaxe::*;
837
///
838
/// let digit = satisfy(|c: &char| c.is_digit(10));
839
/// ```
840
pub fn digit<'a>() -> impl Parser<'a, Output = char> {
841
    satisfy(char::is_ascii_digit).with_err(ErrorKind::ExpectedOther("0-9".into()))
842
}
843
844
/// Unsigned decimal integer.
845
///
846
/// ```
847
/// use syntaxe::*;
848
///
849
/// let p = natural::<u64>();
850
///
851
/// assert!(p.parse("0").is_ok());
852
/// assert!(p.parse("123").is_ok());
853
/// assert!(p.parse("043").is_ok());
854
/// assert!(p.parse("-55").is_err());
855
/// ```
856
pub fn natural<'a, O>() -> impl Parser<'a, Output = O>
857
where
858
    O: str::FromStr<Err = ParseIntError> + 'a,
859
{
860
    repeat(digit()).from_str::<O>()
861
}
862
863
/// Unsigned floating point number.
864
///
865
/// ```
866
/// use syntaxe::*;
867
///
868
/// let p = float::<f64>();
869
///
870
/// assert!(p.parse("123.456").is_ok());
871
/// assert!(p.parse(".42").is_ok());
872
/// assert!(p.parse("0").is_err());
873
/// assert!(p.parse("42").is_err());
874
/// assert!(p.parse("42.").is_err());
875
/// assert!(p.parse("-1.23").is_err());
876
/// ```
877
pub fn float<'a, O>() -> impl Parser<'a, Output = O>
878
where
879
    O: str::FromStr<Err = ParseFloatError> + 'a,
880
{
881
    let whole = repeat(digit());
882
    let fract = repeat(digit());
883
884
    (optional(whole).then(symbol('.')).then(fract))
885
        .map(|((w, _), d)| match w {
886
            Some(w) => format!("{}.{}", w, d),
887
            None => format!("0.{}", d),
888
        })
889
        .from_str::<O>()
890
}
891
892
/// Makes a parser accept an optional sign prefix.
893
///
894
/// ```
895
/// use syntaxe::*;
896
///
897
/// let p = signed(float::<f64>());
898
/// assert_eq!(p.parse("42.019"), Ok((42.019, "")));
899
/// assert_eq!(p.parse("-4.23"), Ok((-4.23, "")));
900
/// assert_eq!(p.parse("+4.23"), Ok((4.23, "")));
901
///
902
/// let p = signed(natural::<i64>());
903
/// assert_eq!(p.parse("42"), Ok((42, "")));
904
/// assert_eq!(p.parse("-42"), Ok((-42, "")));
905
/// assert_eq!(p.parse("+42"), Ok((42, "")));
906
/// ```
907
pub fn signed<'a, P, O>(parser: P) -> impl Parser<'a, Output = O>
908
where
909
    P: Parser<'a, Output = O>,
910
    O: std::ops::Neg<Output = O> + 'a,
911
{
912
    let sign = optional(symbol('-').or(symbol('+')));
913
914
    sign.then(parser).map(|(s, n)| match s {
915
        Some('-') => -n,
916
        _ => n,
917
    })
918
}
919
920
/// Apply the given parser, and if it fails, don't consume any input.
921
///
922
/// ```
923
/// use syntaxe::*;
924
///
925
/// let p = choice([
926
///     peek(string("leave").skip(whitespace()).then(string("england"))),
927
///     peek(string("leave").skip(whitespace()).then(string("france"))),
928
/// ]);
929
///
930
/// assert!(p.parse("leave england").is_ok());
931
/// assert!(p.parse("leave france").is_ok());
932
/// ```
933
pub fn peek<'a, P: Parser<'a>>(parser: P) -> impl Parser<'a, Output = P::Output> {
934
    move |input| match parser.parse_at(input) {
935
        Ok((out, _)) => Ok((out, input)),
936
        Err(err) => Err(err),
937
    }
938
}
939
940
/// Repeatedly apply a parser until it fails, returning the concatenated string of all matches.
941
/// Returns an error if the first application fails.
942
///
943
/// ```
944
/// use syntaxe::*;
945
///
946
/// let p = repeat(letter());
947
/// let (out, rest) = p.parse("Bazinga!").unwrap();
948
///
949
/// assert_eq!(out, "Bazinga");
950
/// assert_eq!(rest, "!");
951
///
952
/// assert!(p.parse("!").is_err());
953
/// ```
954
pub fn repeat<'a, P>(parser: P) -> impl Parser<'a, Output = &'a str>
955
where
956
    P: Parser<'a> + 'a,
957
{
958
    move |cursor: Cursor<'a>| -> Result<'a, &'a str> {
959
        let input = cursor.input;
960
        let (_, mut cursor) = parser.parse_at(cursor)?;
961
962
        while let Ok((_, rest)) = parser.parse_at(cursor) {
963
            if rest.input.len() >= cursor.input.len() {
964
                break;
965
            }
966
            cursor = rest;
967
        }
968
        let len = input.len() - cursor.input.len();
969
970
        Ok((&input[..len], cursor))
971
    }
972
}
973
974
/// Parse characters as long as they match the predicate function.
975
/// Returns all matching characters as a string slice.
976
/// Returns an empty string if no characters match.
977
///
978
/// ```
979
/// use syntaxe::prelude::*;
980
///
981
/// let parser = take_while(|c| c.is_ascii_digit());
982
/// assert_eq!(parser.parse("123abc"), Ok(("123", "abc")));
983
/// assert_eq!(parser.parse("abc"), Ok(("", "abc"))); // No match returns empty string
984
/// ```
985
pub fn take_while<'a, F: Fn(&char) -> bool>(pred: F) -> impl Parser<'a, Output = &'a str> {
986
    move |cursor: Cursor<'a>| {
987
        let input = cursor.input;
988
        let count = input.chars().take_while(&pred).count();
989
        let rest = cursor.advance(count);
990
        let len = input.len() - rest.input.len();
991
992
        Ok((&input[..len], rest))
993
    }
994
}
995
996
/// Like [`take_while`], but requires at least one matching character.
997
/// Parse one or more characters matching a predicate.
998
/// Returns an error if no characters match.
999
///
1000
/// ```
1001
/// use syntaxe::prelude::*;
1002
///
1003
/// let parser = take_while1(|c| c.is_ascii_digit());
1004
/// assert_eq!(parser.parse("123abc"), Ok(("123", "abc")));
1005
/// assert!(parser.parse("abc").is_err());
1006
/// ```
1007
pub fn take_while1<'a, F: Fn(&char) -> bool + Copy + 'static>(
1008
    pred: F,
1009
) -> impl Parser<'a, Output = &'a str> {
1010
    move |cursor: Cursor<'a>| {
1011
        let Some(c) = cursor.input.chars().next() else {
1012
            return Err(Error::new(ErrorKind::UnexpectedEof, cursor));
1013
        };
1014
        if !pred(&c) {
1015
            return Err(Error::new(ErrorKind::UnexpectedChar(c), cursor));
1016
        }
1017
        take_while(pred).parse_at(cursor)
1018
    }
1019
}
1020
1021
/// Parse characters until one matches the predicate function.
1022
/// Returns all non-matching characters as a string slice.
1023
/// Returns an error if the input is empty or if no terminating character is found.
1024
///
1025
/// ```
1026
/// use syntaxe::prelude::*;
1027
///
1028
/// let parser = take_until(|c| c == '.');
1029
/// assert_eq!(parser.parse("abc.def"), Ok(("abc", ".def")));
1030
/// assert!(parser.parse("abc").is_err()); // No terminator found
1031
/// ```
1032
pub fn take_until<'a, F: Fn(char) -> bool + Copy + 'static>(
1033
    term: F,
1034
) -> impl Parser<'a, Output = &'a str> {
1035
    move |cursor: Cursor<'a>| {
1036
        let input = cursor.input;
1037
        let mut rest = cursor;
1038
1039
        for c in input.chars() {
1040
            if term(c) {
1041
                let len = input.len() - rest.input.len();
1042
                return Ok((&input[..len], rest));
1043
            }
1044
            rest = rest.advance(1);
1045
        }
1046
        Err(Error::new(ErrorKind::UnexpectedEof, rest))
1047
    }
1048
}
1049
1050
/// Takes the rest of the input as a string slice.
1051
/// Always succeeds.
1052
///
1053
/// ```
1054
/// use syntaxe::prelude::*;
1055
///
1056
/// let parser = take_str();
1057
/// assert_eq!(parser.parse("hello world"), Ok(("hello world", "")));
1058
/// assert!(parser.parse("").is_ok());
1059
/// ```
1060
pub fn take_str<'a>() -> impl Parser<'a, Output = &'a str> {
1061
    move |cursor: Cursor<'a>| Ok((cursor.input, cursor.advance(cursor.input.chars().count())))
1062
}
1063
1064
/// Takes exactly `n` characters from the input.
1065
/// Fails if there aren't enough characters available.
1066
///
1067
/// ```
1068
/// use syntaxe::prelude::*;
1069
///
1070
/// let parser = take(5);
1071
/// assert_eq!(parser.parse("hello world"), Ok(("hello", " world")));
1072
/// assert!(parser.parse("hi").is_err());
1073
/// ```
1074
pub fn take<'a>(n: usize) -> impl Parser<'a, Output = &'a str> {
1075
    move |cursor: Cursor<'a>| {
1076
        let mut chars = cursor.input.chars();
1077
        for _ in 0..n {
1078
            if chars.next().is_none() {
1079
                return Err(Error::new(ErrorKind::UnexpectedEof, cursor));
1080
            }
1081
        }
1082
        let len = cursor.input.len() - chars.as_str().len();
1083
        Ok((&cursor.input[..len], cursor.advance(n)))
1084
    }
1085
}
1086
1087
/// Attempt to parse, and if it fails, backtrack as if no input had been consumed.
1088
///
1089
/// ```
1090
/// use syntaxe::prelude::*;
1091
///
1092
/// // Without `backtrack`.
1093
/// let parser = string("hello").skip(whitespace()).then(string("tom"));
1094
/// let result = parser.parse("hello bob").unwrap_err();
1095
/// assert_eq!(result.unparsed(), "bob");
1096
///
1097
/// // With `backtrack`.
1098
/// let parser = backtrack(string("hello").skip(whitespace()).then(string("tom")));
1099
/// let result = parser.parse("hello bob").unwrap_err();
1100
/// assert_eq!(result.unparsed(), "hello bob");
1101
/// ```
1102
pub fn backtrack<'a, P>(parser: P) -> impl Parser<'a, Output = P::Output>
1103
where
1104
    P: Parser<'a>,
1105
{
1106
    move |cursor: Cursor<'a>| parser.parse_at(cursor).map_err(|e| Error::new(e.kind, cursor))
1107
}
1108
1109
/// Silence a parser. Discard its output and return `()` instead.
1110
/// Useful when you need to match a pattern but don't care about capturing its value.
1111
pub fn hush<'a, P>(parser: P) -> impl Parser<'a, Output = ()>
1112
where
1113
    P: Parser<'a>,
1114
{
1115
    parser.value(())
1116
}
1117
1118
#[cfg(test)]
1119
#[allow(clippy::unwrap_used)]
1120
mod test {
1121
    use super::*;
1122
    use crate::result::Location;
1123
1124
    #[test]
1125
    fn test_repetition_without_progress() {
1126
        let calls = std::cell::Cell::new(0);
1127
        let empty = |cursor| {
1128
            calls.set(calls.get() + 1);
1129
            assert!(
1130
                calls.get() <= 8,
1131
                "repetition must stop without input progress"
1132
            );
1133
            Ok(((), cursor))
1134
        };
1135
        assert_eq!(any::<_, Vec<_>>(&empty).parse("a"), Ok((vec![], "a")));
1136
        assert_eq!(many::<_, Vec<_>>(&empty).parse("a"), Ok((vec![()], "a")));
1137
        assert_eq!(repeat(&empty).parse("a"), Ok(("", "a")));
1138
        assert_eq!(
1139
            empty.delimited_by(string("")).parse("a"),
1140
            Ok((vec![()], "a"))
1141
        );
1142
    }
1143
1144
    #[test]
1145
    fn test_choice_backtracking() {
1146
        let p = choice([
1147
            string("leave").skip(whitespace()).then(string("england")),
1148
            string("learn").skip(whitespace()).then(string("english")),
1149
            string("leave").skip(whitespace()).then(string("britain")),
1150
        ]);
1151
1152
        assert!(p.parse("learn english").is_ok());
1153
        assert!(p.parse("leave england").is_ok());
1154
        assert!(p.parse("leave britain").is_ok());
1155
1156
        let err = p.parse("leave english").err().unwrap();
1157
        assert_eq!(err.unparsed(), "leave english");
1158
    }
1159
1160
    #[test]
1161
    fn test_choice_backtracking_skip() {
1162
        let p = choice([
1163
            string("leave").skip(whitespace()).skip(string("england")).boxed(),
1164
            string("leave/england").boxed(),
1165
        ]);
1166
1167
        assert!(p.parse("leave england").is_ok());
1168
        assert!(p.parse("leave/england").is_ok());
1169
1170
        let p = choice([
1171
            backtrack(string("leave").skip(whitespace()))
1172
                .skip(string("england"))
1173
                .boxed(),
1174
            string("leave/england").boxed(),
1175
        ]);
1176
1177
        assert!(p.parse("leave england").is_ok());
1178
        assert!(p.parse("leave/england").is_ok());
1179
    }
1180
1181
    #[test]
1182
    fn test_or() {
1183
        let p = string("leave")
1184
            .skip(whitespace())
1185
            .then(string("england"))
1186
            .or(string("learn").skip(whitespace()).then(string("english")))
1187
            .or(string("leave").skip(whitespace()).then(string("britain")));
1188
1189
        // Test backtracking.
1190
        assert!(p.parse("learn english").is_ok());
1191
        assert!(p.parse("leave england").is_ok());
1192
        assert!(p.parse("leave britain").is_ok());
1193
1194
        let err = p.parse("leave english").err().unwrap();
1195
        assert_eq!(err.unparsed(), "english");
1196
        assert_eq!(err.to_string(), "expected `britain`, got `english`");
1197
    }
1198
1199
    #[test]
1200
    fn test_zero_copy() {
1201
        let input = "fnord!";
1202
        let (result, rest) = string("fnord").parse(input).unwrap();
1203
1204
        assert_eq!(result, "fnord".to_owned());
1205
        assert_eq!(rest, "!");
1206
        assert_eq!(input[5..6].as_ptr(), rest.as_ptr());
1207
    }
1208
1209
    #[test]
1210
    fn test_lisp() {
1211
        #[derive(PartialEq, Debug)]
1212
        enum Expr {
1213
            List(Vec<Expr>),
1214
            Op(char),
1215
            Num(u8),
1216
        }
1217
1218
        fn expr<'a>() -> impl Parser<'a, Output = Expr> {
1219
            let num = natural::<u8>().map(Expr::Num);
1220
            let op = choice([symbol('*'), symbol('+'), symbol('^')]).map(Expr::Op);
1221
            let list =
1222
                between('(', ')', (|c| expr().parse_at(c)).delimited_by(spaces1())).map(Expr::List);
1223
1224
            list.or(num).or(op)
1225
        }
1226
        let (output, rest) = expr().parse("(+ 1 (* (^ 2 3) 4))").unwrap();
1227
1228
        assert_eq!(
1229
            output,
1230
            Expr::List(vec![
1231
                Expr::Op('+'),
1232
                Expr::Num(1),
1233
                Expr::List(vec![
1234
                    Expr::Op('*'),
1235
                    Expr::List(vec![Expr::Op('^'), Expr::Num(2), Expr::Num(3)]),
1236
                    Expr::Num(4)
1237
                ]),
1238
            ])
1239
        );
1240
        assert_eq!(rest, "");
1241
    }
1242
1243
    #[test]
1244
    fn test_errors() {
1245
        struct TestCase {
1246
            input: &'static str,
1247
            parser: Box<dyn Parser<'static, Output = ()>>,
1248
            location: Location,
1249
            message: &'static str,
1250
        }
1251
1252
        let cases = vec![
1253
            TestCase {
1254
                input: "abc\ndef\nghi",
1255
                parser: string("xyz").value(()).boxed(),
1256
                location: Location {
1257
                    index: 0,
1258
                    line: 1,
1259
                    column: 1,
1260
                },
1261
                message: "<stdin>:1:1: error: expected `xyz`, got `abc`",
1262
            },
1263
            TestCase {
1264
                input: "123\n456\n789",
1265
                parser: many::<_, String>(digit()).then(symbol('x')).value(()).boxed(),
1266
                location: Location {
1267
                    index: 3,
1268
                    line: 1,
1269
                    column: 4,
1270
                },
1271
                message: "<stdin>:1:4: error: expected 'x', got `\n`",
1272
            },
1273
            TestCase {
1274
                input: "hello\nworld!",
1275
                parser: string("hello")
1276
                    .then(linebreaks())
1277
                    .then(string("earth"))
1278
                    .value(())
1279
                    .boxed(),
1280
                location: Location {
1281
                    index: 6,
1282
                    line: 2,
1283
                    column: 1,
1284
                },
1285
                message: "<stdin>:2:1: error: expected `earth`, got `world!`",
1286
            },
1287
            TestCase {
1288
                input: "",
1289
                parser: digit().value(()).boxed(),
1290
                location: Location {
1291
                    index: 0,
1292
                    line: 1,
1293
                    column: 1,
1294
                },
1295
                message: "<stdin>:1:1: error: expected 0-9, got end-of-input",
1296
            },
1297
            TestCase {
1298
                input: "hello\nworld",
1299
                parser: until(symbol('!')).value(()).boxed(),
1300
                location: Location {
1301
                    index: 11,
1302
                    line: 2,
1303
                    column: 6,
1304
                },
1305
                message: "<stdin>:2:6: error: expected '!', got end-of-input",
1306
            },
1307
            TestCase {
1308
                input: "#@!",
1309
                parser: end().boxed(),
1310
                location: Location {
1311
                    index: 0,
1312
                    line: 1,
1313
                    column: 1,
1314
                },
1315
                message: "<stdin>:1:1: error: expected end-of-input, got `#@!`",
1316
            },
1317
        ];
1318
1319
        for (i, case) in cases.into_iter().enumerate() {
1320
            let result = case.parser.parse(case.input);
1321
            let err = result.expect_err(&format!(
1322
                "Case #{i}: expected error for input: `{}`",
1323
                case.input
1324
            ));
1325
1326
            assert_eq!(
1327
                err.explain(),
1328
                case.message,
1329
                "Case #{i}: wrong error message for input: expected {:?}, got {:?}",
1330
                case.input,
1331
                err
1332
            );
1333
            assert_eq!(
1334
                err.cursor.location, case.location,
1335
                "Case #{i}: wrong location for input: expected {:?}, got {:?}",
1336
                case.location, err.cursor.location,
1337
            );
1338
        }
1339
    }
1340
}