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
39pub 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
88pub 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
126pub 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
178pub 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}
213pub 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}
244pub 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, ()>> }
263pub 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 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
344pub 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<()>)> }
388pub 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<()>)> }
408pub 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
427pub 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
489pub 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
523pub 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
589pub 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> }
608pub 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
660pub 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
712pub 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
738pub 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 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
943pub trait ParserExt : Parser + Sized {
945
946 fn with<P2>(self, p: P2) -> With<Self, P2>
961 where P2: Parser<Input=Self::Input> {
962 With(self, p)
963 }
964
965 fn skip<P2>(self, p: P2) -> Skip<Self, P2>
980 where P2: Parser<Input=Self::Input> {
981 Skip(self, p)
982 }
983
984 fn and<P2>(self, p: P2) -> And<Self, P2>
1000 where P2: Parser<Input=Self::Input> {
1001 And(self, p)
1002 }
1003 fn or<P2>(self, p: P2) -> Or<Self, P2>
1017 where P2: Parser<Input=Self::Input> {
1018 Or(self, p)
1019 }
1020
1021 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 fn map<F, B>(self, f: F) -> Map<Self, F>
1063 where F: FnMut(Self::Output) -> B {
1064 Map(self, f)
1065 }
1066
1067 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 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 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 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 #[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}