1 //! Combinators applying parsers in sequence
2 
3 #[macro_use]
4 mod macros;
5 
6 use crate::error::ParseError;
7 use crate::internal::{IResult, Parser};
8 
9 /// Gets an object from the first parser,
10 /// then gets another object from the second parser.
11 ///
12 /// # Arguments
13 /// * `first` The first parser to apply.
14 /// * `second` The second parser to apply.
15 /// ```rust
16 /// # use nom::{Err, error::ErrorKind, Needed};
17 /// # use nom::Needed::Size;
18 /// use nom::sequence::pair;
19 /// use nom::bytes::complete::tag;
20 ///
21 /// let mut parser = pair(tag("abc"), tag("efg"));
22 ///
23 /// assert_eq!(parser("abcefg"), Ok(("", ("abc", "efg"))));
24 /// assert_eq!(parser("abcefghij"), Ok(("hij", ("abc", "efg"))));
25 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
26 /// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
27 /// ```
pair<I, O1, O2, E: ParseError<I>, F, G>( mut first: F, mut second: G, ) -> impl FnMut(I) -> IResult<I, (O1, O2), E> where F: Parser<I, O1, E>, G: Parser<I, O2, E>,28 pub fn pair<I, O1, O2, E: ParseError<I>, F, G>(
29   mut first: F,
30   mut second: G,
31 ) -> impl FnMut(I) -> IResult<I, (O1, O2), E>
32 where
33   F: Parser<I, O1, E>,
34   G: Parser<I, O2, E>,
35 {
36   move |input: I| {
37     let (input, o1) = first.parse(input)?;
38     second.parse(input).map(|(i, o2)| (i, (o1, o2)))
39   }
40 }
41 
42 // this implementation is used for type inference issues in macros
43 #[doc(hidden)]
pairc<I, O1, O2, E: ParseError<I>, F, G>( input: I, first: F, second: G, ) -> IResult<I, (O1, O2), E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(I) -> IResult<I, O2, E>,44 pub fn pairc<I, O1, O2, E: ParseError<I>, F, G>(
45   input: I,
46   first: F,
47   second: G,
48 ) -> IResult<I, (O1, O2), E>
49 where
50   F: Fn(I) -> IResult<I, O1, E>,
51   G: Fn(I) -> IResult<I, O2, E>,
52 {
53   pair(first, second)(input)
54 }
55 
56 /// Matches an object from the first parser and discards it,
57 /// then gets an object from the second parser.
58 ///
59 /// # Arguments
60 /// * `first` The opening parser.
61 /// * `second` The second parser to get object.
62 /// ```rust
63 /// # use nom::{Err, error::ErrorKind, Needed};
64 /// # use nom::Needed::Size;
65 /// use nom::sequence::preceded;
66 /// use nom::bytes::complete::tag;
67 ///
68 /// let mut parser = preceded(tag("abc"), tag("efg"));
69 ///
70 /// assert_eq!(parser("abcefg"), Ok(("", "efg")));
71 /// assert_eq!(parser("abcefghij"), Ok(("hij", "efg")));
72 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
73 /// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
74 /// ```
preceded<I, O1, O2, E: ParseError<I>, F, G>( mut first: F, mut second: G, ) -> impl FnMut(I) -> IResult<I, O2, E> where F: Parser<I, O1, E>, G: Parser<I, O2, E>,75 pub fn preceded<I, O1, O2, E: ParseError<I>, F, G>(
76   mut first: F,
77   mut second: G,
78 ) -> impl FnMut(I) -> IResult<I, O2, E>
79 where
80   F: Parser<I, O1, E>,
81   G: Parser<I, O2, E>,
82 {
83   move |input: I| {
84     let (input, _) = first.parse(input)?;
85     second.parse(input)
86   }
87 }
88 
89 // this implementation is used for type inference issues in macros
90 #[doc(hidden)]
precededc<I, O1, O2, E: ParseError<I>, F, G>( input: I, first: F, second: G, ) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(I) -> IResult<I, O2, E>,91 pub fn precededc<I, O1, O2, E: ParseError<I>, F, G>(
92   input: I,
93   first: F,
94   second: G,
95 ) -> IResult<I, O2, E>
96 where
97   F: Fn(I) -> IResult<I, O1, E>,
98   G: Fn(I) -> IResult<I, O2, E>,
99 {
100   preceded(first, second)(input)
101 }
102 
103 /// Gets an object from the first parser,
104 /// then matches an object from the second parser and discards it.
105 ///
106 /// # Arguments
107 /// * `first` The first parser to apply.
108 /// * `second` The second parser to match an object.
109 /// ```rust
110 /// # use nom::{Err, error::ErrorKind, Needed};
111 /// # use nom::Needed::Size;
112 /// use nom::sequence::terminated;
113 /// use nom::bytes::complete::tag;
114 ///
115 /// let mut parser = terminated(tag("abc"), tag("efg"));
116 ///
117 /// assert_eq!(parser("abcefg"), Ok(("", "abc")));
118 /// assert_eq!(parser("abcefghij"), Ok(("hij", "abc")));
119 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
120 /// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
121 /// ```
terminated<I, O1, O2, E: ParseError<I>, F, G>( mut first: F, mut second: G, ) -> impl FnMut(I) -> IResult<I, O1, E> where F: Parser<I, O1, E>, G: Parser<I, O2, E>,122 pub fn terminated<I, O1, O2, E: ParseError<I>, F, G>(
123   mut first: F,
124   mut second: G,
125 ) -> impl FnMut(I) -> IResult<I, O1, E>
126 where
127   F: Parser<I, O1, E>,
128   G: Parser<I, O2, E>,
129 {
130   move |input: I| {
131     let (input, o1) = first.parse(input)?;
132     second.parse(input).map(|(i, _)| (i, o1))
133   }
134 }
135 
136 // this implementation is used for type inference issues in macros
137 #[doc(hidden)]
terminatedc<I, O1, O2, E: ParseError<I>, F, G>( input: I, first: F, second: G, ) -> IResult<I, O1, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(I) -> IResult<I, O2, E>,138 pub fn terminatedc<I, O1, O2, E: ParseError<I>, F, G>(
139   input: I,
140   first: F,
141   second: G,
142 ) -> IResult<I, O1, E>
143 where
144   F: Fn(I) -> IResult<I, O1, E>,
145   G: Fn(I) -> IResult<I, O2, E>,
146 {
147   terminated(first, second)(input)
148 }
149 
150 /// Gets an object from the first parser,
151 /// then matches an object from the sep_parser and discards it,
152 /// then gets another object from the second parser.
153 ///
154 /// # Arguments
155 /// * `first` The first parser to apply.
156 /// * `sep` The separator parser to apply.
157 /// * `second` The second parser to apply.
158 /// ```rust
159 /// # use nom::{Err, error::ErrorKind, Needed};
160 /// # use nom::Needed::Size;
161 /// use nom::sequence::separated_pair;
162 /// use nom::bytes::complete::tag;
163 ///
164 /// let mut parser = separated_pair(tag("abc"), tag("|"), tag("efg"));
165 ///
166 /// assert_eq!(parser("abc|efg"), Ok(("", ("abc", "efg"))));
167 /// assert_eq!(parser("abc|efghij"), Ok(("hij", ("abc", "efg"))));
168 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
169 /// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
170 /// ```
separated_pair<I, O1, O2, O3, E: ParseError<I>, F, G, H>( mut first: F, mut sep: G, mut second: H, ) -> impl FnMut(I) -> IResult<I, (O1, O3), E> where F: Parser<I, O1, E>, G: Parser<I, O2, E>, H: Parser<I, O3, E>,171 pub fn separated_pair<I, O1, O2, O3, E: ParseError<I>, F, G, H>(
172   mut first: F,
173   mut sep: G,
174   mut second: H,
175 ) -> impl FnMut(I) -> IResult<I, (O1, O3), E>
176 where
177   F: Parser<I, O1, E>,
178   G: Parser<I, O2, E>,
179   H: Parser<I, O3, E>,
180 {
181   move |input: I| {
182     let (input, o1) = first.parse(input)?;
183     let (input, _) = sep.parse(input)?;
184     second.parse(input).map(|(i, o2)| (i, (o1, o2)))
185   }
186 }
187 
188 // this implementation is used for type inference issues in macros
189 #[doc(hidden)]
separated_pairc<I, O1, O2, O3, E: ParseError<I>, F, G, H>( input: I, first: F, sep: G, second: H, ) -> IResult<I, (O1, O3), E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(I) -> IResult<I, O2, E>, H: Fn(I) -> IResult<I, O3, E>,190 pub fn separated_pairc<I, O1, O2, O3, E: ParseError<I>, F, G, H>(
191   input: I,
192   first: F,
193   sep: G,
194   second: H,
195 ) -> IResult<I, (O1, O3), E>
196 where
197   F: Fn(I) -> IResult<I, O1, E>,
198   G: Fn(I) -> IResult<I, O2, E>,
199   H: Fn(I) -> IResult<I, O3, E>,
200 {
201   separated_pair(first, sep, second)(input)
202 }
203 
204 /// Matches an object from the first parser and discards it,
205 /// then gets an object from the second parser,
206 /// and finally matches an object from the third parser and discards it.
207 ///
208 /// # Arguments
209 /// * `first` The first parser to apply and discard.
210 /// * `second` The second parser to apply.
211 /// * `third` The third parser to apply and discard.
212 /// ```rust
213 /// # use nom::{Err, error::ErrorKind, Needed};
214 /// # use nom::Needed::Size;
215 /// use nom::sequence::delimited;
216 /// use nom::bytes::complete::tag;
217 ///
218 /// let mut parser = delimited(tag("("), tag("abc"), tag(")"));
219 ///
220 /// assert_eq!(parser("(abc)"), Ok(("", "abc")));
221 /// assert_eq!(parser("(abc)def"), Ok(("def", "abc")));
222 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
223 /// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
224 /// ```
delimited<I, O1, O2, O3, E: ParseError<I>, F, G, H>( mut first: F, mut second: G, mut third: H, ) -> impl FnMut(I) -> IResult<I, O2, E> where F: Parser<I, O1, E>, G: Parser<I, O2, E>, H: Parser<I, O3, E>,225 pub fn delimited<I, O1, O2, O3, E: ParseError<I>, F, G, H>(
226   mut first: F,
227   mut second: G,
228   mut third: H,
229 ) -> impl FnMut(I) -> IResult<I, O2, E>
230 where
231   F: Parser<I, O1, E>,
232   G: Parser<I, O2, E>,
233   H: Parser<I, O3, E>,
234 {
235   move |input: I| {
236     let (input, _) = first.parse(input)?;
237     let (input, o2) = second.parse(input)?;
238     third.parse(input).map(|(i, _)| (i, o2))
239   }
240 }
241 
242 // this implementation is used for type inference issues in macros
243 #[doc(hidden)]
delimitedc<I, O1, O2, O3, E: ParseError<I>, F, G, H>( input: I, first: F, second: G, third: H, ) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(I) -> IResult<I, O2, E>, H: Fn(I) -> IResult<I, O3, E>,244 pub fn delimitedc<I, O1, O2, O3, E: ParseError<I>, F, G, H>(
245   input: I,
246   first: F,
247   second: G,
248   third: H,
249 ) -> IResult<I, O2, E>
250 where
251   F: Fn(I) -> IResult<I, O1, E>,
252   G: Fn(I) -> IResult<I, O2, E>,
253   H: Fn(I) -> IResult<I, O3, E>,
254 {
255   delimited(first, second, third)(input)
256 }
257 
258 /// Helper trait for the tuple combinator.
259 ///
260 /// This trait is implemented for tuples of parsers of up to 21 elements.
261 pub trait Tuple<I, O, E> {
262   /// Parses the input and returns a tuple of results of each parser.
parse(&mut self, input: I) -> IResult<I, O, E>263   fn parse(&mut self, input: I) -> IResult<I, O, E>;
264 }
265 
266 impl<Input, Output, Error: ParseError<Input>, F: Parser<Input, Output, Error>>
267   Tuple<Input, (Output,), Error> for (F,)
268 {
parse(&mut self, input: Input) -> IResult<Input, (Output,), Error>269   fn parse(&mut self, input: Input) -> IResult<Input, (Output,), Error> {
270     self.0.parse(input).map(|(i, o)| (i, (o,)))
271   }
272 }
273 
274 macro_rules! tuple_trait(
275   ($name1:ident $ty1:ident, $name2: ident $ty2:ident, $($name:ident $ty:ident),*) => (
276     tuple_trait!(__impl $name1 $ty1, $name2 $ty2; $($name $ty),*);
277   );
278   (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident, $($name2:ident $ty2:ident),*) => (
279     tuple_trait_impl!($($name $ty),+);
280     tuple_trait!(__impl $($name $ty),+ , $name1 $ty1; $($name2 $ty2),*);
281   );
282   (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident) => (
283     tuple_trait_impl!($($name $ty),+);
284     tuple_trait_impl!($($name $ty),+, $name1 $ty1);
285   );
286 );
287 
288 macro_rules! tuple_trait_impl(
289   ($($name:ident $ty: ident),+) => (
290     impl<
291       Input: Clone, $($ty),+ , Error: ParseError<Input>,
292       $($name: Parser<Input, $ty, Error>),+
293     > Tuple<Input, ( $($ty),+ ), Error> for ( $($name),+ ) {
294 
295       fn parse(&mut self, input: Input) -> IResult<Input, ( $($ty),+ ), Error> {
296         tuple_trait_inner!(0, self, input, (), $($name)+)
297 
298       }
299     }
300   );
301 );
302 
303 macro_rules! tuple_trait_inner(
304   ($it:tt, $self:expr, $input:expr, (), $head:ident $($id:ident)+) => ({
305     let (i, o) = $self.$it.parse($input.clone())?;
306 
307     succ!($it, tuple_trait_inner!($self, i, ( o ), $($id)+))
308   });
309   ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident $($id:ident)+) => ({
310     let (i, o) = $self.$it.parse($input.clone())?;
311 
312     succ!($it, tuple_trait_inner!($self, i, ($($parsed)* , o), $($id)+))
313   });
314   ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident) => ({
315     let (i, o) = $self.$it.parse($input.clone())?;
316 
317     Ok((i, ($($parsed)* , o)))
318   });
319 );
320 
321 tuple_trait!(FnA A, FnB B, FnC C, FnD D, FnE E, FnF F, FnG G, FnH H, FnI I, FnJ J, FnK K, FnL L,
322   FnM M, FnN N, FnO O, FnP P, FnQ Q, FnR R, FnS S, FnT T, FnU U);
323 
324 ///Applies a tuple of parsers one by one and returns their results as a tuple.
325 ///
326 /// ```rust
327 /// # use nom::{Err, error::ErrorKind};
328 /// use nom::sequence::tuple;
329 /// use nom::character::complete::{alpha1, digit1};
330 /// let mut parser = tuple((alpha1, digit1, alpha1));
331 ///
332 /// assert_eq!(parser("abc123def"), Ok(("", ("abc", "123", "def"))));
333 /// assert_eq!(parser("123def"), Err(Err::Error(("123def", ErrorKind::Alpha))));
334 /// ```
tuple<I, O, E: ParseError<I>, List: Tuple<I, O, E>>( mut l: List, ) -> impl FnMut(I) -> IResult<I, O, E>335 pub fn tuple<I, O, E: ParseError<I>, List: Tuple<I, O, E>>(
336   mut l: List,
337 ) -> impl FnMut(I) -> IResult<I, O, E> {
338   move |i: I| l.parse(i)
339 }
340 
341 #[cfg(test)]
342 mod tests {
343   use super::*;
344 
345   #[test]
single_element_tuples()346   fn single_element_tuples() {
347     use crate::character::complete::alpha1;
348     use crate::{error::ErrorKind, Err};
349 
350     let mut parser = tuple((alpha1,));
351     assert_eq!(parser("abc123def"), Ok(("123def", ("abc",))));
352     assert_eq!(
353       parser("123def"),
354       Err(Err::Error(("123def", ErrorKind::Alpha)))
355     );
356   }
357 }
358