parser_combinators/
combinator.rs

1use std::iter::FromIterator;
2use std::marker::PhantomData;
3use primitives::{Info, Parser, ParseResult, ParseError, Positioner, Stream, State, Error, Consumed};
4
5macro_rules! impl_parser {
6    ($name: ident ($first: ident, $($ty_var: ident),*), $inner_type: ty) => {
7    #[derive(Clone)]
8    pub struct $name<$first $(,$ty_var)*>($inner_type)
9        where $first: Parser $(,$ty_var : Parser<Input=<$first as Parser>::Input>)*;
10    impl <$first, $($ty_var),*> Parser for $name<$first $(,$ty_var)*>
11        where $first: Parser $(, $ty_var : Parser<Input=<$first as Parser>::Input>)* {
12        type Input = <$first as Parser>::Input;
13        type Output = <$inner_type as Parser>::Output;
14        fn parse_state(&mut self, input: State<<Self as Parser>::Input>) -> ParseResult<<Self as Parser>::Output, <Self as Parser>::Input, <Self::Input as Stream>::Item> {
15            self.0.parse_state(input)
16        }
17        fn parse_lazy(&mut self, input: State<<Self as Parser>::Input>) -> ParseResult<<Self as Parser>::Output, <Self as Parser>::Input, <Self::Input as Stream>::Item> {
18            self.0.parse_lazy(input)
19        }
20        fn add_error(&mut self, error: &mut ParseError<<Self::Input as Stream>::Item>) {
21            self.0.add_error(error)
22        }
23    }
24}
25}
26
27#[derive(Clone)]
28pub struct Any<I>(PhantomData<fn (I) -> I>);
29
30impl <I> Parser for Any<I>
31    where I: Stream {
32    type Input = I;
33    type Output = I::Item;
34    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<I::Item, I, I::Item> {
35        input.uncons()
36    }
37}
38
39///Parses any token
40///
41/// ```
42/// # extern crate parser_combinators as pc;
43/// # use pc::*;
44/// # fn main() {
45/// let mut char_parser = any();
46/// assert_eq!(char_parser.parse("!").map(|x| x.0), Ok('!'));
47/// assert!(char_parser.parse("").is_err());
48/// let mut byte_parser = any();
49/// assert_eq!(byte_parser.parse(&b"!"[..]).map(|x| x.0), Ok(&b'!'));
50/// assert!(byte_parser.parse(&b""[..]).is_err());
51/// # }
52/// ```
53pub fn any<I>() -> Any<I>
54    where I: Stream {
55    Any(PhantomData)
56}
57
58
59
60#[derive(Clone)]
61pub struct Satisfy<I, P> { predicate: P, _marker: PhantomData<I> }
62
63fn satisfy_impl<I, P, F>(input: State<I>, predicate: &mut P, f: F) -> ParseResult<I::Item, I, I::Item>
64    where I: Stream
65        , P: FnMut(I::Item) -> bool
66        , F: FnOnce(<I::Item as Positioner>::Position, I::Item) -> ParseError<I::Item> {
67    match input.input.clone().uncons() {
68        Ok((c, s)) => {
69            if (predicate)(c.clone()) { input.update(c, s) }
70            else {
71                Err(Consumed::Empty(f(input.position, c)))
72            }
73        }
74        Err(err) => Err(Consumed::Empty(ParseError::new(input.position, err)))
75    }
76}
77
78impl <I, P> Parser for Satisfy<I, P>
79    where I: Stream, P: FnMut(I::Item) -> bool {
80
81    type Input = I;
82    type Output = I::Item;
83    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<I::Item, I, I::Item> {
84        satisfy_impl(input, &mut self.predicate, |pos, _| ParseError::empty(pos))
85    }
86}
87
88///Parses a token and succeeds depending on the result of `predicate`
89///
90/// ```
91/// # extern crate parser_combinators as pc;
92/// # use pc::*;
93/// # fn main() {
94/// let mut parser = satisfy(|c| c == '!' || c == '?');
95/// assert_eq!(parser.parse("!").map(|x| x.0), Ok('!'));
96/// assert_eq!(parser.parse("?").map(|x| x.0), Ok('?'));
97/// # }
98/// ```
99pub fn satisfy<I, P>(predicate: P) -> Satisfy<I, P>
100    where I: Stream, P: FnMut(I::Item) -> bool {
101    Satisfy { predicate: predicate, _marker: PhantomData }
102}
103
104#[derive(Clone)]
105pub struct Token<I>
106    where I: Stream
107        , I::Item: PartialEq {
108    c: I::Item,
109    _marker: PhantomData<I>
110}
111
112impl <I> Parser for Token<I>
113    where I: Stream
114        , I::Item: PartialEq {
115
116    type Input = I;
117    type Output = I::Item;
118    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<I::Item, I, I::Item> {
119        satisfy_impl(input, &mut |c| c == self.c, |pos, _| ParseError::empty(pos))
120    }
121    fn add_error(&mut self, error: &mut ParseError<<Self::Input as Stream>::Item>) {
122        error.errors.push(Error::Expected(self.c.clone().into()));
123    }
124}
125
126///Parses a character and succeeds if the characther is equal to `c`
127///
128/// ```
129/// # extern crate parser_combinators as pc;
130/// # use pc::*;
131/// # fn main() {
132/// let result = token('!')
133///     .parse("!")
134///     .map(|x| x.0);
135/// assert_eq!(result, Ok('!'));
136/// # }
137/// ```
138pub fn token<I>(c: I::Item) -> Token<I>
139    where I: Stream
140        , I::Item: PartialEq {
141    Token { c: c, _marker: PhantomData }
142}
143
144pub struct Choice<S, P>(S, PhantomData<P>);
145
146impl <I, O, S, P> Parser for Choice<S, P>
147    where I: Stream
148        , S: AsMut<[P]>
149        , P: Parser<Input=I, Output=O> {
150    type Input = I;
151    type Output = O;
152    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
153        let mut empty_err = None;
154        for p in AsMut::as_mut(&mut self.0) {
155            match p.parse_lazy(input.clone()) {
156                consumed_err@Err(Consumed::Consumed(_)) => return consumed_err,
157                Err(Consumed::Empty(err)) => {
158                    empty_err = match empty_err {
159                        None => Some(err),
160                        Some(prev_err) => Some(prev_err.merge(err)),
161                    };
162                },
163                ok@Ok(_) => return ok,
164            }
165        }
166        Err(Consumed::Empty(match empty_err {
167            None => ParseError::new(input.position.clone(), Error::Message("parser choice is empty".into())),
168            Some(err) => err,
169        }))
170    }
171    fn add_error(&mut self, error: &mut ParseError<<Self::Input as Stream>::Item>) {
172        for p in self.0.as_mut() {
173            p.add_error(error);
174        }
175    }
176}
177
178/// Takes an array of parsers and tries them each in turn.
179/// Fails if all parsers fails or when a parsers fails with a consumed state.
180///
181/// ```
182/// # extern crate parser_combinators as pc;
183/// # use pc::*;
184/// # use pc::primitives::Error;
185/// # fn main() {
186/// let mut parser = choice([string("Apple"), string("Banana"), string("Orange")]);
187/// assert_eq!(parser.parse("Banana"), Ok(("Banana", "")));
188/// assert_eq!(parser.parse("Orangexx"), Ok(("Orange", "xx")));
189/// assert!(parser.parse("Appl").is_err());
190/// assert!(parser.parse("Pear").is_err());
191/// # }
192/// ```
193pub fn choice<S, P>(ps: S) -> Choice<S, P>
194    where S: AsMut<[P]>
195        , P: Parser {
196    Choice(ps, PhantomData)
197}
198
199#[derive(Clone)]
200pub struct Unexpected<I>(Info<I::Item>, PhantomData<fn (I) -> I>)
201    where I: Stream;
202impl <I> Parser for Unexpected<I>
203    where I : Stream {
204    type Input = I;
205    type Output = ();
206    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<(), I, I::Item> {
207        Err(Consumed::Empty(ParseError::empty(input.position)))
208    }
209    fn add_error(&mut self, error: &mut ParseError<<Self::Input as Stream>::Item>) {
210        error.errors.push(Error::Message(self.0.clone()));
211    }
212}
213///Always fails with `message` as the error.
214///Never consumes any input.
215///
216/// ```
217/// # extern crate parser_combinators as pc;
218/// # use pc::*;
219/// # use pc::primitives::Error;
220/// # fn main() {
221/// let result = unexpected("token")
222///     .parse("a");
223/// assert!(result.is_err());
224/// assert!(result.err().unwrap().errors.iter().any(|m| *m == Error::Message("token".into())));
225/// # }
226/// ```
227pub fn unexpected<I, S>(message: S) -> Unexpected<I>
228    where I: Stream
229        , S: Into<Info<I::Item>> {
230    Unexpected(message.into(), PhantomData)
231}
232
233#[derive(Clone)]
234pub struct Value<I, T>(T, PhantomData<fn (I) -> I>);
235impl <I, T> Parser for Value<I, T>
236    where I: Stream
237        , T: Clone {
238    type Input = I;
239    type Output = T;
240    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<T, I, I::Item> {
241        Ok((self.0.clone(), Consumed::Empty(input)))
242    }
243}
244///Always returns the value `v` without consuming any input.
245///
246/// ```
247/// # extern crate parser_combinators as pc;
248/// # use pc::*;
249/// # fn main() {
250/// let result = value(42)
251///     .parse("hello world")
252///     .map(|x| x.0);
253/// assert_eq!(result, Ok(42));
254/// # }
255/// ```
256pub fn value<I, T>(v: T) -> Value<I, T>
257    where I: Stream
258        , T: Clone {
259    Value(v, PhantomData)
260}
261
262impl_parser! { NotFollowedBy(P,), Or<Then<Try<P>, fn(<P as Parser>::Output) -> Unexpected<<P as Parser>::Input>>, Value<<P as Parser>::Input, ()>> }
263///Succeeds only if `parser` fails.
264///Never consumes any input.
265///
266/// ```
267/// # extern crate parser_combinators as pc;
268/// # use pc::*;
269/// # fn main() {
270/// let result = string("let")
271///     .skip(not_followed_by(alpha_num()))
272///     .parse("letx")
273///     .map(|x| x.0);
274/// assert!(result.is_err());
275/// # }
276/// ```
277pub fn not_followed_by<P>(parser: P) -> NotFollowedBy<P>
278    where P: Parser
279        , <P as Parser>::Output: ::std::fmt::Display {
280    fn f<T: ::std::fmt::Display, I: Stream>(t: T) -> Unexpected<I> {
281        unexpected(format!("{}", t))
282    }
283    let f : fn (P::Output) -> Unexpected<P::Input> = f;
284    NotFollowedBy(try(parser).then(f)
285                 .or(value(())))
286}
287
288pub struct Iter<P: Parser> {
289    parser: P,
290    input: State<P::Input>,
291    error: Option<Consumed<ParseError<<P::Input as Stream>::Item>>>,
292    consumed: bool,
293}
294
295impl <P: Parser> Iter<P> {
296    fn new(parser: P, input: State<P::Input>) -> Iter<P> {
297        Iter { parser: parser, input: input, error: None, consumed: false }
298    }
299    ///Converts the iterator to a `ParseResult`, returning `Ok` if the parsing so far has be done
300    ///without any errors which consumed data.
301    pub fn into_result<O>(self, value: O) -> ParseResult<O, P::Input, <P::Input as Stream>::Item> {
302        match self.error {
303            Some(err@Consumed::Consumed(_)) => Err(err),
304            _ => if self.consumed { Ok((value, Consumed::Consumed(self.input))) }
305                 else { Ok((value, Consumed::Empty(self.input))) }
306        }
307    }
308}
309
310impl <P: Parser> Iterator for Iter<P> {
311    type Item = P::Output;
312    fn next(&mut self) -> Option<P::Output> {
313        if self.error.is_some() {
314            return None;
315        }
316        match self.parser.parse_lazy(self.input.clone()) {
317            Ok((value, rest)) => {
318                self.consumed = self.consumed || !rest.is_empty();
319                self.input = rest.into_inner();
320                Some(value)
321            }
322            Err(err) => {
323                self.error = Some(err);
324                None
325            }
326        }
327    }
328}
329
330#[derive(Clone)]
331pub struct Many<F, P>(P, PhantomData<F>)
332    where P: Parser;
333impl <F, P> Parser for Many<F, P>
334    where P: Parser, F: FromIterator<<P as Parser>::Output> {
335    type Input = <P as Parser>::Input;
336    type Output = F;
337    fn parse_state(&mut self, input: State<<P as Parser>::Input>) -> ParseResult<F, <P as Parser>::Input, <Self::Input as Stream>::Item> {
338        let mut iter = (&mut self.0).iter(input);
339        let result = iter.by_ref().collect();
340        iter.into_result(result)
341    }
342}
343
344///Parses `p` zero or more times returning a collection with the values from `p`.
345///If the returned collection cannot be inferred type annotations must be supplied, either by
346///annotating the resulting type binding `let collection: Vec<_> = ...` or by specializing when
347///calling many, `many::<Vec<_>, _>(...)`
348///
349/// ```
350/// # extern crate parser_combinators as pc;
351/// # use pc::*;
352/// # fn main() {
353/// let result = many(digit())
354///     .parse("123A")
355///     .map(|x| x.0);
356/// assert_eq!(result, Ok(vec!['1', '2', '3']));
357/// # }
358/// ```
359pub fn many<F, P>(p: P) -> Many<F, P>
360    where P: Parser, F: FromIterator<<P as Parser>::Output> {
361    Many(p, PhantomData)
362}
363
364
365#[derive(Clone)]
366pub struct Many1<F, P>(P, PhantomData<fn () -> F>);
367impl <F, P> Parser for Many1<F, P>
368    where F: FromIterator<<P as Parser>::Output>
369        , P: Parser {
370    type Input = <P as Parser>::Input;
371    type Output = F;
372    fn parse_lazy(&mut self, input: State<<P as Parser>::Input>) -> ParseResult<F, <P as Parser>::Input, <Self::Input as Stream>::Item> {
373        let (first, input) = try!(self.0.parse_lazy(input));
374		input.combine(move |input| {
375	        let mut iter = Iter::new(&mut self.0, input);
376	        let result = Some(first).into_iter()
377	            .chain(iter.by_ref())
378	            .collect();
379	        iter.into_result(result)
380		})
381    }
382    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
383        self.0.add_error(errors)
384    }
385}
386
387impl_parser!{ SkipMany(P,), Map<Many<Vec<()>, Map<P, fn (<P as Parser>::Output)>>, fn (Vec<()>)> }
388///Parses `p` zero or more times ignoring the result
389///
390/// ```
391/// # extern crate parser_combinators as pc;
392/// # use pc::*;
393/// # fn main() {
394/// let result = skip_many(digit())
395///     .parse("A");
396/// assert_eq!(result, Ok(((), "A")));
397/// # }
398/// ```
399pub fn skip_many<P>(p: P) -> SkipMany<P>
400    where P: Parser {
401    fn ignore<T>(_: T) {  }
402    let ignore1: fn (P::Output) = ignore;
403    let ignore2: fn (Vec<()>) = ignore;
404    SkipMany(many(p.map(ignore1)).map(ignore2))
405}
406
407impl_parser!{ SkipMany1(P,), Map<Many1<Vec<()>, Map<P, fn (<P as Parser>::Output)>>, fn (Vec<()>)> }
408///Parses `p` one or more times ignoring the result
409///
410/// ```
411/// # extern crate parser_combinators as pc;
412/// # use pc::*;
413/// # fn main() {
414/// let result = skip_many1(digit())
415///     .parse("123A");
416/// assert_eq!(result, Ok(((), "A")));
417/// # }
418/// ```
419pub fn skip_many1<P>(p: P) -> SkipMany1<P>
420    where P: Parser {
421    fn ignore<T>(_: T) {  }
422    let ignore1: fn (P::Output) = ignore;
423    let ignore2: fn (Vec<()>) = ignore;
424    SkipMany1(many1(p.map(ignore1)).map(ignore2))
425}
426
427///Parses `p` one or more times returning a collection with the values from `p`.
428///If the returned collection cannot be inferred type annotations must be supplied, either by
429///annotating the resulting type binding `let collection: Vec<_> = ...` or by specializing when
430///calling many1 `many1::<Vec<_>, _>(...)`
431///
432///
433/// ```
434/// # extern crate parser_combinators as pc;
435/// # use pc::*;
436/// # fn main() {
437/// let result = many1::<Vec<_>, _>(digit())
438///     .parse("A123");
439/// assert!(result.is_err());
440/// # }
441/// ```
442pub fn many1<F, P>(p: P) -> Many1<F, P>
443    where F: FromIterator<<P as Parser>::Output>
444        , P: Parser {
445    Many1(p, PhantomData)
446}
447
448#[derive(Clone)]
449pub struct SepBy<F, P, S> {
450    parser: P,
451    separator: S,
452    _marker: PhantomData<fn () -> F>
453}
454impl <F, P, S> Parser for SepBy<F, P, S>
455    where F: FromIterator<<P as Parser>::Output>
456        , P: Parser
457        , S: Parser<Input=<P as Parser>::Input> {
458
459    type Input = <P as Parser>::Input;
460    type Output = F;
461    fn parse_lazy(&mut self, input: State<<P as Parser>::Input>) -> ParseResult<F, <P as Parser>::Input, <Self::Input as Stream>::Item> {
462        let mut input = Consumed::Empty(input);
463        let first;
464        match input.clone().combine(|input| self.parser.parse_lazy(input)) {
465            Ok((x, rest)) => {
466                input = rest;
467                first = x
468            }
469            Err(err@Consumed::Consumed(_)) => return Err(err),
470            Err(Consumed::Empty(_)) => return Ok((None.into_iter().collect(), input))
471        };
472
473        let (result, input) = try!(input.combine(move |input| {
474            let rest = (&mut self.separator)
475                .with(&mut self.parser);
476	        let mut iter = Iter::new(rest, input);
477	        let result = Some(first).into_iter()
478	            .chain(iter.by_ref())
479	            .collect();
480        	iter.into_result(result)
481        }));
482        Ok((result, input))
483    }
484    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
485        self.parser.add_error(errors)
486    }
487}
488
489///Parses `parser` zero or more time separated by `separator`, returning a collection with the values from `p`.
490///If the returned collection cannot be inferred type annotations must be supplied, either by
491///annotating the resulting type binding `let collection: Vec<_> = ...` or by specializing when
492///calling sep_by, `sep_by::<Vec<_>, _, _>(...)`
493///
494/// ```
495/// # extern crate parser_combinators as pc;
496/// # use pc::*;
497/// # fn main() {
498/// let mut parser = sep_by(digit(), token(','));
499/// let result_ok = parser.parse("1,2,3");
500/// assert_eq!(result_ok, Ok((vec!['1', '2', '3'], "")));
501/// let result_ok2 = parser.parse("");
502/// assert_eq!(result_ok2, Ok((vec![], "")));
503/// # }
504/// ```
505pub fn sep_by<F, P, S>(parser: P, separator: S) -> SepBy<F, P, S>
506    where F: FromIterator<<P as Parser>::Output>
507        , P: Parser
508        , S: Parser<Input=<P as Parser>::Input> {
509    SepBy { parser: parser, separator: separator, _marker: PhantomData }
510}
511
512
513impl <'a, I: Stream, O> Parser for FnMut(State<I>) -> ParseResult<O, I, I::Item> + 'a {
514    type Input = I;
515    type Output = O;
516    fn parse_state(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
517        self(input)
518    }
519}
520#[derive(Clone)]
521pub struct FnParser<I, F>(F, PhantomData<fn (I) -> I>);
522
523///Wraps a function, turning it into a parser
524///Mainly needed to turn closures into parsers as function types can be casted to function pointers
525///to make them usable as a parser
526///
527/// ```
528/// extern crate parser_combinators as pc;
529/// use pc::*;
530/// use pc::primitives::{Consumed, Error};
531/// # fn main() {
532/// let mut even_digit = parser(|input| {
533///     let position = input.position;
534///     let (char_digit, input) = try!(digit().parse_state(input));
535///     let d = (char_digit as i32) - ('0' as i32);
536///     if d % 2 == 0 {
537///         Ok((d, input))
538///     }
539///     else {
540///         //Return an empty error since we only tested the first token of the stream
541///         Err(Consumed::Empty(ParseError::new(position, Error::Expected(From::from("even number")))))
542///     }
543/// });
544/// let result = even_digit
545///     .parse("8")
546///     .map(|x| x.0);
547/// assert_eq!(result, Ok(8));
548/// # }
549/// ```
550pub fn parser<I, O, F>(f: F) -> FnParser<I, F>
551    where I: Stream
552        , F: FnMut(State<I>) -> ParseResult<O, I, I::Item> {
553    FnParser(f, PhantomData)
554}
555
556impl <I, O, F> Parser for FnParser<I, F>
557    where I: Stream, F: FnMut(State<I>) -> ParseResult<O, I, I::Item> {
558    type Input = I;
559    type Output = O;
560    fn parse_state(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
561        (self.0)(input)
562    }
563}
564
565impl <I, O> Parser for fn (State<I>) -> ParseResult<O, I, I::Item>
566    where I: Stream {
567    type Input = I;
568    type Output = O;
569    fn parse_state(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
570        self(input)
571    }
572}
573
574#[derive(Clone)]
575pub struct Optional<P>(P);
576impl <P> Parser for Optional<P>
577    where P: Parser {
578    type Input = <P as Parser>::Input;
579    type Output = Option<<P as Parser>::Output>;
580    fn parse_lazy(&mut self, input: State<<P as Parser>::Input>) -> ParseResult<Option<<P as Parser>::Output>, <P as Parser>::Input, <Self::Input as Stream>::Item> {
581        match self.0.parse_state(input.clone()) {
582            Ok((x, rest)) => Ok((Some(x), rest)),
583            Err(err@Consumed::Consumed(_)) => return Err(err),
584            Err(Consumed::Empty(_)) => Ok((None, Consumed::Empty(input)))
585        }
586    }
587}
588
589///Returns `Some(value)` and `None` on parse failure (always succeeds)
590///
591/// ```
592/// # extern crate parser_combinators as pc;
593/// # use pc::*;
594/// # fn main() {
595/// let mut parser = optional(digit());
596/// let result1 = parser.parse("a");
597/// assert_eq!(result1, Ok((None, "a")));
598/// let result2 = parser.parse("1");
599/// assert_eq!(result2, Ok((Some('1'), "")));
600/// # }
601/// ```
602pub fn optional<P>(parser: P) -> Optional<P>
603    where P: Parser {
604    Optional(parser)
605}
606
607impl_parser! { Between(L, R, P), Skip<With<L, P>, R> }
608///Parses `open` followed by `parser` followed by `close`
609///Returns the value of `parser`
610///
611/// ```
612/// # extern crate parser_combinators as pc;
613/// # use pc::*;
614/// # fn main() {
615/// let result = between(token('['), token(']'), string("rust"))
616///     .parse("[rust]")
617///     .map(|x| x.0);
618/// assert_eq!(result, Ok("rust"));
619/// # }
620/// ```
621pub fn between<I, L, R, P>(open: L, close: R, parser: P) -> Between<L, R, P>
622    where I: Stream
623        , L: Parser<Input=I>
624        , R: Parser<Input=I>
625        , P: Parser<Input=I> {
626    Between(open.with(parser).skip(close))
627}
628
629#[derive(Clone)]
630pub struct Chainl1<P, Op>(P, Op);
631impl <I, O, P, Op> Parser for Chainl1<P, Op>
632    where I: Stream
633        , P: Parser<Input=I, Output=O>
634        , Op: Parser<Input=I>
635        , Op::Output: FnOnce(O, O) -> O {
636
637    type Input = I;
638    type Output = O;
639    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
640        let (mut l, mut input) = try!(self.0.parse_lazy(input));
641        loop {
642            let was_empty = input.is_empty();
643            let rest = input.clone().into_inner();
644            match (&mut self.1).and(&mut self.0).parse_lazy(rest) {
645                Ok(((op, r), rest)) => {
646                    l = op(l, r);
647                    input = if was_empty { rest } else { rest.as_consumed() };
648                }
649                Err(err@Consumed::Consumed(_)) => return Err(err),
650                Err(Consumed::Empty(_)) => break
651            }
652        }
653        Ok((l, input))
654    }
655    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
656        self.0.add_error(errors)
657    }
658}
659
660///Parses `p` 1 or more times separated by `op`
661///The value returned is the one produced by the left associative application of `op`
662pub fn chainl1<P, Op>(parser: P, op: Op) -> Chainl1<P, Op>
663    where P: Parser
664        , Op: Parser<Input=P::Input>
665        , Op::Output: FnOnce(P::Output, P::Output) -> P::Output {
666    Chainl1(parser, op)
667}
668
669#[derive(Clone)]
670pub struct Chainr1<P, Op>(P, Op);
671impl <I, O, P, Op> Parser for Chainr1<P, Op>
672    where I: Stream
673        , P: Parser<Input=I, Output=O>
674        , Op: Parser<Input=I>
675        , Op::Output: FnOnce(O, O) -> O {
676
677    type Input = I;
678    type Output = O;
679    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
680        let (mut l, mut input) = try!(self.0.parse_lazy(input));
681        loop {
682            let was_empty = input.is_empty();
683            let rest = input.clone().into_inner();
684            let op = match self.1.parse_lazy(rest) {
685                Ok((x, rest)) => {
686                    input = if was_empty { rest } else { rest.as_consumed() };
687                    x
688                }
689                Err(err@Consumed::Consumed(_)) => return Err(err),
690                Err(Consumed::Empty(_)) => break
691            };
692            let was_empty = was_empty && input.is_empty();
693            let rest = input.clone().into_inner();
694            match self.parse_lazy(rest) {
695                Ok((r, rest)) => {
696                    l = op(l, r);
697                    input = if was_empty { rest } else { rest.as_consumed() };
698                }
699                Err(err@Consumed::Consumed(_)) => return Err(err),
700                Err(Consumed::Empty(_)) => break
701            }
702            
703
704        }
705        Ok((l, input))
706    }
707    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
708        self.0.add_error(errors)
709    }
710}
711
712///Parses `p` one or more times separated by `op`
713///The value returned is the one produced by the right associative application of `op`
714pub fn chainr1<P, Op>(parser: P, op: Op) -> Chainr1<P, Op>
715    where P: Parser
716        , Op: Parser<Input=P::Input>
717        , Op::Output: FnOnce(P::Output, P::Output) -> P::Output {
718    Chainr1(parser, op)
719}
720
721#[derive(Clone)]
722pub struct Try<P>(P);
723impl <I, O, P> Parser for Try<P>
724    where I: Stream
725        , P: Parser<Input=I, Output=O> {
726
727    type Input = I;
728    type Output = O;
729    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
730        self.0.parse_state(input)
731            .map_err(Consumed::as_empty)
732    }
733    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
734        self.0.add_error(errors)
735    }
736}
737
738///Try acts as `p` except it acts as if the parser hadn't consumed any input
739///if `p` returns an error after consuming input
740///
741/// ```
742/// # extern crate parser_combinators as pc;
743/// # use pc::*;
744/// # fn main() {
745/// let mut p = try(string("let"))
746///     .or(string("lex"));
747/// let result = p.parse("lex").map(|x| x.0);
748/// assert_eq!(result, Ok("lex"));
749/// let result = p.parse("aet").map(|x| x.0);
750/// assert!(result.is_err());
751/// # }
752/// ```
753pub fn try<P>(p : P) -> Try<P>
754    where P: Parser {
755    Try(p)
756}
757
758#[derive(Clone)]
759pub struct And<P1, P2>(P1, P2);
760impl <I, A, B, P1, P2> Parser for And<P1, P2>
761    where I: Stream, P1: Parser<Input=I, Output=A>, P2: Parser<Input=I, Output=B> {
762
763    type Input = I;
764    type Output = (A, B);
765    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<(A, B), I, I::Item> {
766        let (a, rest) = try!(self.0.parse_lazy(input));
767        rest.combine(move |rest| {
768            let (b, rest) = try!(self.1.parse_state(rest));
769            Ok(((a, b), rest))
770        })
771    }
772    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
773        self.0.add_error(errors)
774    }
775}
776
777#[derive(Clone)]
778pub struct With<P1, P2>(P1, P2) where P1: Parser, P2: Parser;
779impl <I, P1, P2> Parser for With<P1, P2>
780    where I: Stream, P1: Parser<Input=I>, P2: Parser<Input=I> {
781
782    type Input = I;
783    type Output = <P2 as Parser>::Output;
784    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<<Self as Parser>::Output, I, I::Item> {
785        let ((_, b), rest) = try!((&mut self.0).and(&mut self.1).parse_lazy(input));
786        Ok((b, rest))
787    }
788    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
789        self.0.add_error(errors)
790    }
791}
792
793#[derive(Clone)]
794pub struct Skip<P1, P2>(P1, P2) where P1: Parser, P2: Parser;
795impl <I, P1, P2> Parser for Skip<P1, P2>
796    where I: Stream, P1: Parser<Input=I>, P2: Parser<Input=I> {
797
798    type Input = I;
799    type Output = <P1 as Parser>::Output;
800    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<<Self as Parser>::Output, I, I::Item> {
801        let ((a, _), rest) = try!((&mut self.0).and(&mut self.1).parse_lazy(input));
802        Ok((a, rest))
803    }
804    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
805        self.0.add_error(errors)
806    }
807}
808
809#[derive(Clone)]
810pub struct Message<P>(P, Info<<P::Input as Stream>::Item>)
811    where P: Parser;
812impl <I, P> Parser for Message<P>
813    where I: Stream, P: Parser<Input=I> {
814
815    type Input = I;
816    type Output = <P as Parser>::Output;
817    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<<Self as Parser>::Output, I, I::Item> {
818        self.0.parse_lazy(input.clone())
819    }
820    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
821        self.0.add_error(errors);
822        errors.add_message(self.1.clone());
823    }
824}
825
826#[derive(Clone)]
827pub struct Or<P1, P2>(P1, P2) where P1: Parser, P2: Parser;
828impl <I, O, P1, P2> Parser for Or<P1, P2>
829    where I: Stream, P1: Parser<Input=I, Output=O>, P2: Parser<Input=I, Output=O> {
830
831    type Input = I;
832    type Output = O;
833    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<O, I, I::Item> {
834        match self.0.parse_lazy(input.clone()) {
835            Ok(x) => Ok(x),
836            Err(err@Consumed::Consumed(_)) => Err(err),
837            Err(Consumed::Empty(error1)) => {
838                match self.1.parse_lazy(input) {
839                    Ok(x) => Ok(x),
840                    Err(err@Consumed::Consumed(_)) => Err(err),
841                    Err(Consumed::Empty(error2)) => Err(Consumed::Empty(error1.merge(error2)))
842                }
843            }
844        }
845    }
846    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
847        self.0.add_error(errors);
848        self.1.add_error(errors);
849    }
850}
851
852#[derive(Clone)]
853pub struct Map<P, F>(P, F);
854impl <I, A, B, P, F> Parser for Map<P, F>
855    where I: Stream, P: Parser<Input=I, Output=A>, F: FnMut(A) -> B {
856
857    type Input = I;
858    type Output = B;
859    fn parse_lazy(&mut self, input: State<I>) -> ParseResult<B, I, I::Item> {
860        match self.0.parse_lazy(input) {
861            Ok((x, input)) => Ok(((self.1)(x), input)),
862            Err(err) => Err(err)
863        }
864    }
865    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
866        self.0.add_error(errors);
867    }
868}
869
870#[derive(Clone)]
871pub struct Then<P, F>(P, F);
872impl <P, N, F> Parser for Then<P, F>
873    where F: FnMut(<P as Parser>::Output) -> N
874        , P: Parser
875        , N: Parser<Input=<P as Parser>::Input> {
876
877    type Input = <N as Parser>::Input;
878    type Output = <N as Parser>::Output;
879    fn parse_lazy(&mut self, input: State<<Self as Parser>::Input>) -> ParseResult<<Self as Parser>::Output, <Self as Parser>::Input, <Self::Input as Stream>::Item> {
880        let (value, input) = try!(self.0.parse_lazy(input));
881        input.combine(move |input| {
882            let mut next = (self.1)(value);
883            next.parse_state(input)
884        })
885    }
886    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
887        self.0.add_error(errors);
888    }
889}
890
891#[derive(Clone)]
892pub struct Expected<P>(P, Info<<P::Input as Stream>::Item>)
893    where P: Parser;
894impl <P> Parser for Expected<P>
895    where P: Parser {
896
897    type Input = <P as Parser>::Input;
898    type Output = <P as Parser>::Output;
899    fn parse_lazy(&mut self, input: State<<Self as Parser>::Input>) -> ParseResult<<Self as Parser>::Output, <Self as Parser>::Input, <Self::Input as Stream>::Item> {
900        self.0.parse_lazy(input)
901    }
902    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
903        let start = errors.errors.len();
904        self.0.add_error(errors);
905        //Replace all expected errors that where added from the previous add_error
906        //with this expected error
907        let mut i = 0;
908        errors.errors.retain(|e| {
909            if i < start {
910                i += 1;
911                true
912            }
913            else {
914                match *e { Error::Expected(_) => false, _ => true }
915            }
916        });
917        errors.add_error(Error::Expected(self.1.clone()));
918    }
919}
920
921pub struct AndThen<P, F>(P, F);
922impl <P, F, O, E> Parser for AndThen<P, F>
923    where P: Parser
924        , F: FnMut(P::Output) -> Result<O, E>
925        , E: Into<Error<<P::Input as Stream>::Item>> {
926
927    type Input = <P as Parser>::Input;
928    type Output = O;
929    fn parse_lazy(&mut self, input: State<<Self as Parser>::Input>) -> ParseResult<O, <Self as Parser>::Input, <Self::Input as Stream>::Item> {
930        self.0.parse_lazy(input)
931            .and_then(|(o, input)|
932                match (self.1)(o) {
933                    Ok(o) => Ok((o, input)),
934                    Err(err) => Err(input.map(move |input| ParseError::new(input.position, err.into())))
935                }
936            )
937    }
938    fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
939        self.0.add_error(errors);
940    }
941}
942
943///Extension trait which provides functions that are more conveniently used through method calls
944pub trait ParserExt : Parser + Sized {
945
946    ///Discards the value of the `self` parser and returns the value of `p`
947    ///Fails if any of the parsers fails
948    ///
949    /// ```
950    /// # extern crate parser_combinators as pc;
951    /// # use pc::*;
952    /// # fn main() {
953    /// let result = digit()
954    ///     .with(token('i'))
955    ///     .parse("9i")
956    ///     .map(|x| x.0);
957    /// assert_eq!(result, Ok('i'));
958    /// # }
959    /// ```
960    fn with<P2>(self, p: P2) -> With<Self, P2>
961        where P2: Parser<Input=Self::Input> {
962        With(self, p)
963    }
964
965    ///Discards the value of the `p` parser and returns the value of `self`
966    ///Fails if any of the parsers fails
967    ///
968    /// ```
969    /// # extern crate parser_combinators as pc;
970    /// # use pc::*;
971    /// # fn main() {
972    /// let result = digit()
973    ///     .skip(token('i'))
974    ///     .parse("9i")
975    ///     .map(|x| x.0);
976    /// assert_eq!(result, Ok('9'));
977    /// # }
978    /// ```
979    fn skip<P2>(self, p: P2) -> Skip<Self, P2>
980        where P2: Parser<Input=Self::Input> {
981        Skip(self, p)
982    }
983
984    ///Parses with `self` followed by `p`
985    ///Succeds if both parsers succed, otherwise fails
986    ///Returns a tuple with both values on success
987    ///
988    /// ```
989    /// # extern crate parser_combinators as pc;
990    /// # use pc::*;
991    /// # fn main() {
992    /// let result = digit()
993    ///     .and(token('i'))
994    ///     .parse("9i")
995    ///     .map(|x| x.0);
996    /// assert_eq!(result, Ok(('9', 'i')));
997    /// # }
998    /// ```
999    fn and<P2>(self, p: P2) -> And<Self, P2>
1000        where P2: Parser<Input=Self::Input> {
1001        And(self, p)
1002    }
1003    ///Tries to parse using `self` and if it fails returns the result of parsing `p`
1004    ///
1005    /// ```
1006    /// # extern crate parser_combinators as pc;
1007    /// # use pc::*;
1008    /// # fn main() {
1009    /// let result = digit().map(|_| "")
1010    ///     .or(string("let"))
1011    ///     .parse("let")
1012    ///     .map(|x| x.0);
1013    /// assert_eq!(result, Ok("let"));
1014    /// # }
1015    /// ```
1016    fn or<P2>(self, p: P2) -> Or<Self, P2>
1017        where P2: Parser<Input=Self::Input> {
1018        Or(self, p)
1019    }
1020
1021    ///Parses using `self` and then passes the value to `f` which returns a parser used to parse
1022    ///the rest of the input
1023    ///
1024    /// ```
1025    /// # extern crate parser_combinators as pc;
1026    /// # use pc::*;
1027    /// # use pc::primitives::{Consumed, Error};
1028    /// # fn main() {
1029    /// let result = digit()
1030    ///     .then(|d| parser(move |input| {
1031    ///         if d == '9' {
1032    ///             Ok((9, Consumed::Empty(input)))
1033    ///         }
1034    ///         else {
1035    ///             let err = ParseError::new(input.position, Error::Message("Not a nine".into()));
1036    ///             Err((Consumed::Empty(err)))
1037    ///         }
1038    ///     }))
1039    ///     .parse("9");
1040    /// assert_eq!(result, Ok((9, "")));
1041    /// # }
1042    /// ```
1043    fn then<N, F>(self, f: F) -> Then<Self, F>
1044        where F: FnMut(Self::Output) -> N
1045            , N: Parser<Input=Self::Input> {
1046        Then(self, f)
1047    }
1048
1049    ///Uses `f` to map over the parsed value
1050    ///
1051    /// ```
1052    /// # extern crate parser_combinators as pc;
1053    /// # use pc::*;
1054    /// # fn main() {
1055    /// let result = digit()
1056    ///     .map(|c| c == '9')
1057    ///     .parse("9")
1058    ///     .map(|x| x.0);
1059    /// assert_eq!(result, Ok(true));
1060    /// # }
1061    /// ```
1062    fn map<F, B>(self, f: F) -> Map<Self, F>
1063        where F: FnMut(Self::Output) -> B {
1064        Map(self, f)
1065    }
1066
1067    ///Parses with `self` and if it fails, adds the message `msg` to the error
1068    ///
1069    /// ```
1070    /// # extern crate parser_combinators as pc;
1071    /// # use pc::*;
1072    /// # use pc::primitives::Error;
1073    /// # fn main() {
1074    /// let result = token('9')
1075    ///     .message("Not a nine")
1076    ///     .parse("8");
1077    /// assert!(result.is_err());
1078    /// assert!(result.unwrap_err().errors.iter()
1079    ///     .find(|e| **e == Error::Message("Not a nine".into())).is_some());
1080    /// # }
1081    /// ```
1082    fn message<S>(self, msg: S) -> Message<Self>
1083        where S: Into<Info<<Self::Input as Stream>::Item>> {
1084        Message(self, msg.into())
1085    }
1086
1087    ///Parses with `self` and if it fails without consuming any input any expected errors are replaced by
1088    ///`msg`. `msg` is then used in error messages as "Expected `msg`".
1089    ///
1090    /// ```
1091    /// # extern crate parser_combinators as pc;
1092    /// # use pc::*;
1093    /// # use pc::primitives::Error;
1094    /// # fn main() {
1095    /// let result = token('9')
1096    ///     .expected("9")
1097    ///     .parse("8");
1098    /// assert!(result.is_err());
1099    /// assert!(result.unwrap_err().errors.iter()
1100    ///     .find(|e| **e == Error::Expected("9".into())).is_some());
1101    /// # }
1102    /// ```
1103    fn expected<S>(self, msg: S) -> Expected<Self>
1104        where S: Into<Info<<Self::Input as Stream>::Item>> {
1105        Expected(self, msg.into())
1106    }
1107
1108    ///Parses with `self` and applies `f` on the result if `self` parses successfully
1109    ///`f` may optionally fail with an error which is automatically converted to a `ParseError`
1110    ///
1111    /// ```
1112    /// # extern crate parser_combinators as pc;
1113    /// # use pc::*;
1114    /// # fn main() {
1115    /// let mut parser = many1(digit())
1116    ///     .and_then(|s: String| s.parse::<i32>());
1117    /// let result = parser.parse("1234");
1118    /// assert_eq!(result, Ok((1234, "")));
1119    /// let err = parser.parse("abc");
1120    /// assert!(err.is_err());
1121    /// # }
1122    /// ```
1123    fn and_then<F, O, E>(self, f: F) -> AndThen<Self, F>
1124        where F: FnMut(Self::Output) -> Result<O, E>
1125            , E: Into<Error<<Self::Input as Stream>::Item>> {
1126        AndThen(self, f)
1127    }
1128
1129    ///Creates an iterator from a parser and a state. Can be used as an alternative to `many` when
1130    ///collecting directly into a `FromIterator` type is not desirable
1131    ///
1132    /// ```
1133    /// # extern crate parser_combinators as pc;
1134    /// # use pc::*;
1135    /// # fn main() {
1136    /// let mut buffer = String::new();
1137    /// let number = parser(|input| {
1138    ///     buffer.clear();
1139    ///     let mut iter = digit().iter(input);
1140    ///     buffer.extend(&mut iter);
1141    ///     let i = buffer.parse::<i32>().unwrap();
1142    ///     iter.into_result(i)
1143    /// });
1144    /// let result = sep_by(number, char(','))
1145    ///     .parse("123,45,6");
1146    /// assert_eq!(result, Ok((vec![123, 45, 6], "")));
1147    /// # }
1148    /// ```
1149    fn iter(self, input: State<Self::Input>) -> Iter<Self> {
1150        Iter::new(self, input)
1151    }
1152}
1153
1154impl <P: Parser> ParserExt for P { }
1155
1156macro_rules! tuple_parser {
1157    ($h: ident, $($id: ident),+) => {
1158        impl <Input: Stream, $h: Parser<Input=Input>, $($id: Parser<Input=Input>),+> Parser for ($h, $($id),+) {
1159            type Input = Input;
1160            type Output = ($h::Output, $($id::Output),+);
1161            #[allow(non_snake_case)]
1162            fn parse_lazy(&mut self, input: State<Input>) -> ParseResult<($h::Output, $($id::Output),+), Input, Input::Item> {
1163                let (ref mut $h, $(ref mut $id),+) = *self;
1164                let ($h, input) = try!($h.parse_lazy(input));
1165                $(let ($id, input) = try!(input.combine(|input| $id.parse_state(input)));)+
1166                Ok((($h, $($id),+), input))
1167            }
1168            fn add_error(&mut self, errors: &mut ParseError<<Self::Input as Stream>::Item>) {
1169                self.0.add_error(errors);
1170            }
1171        }
1172    }
1173}
1174
1175tuple_parser!(A, B);
1176tuple_parser!(A, B, C);
1177tuple_parser!(A, B, C, D);
1178tuple_parser!(A, B, C, D, E);
1179tuple_parser!(A, B, C, D, E, F);
1180tuple_parser!(A, B, C, D, E, F, G);
1181tuple_parser!(A, B, C, D, E, F, G, H);
1182tuple_parser!(A, B, C, D, E, F, G, H, I);
1183tuple_parser!(A, B, C, D, E, F, G, H, I, J);
1184tuple_parser!(A, B, C, D, E, F, G, H, I, J, K);
1185tuple_parser!(A, B, C, D, E, F, G, H, I, J, K, L);
1186
1187#[cfg(test)]
1188mod tests {
1189    use super::*;
1190    use primitives::{Error, ParseError, Positioner, Parser};
1191    use char::{digit, letter};
1192
1193    #[test]
1194    fn choice_empty() {
1195        let mut parser = choice::<&mut [Token<&str>], Token<&str>>(&mut []);
1196        let result_err = parser.parse("a");
1197        assert!(result_err.is_err());
1198    }
1199    #[test]
1200    fn sep_by_consumed_error() {
1201        let mut parser2 = sep_by((letter(), letter()), token(','));
1202        let result_err: Result<(Vec<(char, char)>, &str), ParseError<char>> = parser2.parse("a,bc");
1203        assert!(result_err.is_err());
1204    }
1205    #[test]
1206    fn chainr1_test() {
1207        fn pow(l: i32, r: i32) -> i32 { l.pow(r as u32) }
1208
1209        let number = digit::<&str>().map(|c| c.to_digit(10).unwrap() as i32);
1210        let pow = token('^').map(|_| pow);
1211        let mut parser = chainr1(number, pow);
1212        assert_eq!(parser.parse("2^3^2"), Ok((512, "")));
1213    }
1214    
1215    #[test]
1216    fn tuple() {
1217        let mut parser = (digit(), token(','), digit(), token(','), letter());
1218        assert_eq!(parser.parse("1,2,z"), Ok((('1', ',', '2', ',', 'z'), "")));
1219    }
1220
1221    ///The expected combinator should retain only errors that are not `Expected`
1222    #[test]
1223    fn expected_retain_errors() {
1224        let mut parser = digit()
1225            .message("message")
1226            .expected("N/A")
1227            .expected("my expected digit");
1228        assert_eq!(parser.parse("a"), Err(ParseError {
1229            position: char::start(),
1230            errors: vec![Error::Unexpected('a'.into()),
1231                         Error::Message("message".into()),
1232                         Error::Expected("my expected digit".into())]
1233        }));
1234    }
1235    #[test]
1236    fn tuple_parse_error() {
1237        let mut parser = (digit(), digit());
1238        let result = parser.parse("a");
1239        assert_eq!(result, Err(ParseError {
1240            position: char::start(),
1241            errors: vec![
1242                Error::Unexpected('a'.into()),
1243                Error::Expected("digit".into())]
1244        }));
1245    }
1246}