1 //! Choice combinators
2 
3 #[macro_use]
4 mod macros;
5 
6 use crate::error::ErrorKind;
7 use crate::error::ParseError;
8 use crate::internal::{Err, IResult, Parser};
9 
10 /// Helper trait for the [alt()] combinator.
11 ///
12 /// This trait is implemented for tuples of up to 21 elements
13 pub trait Alt<I, O, E> {
14   /// Tests each parser in the tuple and returns the result of the first one that succeeds
choice(&mut self, input: I) -> IResult<I, O, E>15   fn choice(&mut self, input: I) -> IResult<I, O, E>;
16 }
17 
18 /// Tests a list of parsers one by one until one succeeds.
19 ///
20 /// It takes as argument a tuple of parsers. There is a maximum of 21
21 /// parsers. If you need more, it is possible to nest them in other `alt` calls,
22 /// like this: `alt(parser_a, alt(parser_b, parser_c))`
23 ///
24 /// ```rust
25 /// # #[macro_use] extern crate nom;
26 /// # use nom::{Err,error::ErrorKind, Needed, IResult};
27 /// use nom::character::complete::{alpha1, digit1};
28 /// use nom::branch::alt;
29 /// # fn main() {
30 /// fn parser(input: &str) -> IResult<&str, &str> {
31 ///   alt((alpha1, digit1))(input)
32 /// };
33 ///
34 /// // the first parser, alpha1, recognizes the input
35 /// assert_eq!(parser("abc"), Ok(("", "abc")));
36 ///
37 /// // the first parser returns an error, so alt tries the second one
38 /// assert_eq!(parser("123456"), Ok(("", "123456")));
39 ///
40 /// // both parsers failed, and with the default error type, alt will return the last error
41 /// assert_eq!(parser(" "), Err(Err::Error(error_position!(" ", ErrorKind::Digit))));
42 /// # }
43 /// ```
44 ///
45 /// With a custom error type, it is possible to have alt return the error of the parser
46 /// that went the farthest in the input data
alt<I: Clone, O, E: ParseError<I>, List: Alt<I, O, E>>( mut l: List, ) -> impl FnMut(I) -> IResult<I, O, E>47 pub fn alt<I: Clone, O, E: ParseError<I>, List: Alt<I, O, E>>(
48   mut l: List,
49 ) -> impl FnMut(I) -> IResult<I, O, E> {
50   move |i: I| l.choice(i)
51 }
52 
53 /// Helper trait for the [permutation()] combinator.
54 ///
55 /// This trait is implemented for tuples of up to 21 elements
56 pub trait Permutation<I, O, E> {
57   /// Tries to apply all parsers in the tuple in various orders until all of them succeed
permutation(&mut self, input: I) -> IResult<I, O, E>58   fn permutation(&mut self, input: I) -> IResult<I, O, E>;
59 }
60 
61 /// Applies a list of parsers in any order.
62 ///
63 /// Permutation will succeed if all of the child parsers succeeded.
64 /// It takes as argument a tuple of parsers, and returns a
65 /// tuple of the parser results.
66 ///
67 /// ```rust
68 /// # #[macro_use] extern crate nom;
69 /// # use nom::{Err,error::{Error, ErrorKind}, Needed, IResult};
70 /// use nom::character::complete::{alpha1, digit1};
71 /// use nom::branch::permutation;
72 /// # fn main() {
73 /// fn parser(input: &str) -> IResult<&str, (&str, &str)> {
74 ///   permutation((alpha1, digit1))(input)
75 /// }
76 ///
77 /// // permutation recognizes alphabetic characters then digit
78 /// assert_eq!(parser("abc123"), Ok(("", ("abc", "123"))));
79 ///
80 /// // but also in inverse order
81 /// assert_eq!(parser("123abc"), Ok(("", ("abc", "123"))));
82 ///
83 /// // it will fail if one of the parsers failed
84 /// assert_eq!(parser("abc;"), Err(Err::Error(Error::new(";", ErrorKind::Digit))));
85 /// # }
86 /// ```
87 ///
88 /// The parsers are applied greedily: if there are multiple unapplied parsers
89 /// that could parse the next slice of input, the first one is used.
90 /// ```rust
91 /// # use nom::{Err, error::{Error, ErrorKind}, IResult};
92 /// use nom::branch::permutation;
93 /// use nom::character::complete::{anychar, char};
94 ///
95 /// fn parser(input: &str) -> IResult<&str, (char, char)> {
96 ///   permutation((anychar, char('a')))(input)
97 /// }
98 ///
99 /// // anychar parses 'b', then char('a') parses 'a'
100 /// assert_eq!(parser("ba"), Ok(("", ('b', 'a'))));
101 ///
102 /// // anychar parses 'a', then char('a') fails on 'b',
103 /// // even though char('a') followed by anychar would succeed
104 /// assert_eq!(parser("ab"), Err(Err::Error(Error::new("b", ErrorKind::Char))));
105 /// ```
106 ///
permutation<I: Clone, O, E: ParseError<I>, List: Permutation<I, O, E>>( mut l: List, ) -> impl FnMut(I) -> IResult<I, O, E>107 pub fn permutation<I: Clone, O, E: ParseError<I>, List: Permutation<I, O, E>>(
108   mut l: List,
109 ) -> impl FnMut(I) -> IResult<I, O, E> {
110   move |i: I| l.permutation(i)
111 }
112 
113 macro_rules! alt_trait(
114   ($first:ident $second:ident $($id: ident)+) => (
115     alt_trait!(__impl $first $second; $($id)+);
116   );
117   (__impl $($current:ident)*; $head:ident $($id: ident)+) => (
118     alt_trait_impl!($($current)*);
119 
120     alt_trait!(__impl $($current)* $head; $($id)+);
121   );
122   (__impl $($current:ident)*; $head:ident) => (
123     alt_trait_impl!($($current)*);
124     alt_trait_impl!($($current)* $head);
125   );
126 );
127 
128 macro_rules! alt_trait_impl(
129   ($($id:ident)+) => (
130     impl<
131       Input: Clone, Output, Error: ParseError<Input>,
132       $($id: Parser<Input, Output, Error>),+
133     > Alt<Input, Output, Error> for ( $($id),+ ) {
134 
135       fn choice(&mut self, input: Input) -> IResult<Input, Output, Error> {
136         match self.0.parse(input.clone()) {
137           Err(Err::Error(e)) => alt_trait_inner!(1, self, input, e, $($id)+),
138           res => res,
139         }
140       }
141     }
142   );
143 );
144 
145 macro_rules! alt_trait_inner(
146   ($it:tt, $self:expr, $input:expr, $err:expr, $head:ident $($id:ident)+) => (
147     match $self.$it.parse($input.clone()) {
148       Err(Err::Error(e)) => {
149         let err = $err.or(e);
150         succ!($it, alt_trait_inner!($self, $input, err, $($id)+))
151       }
152       res => res,
153     }
154   );
155   ($it:tt, $self:expr, $input:expr, $err:expr, $head:ident) => (
156     Err(Err::Error(Error::append($input, ErrorKind::Alt, $err)))
157   );
158 );
159 
160 alt_trait!(A B C D E F G H I J K L M N O P Q R S T U);
161 
162 macro_rules! permutation_trait(
163   (
164     $name1:ident $ty1:ident $item1:ident
165     $name2:ident $ty2:ident $item2:ident
166     $($name3:ident $ty3:ident $item3:ident)*
167   ) => (
168     permutation_trait!(__impl $name1 $ty1 $item1, $name2 $ty2 $item2; $($name3 $ty3 $item3)*);
169   );
170   (
171     __impl $($name:ident $ty:ident $item:ident),+;
172     $name1:ident $ty1:ident $item1:ident $($name2:ident $ty2:ident $item2:ident)*
173   ) => (
174     permutation_trait_impl!($($name $ty $item),+);
175     permutation_trait!(__impl $($name $ty $item),+ , $name1 $ty1 $item1; $($name2 $ty2 $item2)*);
176   );
177   (__impl $($name:ident $ty:ident $item:ident),+;) => (
178     permutation_trait_impl!($($name $ty $item),+);
179   );
180 );
181 
182 macro_rules! permutation_trait_impl(
183   ($($name:ident $ty:ident $item:ident),+) => (
184     impl<
185       Input: Clone, $($ty),+ , Error: ParseError<Input>,
186       $($name: Parser<Input, $ty, Error>),+
187     > Permutation<Input, ( $($ty),+ ), Error> for ( $($name),+ ) {
188 
189       fn permutation(&mut self, mut input: Input) -> IResult<Input, ( $($ty),+ ), Error> {
190         let mut res = ($(Option::<$ty>::None),+);
191 
192         loop {
193           let mut err: Option<Error> = None;
194           permutation_trait_inner!(0, self, input, res, err, $($name)+);
195 
196           // If we reach here, every iterator has either been applied before,
197           // or errored on the remaining input
198           if let Some(err) = err {
199             // There are remaining parsers, and all errored on the remaining input
200             return Err(Err::Error(Error::append(input, ErrorKind::Permutation, err)));
201           }
202 
203           // All parsers were applied
204           match res {
205             ($(Some($item)),+) => return Ok((input, ($($item),+))),
206             _ => unreachable!(),
207           }
208         }
209       }
210     }
211   );
212 );
213 
214 macro_rules! permutation_trait_inner(
215   ($it:tt, $self:expr, $input:ident, $res:expr, $err:expr, $head:ident $($id:ident)*) => (
216     if $res.$it.is_none() {
217       match $self.$it.parse($input.clone()) {
218         Ok((i, o)) => {
219           $input = i;
220           $res.$it = Some(o);
221           continue;
222         }
223         Err(Err::Error(e)) => {
224           $err = Some(match $err {
225             Some(err) => err.or(e),
226             None => e,
227           });
228         }
229         Err(e) => return Err(e),
230       };
231     }
232     succ!($it, permutation_trait_inner!($self, $input, $res, $err, $($id)*));
233   );
234   ($it:tt, $self:expr, $input:ident, $res:expr, $err:expr,) => ();
235 );
236 
237 permutation_trait!(
238   FnA A a
239   FnB B b
240   FnC C c
241   FnD D d
242   FnE E e
243   FnF F f
244   FnG G g
245   FnH H h
246   FnI I i
247   FnJ J j
248   FnK K k
249   FnL L l
250   FnM M m
251   FnN N n
252   FnO O o
253   FnP P p
254   FnQ Q q
255   FnR R r
256   FnS S s
257   FnT T t
258   FnU U u
259 );
260