nom/sequence/
mod.rs

1//! Combinators applying parsers in sequence
2
3#[cfg(test)]
4mod tests;
5
6use crate::error::ParseError;
7use 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///
16/// ```rust
17/// # use nom::{Err, error::ErrorKind, Needed};
18/// # use nom::Needed::Size;
19/// use nom::sequence::pair;
20/// use nom::bytes::complete::tag;
21///
22/// let mut parser = pair(tag("abc"), tag("efg"));
23///
24/// assert_eq!(parser("abcefg"), Ok(("", ("abc", "efg"))));
25/// assert_eq!(parser("abcefghij"), Ok(("hij", ("abc", "efg"))));
26/// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
27/// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
28/// ```
29pub fn pair<I, O1, O2, E: ParseError<I>, F, G>(
30  mut first: F,
31  mut second: G,
32) -> impl FnMut(I) -> IResult<I, (O1, O2), E>
33where
34  F: Parser<I, O1, E>,
35  G: Parser<I, O2, E>,
36{
37  move |input: I| {
38    let (input, o1) = first.parse(input)?;
39    second.parse(input).map(|(i, o2)| (i, (o1, o2)))
40  }
41}
42
43/// Matches an object from the first parser and discards it,
44/// then gets an object from the second parser.
45///
46/// # Arguments
47/// * `first` The opening parser.
48/// * `second` The second parser to get object.
49///
50/// ```rust
51/// # use nom::{Err, error::ErrorKind, Needed};
52/// # use nom::Needed::Size;
53/// use nom::sequence::preceded;
54/// use nom::bytes::complete::tag;
55///
56/// let mut parser = preceded(tag("abc"), tag("efg"));
57///
58/// assert_eq!(parser("abcefg"), Ok(("", "efg")));
59/// assert_eq!(parser("abcefghij"), Ok(("hij", "efg")));
60/// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
61/// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
62/// ```
63pub fn preceded<I, O1, O2, E: ParseError<I>, F, G>(
64  mut first: F,
65  mut second: G,
66) -> impl FnMut(I) -> IResult<I, O2, E>
67where
68  F: Parser<I, O1, E>,
69  G: Parser<I, O2, E>,
70{
71  move |input: I| {
72    let (input, _) = first.parse(input)?;
73    second.parse(input)
74  }
75}
76
77/// Gets an object from the first parser,
78/// then matches an object from the second parser and discards it.
79///
80/// # Arguments
81/// * `first` The first parser to apply.
82/// * `second` The second parser to match an object.
83///
84/// ```rust
85/// # use nom::{Err, error::ErrorKind, Needed};
86/// # use nom::Needed::Size;
87/// use nom::sequence::terminated;
88/// use nom::bytes::complete::tag;
89///
90/// let mut parser = terminated(tag("abc"), tag("efg"));
91///
92/// assert_eq!(parser("abcefg"), Ok(("", "abc")));
93/// assert_eq!(parser("abcefghij"), Ok(("hij", "abc")));
94/// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
95/// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
96/// ```
97pub fn terminated<I, O1, O2, E: ParseError<I>, F, G>(
98  mut first: F,
99  mut second: G,
100) -> impl FnMut(I) -> IResult<I, O1, E>
101where
102  F: Parser<I, O1, E>,
103  G: Parser<I, O2, E>,
104{
105  move |input: I| {
106    let (input, o1) = first.parse(input)?;
107    second.parse(input).map(|(i, _)| (i, o1))
108  }
109}
110
111/// Gets an object from the first parser,
112/// then matches an object from the sep_parser and discards it,
113/// then gets another object from the second parser.
114///
115/// # Arguments
116/// * `first` The first parser to apply.
117/// * `sep` The separator parser to apply.
118/// * `second` The second parser to apply.
119///
120/// ```rust
121/// # use nom::{Err, error::ErrorKind, Needed};
122/// # use nom::Needed::Size;
123/// use nom::sequence::separated_pair;
124/// use nom::bytes::complete::tag;
125///
126/// let mut parser = separated_pair(tag("abc"), tag("|"), tag("efg"));
127///
128/// assert_eq!(parser("abc|efg"), Ok(("", ("abc", "efg"))));
129/// assert_eq!(parser("abc|efghij"), Ok(("hij", ("abc", "efg"))));
130/// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
131/// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
132/// ```
133pub fn separated_pair<I, O1, O2, O3, E: ParseError<I>, F, G, H>(
134  mut first: F,
135  mut sep: G,
136  mut second: H,
137) -> impl FnMut(I) -> IResult<I, (O1, O3), E>
138where
139  F: Parser<I, O1, E>,
140  G: Parser<I, O2, E>,
141  H: Parser<I, O3, E>,
142{
143  move |input: I| {
144    let (input, o1) = first.parse(input)?;
145    let (input, _) = sep.parse(input)?;
146    second.parse(input).map(|(i, o2)| (i, (o1, o2)))
147  }
148}
149
150/// Matches an object from the first parser and discards it,
151/// then gets an object from the second parser,
152/// and finally matches an object from the third parser and discards it.
153///
154/// # Arguments
155/// * `first` The first parser to apply and discard.
156/// * `second` The second parser to apply.
157/// * `third` The third parser to apply and discard.
158///
159/// ```rust
160/// # use nom::{Err, error::ErrorKind, Needed};
161/// # use nom::Needed::Size;
162/// use nom::sequence::delimited;
163/// use nom::bytes::complete::tag;
164///
165/// let mut parser = delimited(tag("("), tag("abc"), tag(")"));
166///
167/// assert_eq!(parser("(abc)"), Ok(("", "abc")));
168/// assert_eq!(parser("(abc)def"), Ok(("def", "abc")));
169/// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
170/// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
171/// ```
172pub fn delimited<I, O1, O2, O3, E: ParseError<I>, F, G, H>(
173  mut first: F,
174  mut second: G,
175  mut third: H,
176) -> impl FnMut(I) -> IResult<I, O2, E>
177where
178  F: Parser<I, O1, E>,
179  G: Parser<I, O2, E>,
180  H: Parser<I, O3, E>,
181{
182  move |input: I| {
183    let (input, _) = first.parse(input)?;
184    let (input, o2) = second.parse(input)?;
185    third.parse(input).map(|(i, _)| (i, o2))
186  }
187}
188
189/// Helper trait for the tuple combinator.
190///
191/// This trait is implemented for tuples of parsers of up to 21 elements.
192pub trait Tuple<I, O, E> {
193  /// Parses the input and returns a tuple of results of each parser.
194  fn parse(&mut self, input: I) -> IResult<I, O, E>;
195}
196
197impl<Input, Output, Error: ParseError<Input>, F: Parser<Input, Output, Error>>
198  Tuple<Input, (Output,), Error> for (F,)
199{
200  fn parse(&mut self, input: Input) -> IResult<Input, (Output,), Error> {
201    self.0.parse(input).map(|(i, o)| (i, (o,)))
202  }
203}
204
205macro_rules! tuple_trait(
206  ($name1:ident $ty1:ident, $name2: ident $ty2:ident, $($name:ident $ty:ident),*) => (
207    tuple_trait!(__impl $name1 $ty1, $name2 $ty2; $($name $ty),*);
208  );
209  (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident, $($name2:ident $ty2:ident),*) => (
210    tuple_trait_impl!($($name $ty),+);
211    tuple_trait!(__impl $($name $ty),+ , $name1 $ty1; $($name2 $ty2),*);
212  );
213  (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident) => (
214    tuple_trait_impl!($($name $ty),+);
215    tuple_trait_impl!($($name $ty),+, $name1 $ty1);
216  );
217);
218
219macro_rules! tuple_trait_impl(
220  ($($name:ident $ty: ident),+) => (
221    impl<
222      Input: Clone, $($ty),+ , Error: ParseError<Input>,
223      $($name: Parser<Input, $ty, Error>),+
224    > Tuple<Input, ( $($ty),+ ), Error> for ( $($name),+ ) {
225
226      fn parse(&mut self, input: Input) -> IResult<Input, ( $($ty),+ ), Error> {
227        tuple_trait_inner!(0, self, input, (), $($name)+)
228
229      }
230    }
231  );
232);
233
234macro_rules! tuple_trait_inner(
235  ($it:tt, $self:expr, $input:expr, (), $head:ident $($id:ident)+) => ({
236    let (i, o) = $self.$it.parse($input.clone())?;
237
238    succ!($it, tuple_trait_inner!($self, i, ( o ), $($id)+))
239  });
240  ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident $($id:ident)+) => ({
241    let (i, o) = $self.$it.parse($input.clone())?;
242
243    succ!($it, tuple_trait_inner!($self, i, ($($parsed)* , o), $($id)+))
244  });
245  ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident) => ({
246    let (i, o) = $self.$it.parse($input.clone())?;
247
248    Ok((i, ($($parsed)* , o)))
249  });
250);
251
252tuple_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,
253  FnM M, FnN N, FnO O, FnP P, FnQ Q, FnR R, FnS S, FnT T, FnU U);
254
255// Special case: implement `Tuple` for `()`, the unit type.
256// This can come up in macros which accept a variable number of arguments.
257// Literally, `()` is an empty tuple, so it should simply parse nothing.
258impl<I, E: ParseError<I>> Tuple<I, (), E> for () {
259  fn parse(&mut self, input: I) -> IResult<I, (), E> {
260    Ok((input, ()))
261  }
262}
263
264///Applies a tuple of parsers one by one and returns their results as a tuple.
265///There is a maximum of 21 parsers
266/// ```rust
267/// # use nom::{Err, error::ErrorKind};
268/// use nom::sequence::tuple;
269/// use nom::character::complete::{alpha1, digit1};
270/// let mut parser = tuple((alpha1, digit1, alpha1));
271///
272/// assert_eq!(parser("abc123def"), Ok(("", ("abc", "123", "def"))));
273/// assert_eq!(parser("123def"), Err(Err::Error(("123def", ErrorKind::Alpha))));
274/// ```
275pub fn tuple<I, O, E: ParseError<I>, List: Tuple<I, O, E>>(
276  mut l: List,
277) -> impl FnMut(I) -> IResult<I, O, E> {
278  move |i: I| l.parse(i)
279}