1 //! combinators applying their child parser multiple times
2
3 #[macro_use]
4 mod macros;
5
6 use crate::internal::{Err, IResult, Needed};
7 use crate::error::ParseError;
8 use crate::traits::{InputLength, InputTake, ToUsize};
9 #[cfg(feature = "alloc")]
10 use crate::lib::std::vec::Vec;
11 use crate::error::ErrorKind;
12
13 /// Repeats the embedded parser until it fails
14 /// and returns the results in a `Vec`.
15 ///
16 /// # Arguments
17 /// * `f` The parser to apply.
18 ///
19 /// *Note*: if the parser passed to `many0` accepts empty inputs
20 /// (like `alpha0` or `digit0`), `many0` will return an error,
21 /// to prevent going into an infinite loop
22 ///
23 /// ```rust
24 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
25 /// use nom::multi::many0;
26 /// use nom::bytes::complete::tag;
27 ///
28 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
29 /// many0(tag("abc"))(s)
30 /// }
31 ///
32 /// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
33 /// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
34 /// assert_eq!(parser("123123"), Ok(("123123", vec![])));
35 /// assert_eq!(parser(""), Ok(("", vec![])));
36 /// ```
37 #[cfg(feature = "alloc")]
many0<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,38 pub fn many0<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E>
39 where
40 I: Clone + PartialEq,
41 F: Fn(I) -> IResult<I, O, E>,
42 E: ParseError<I>,
43 {
44 move |i: I| {
45 let mut acc = crate::lib::std::vec::Vec::with_capacity(4);
46 let mut i = i.clone();
47 loop {
48 match f(i.clone()) {
49 Err(Err::Error(_)) => return Ok((i, acc)),
50 Err(e) => return Err(e),
51 Ok((i1, o)) => {
52 if i1 == i {
53 return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many0)));
54 }
55
56 i = i1;
57 acc.push(o);
58 }
59 }
60 }
61 }
62 }
63 // this implementation is used for type inference issues in macros
64 #[doc(hidden)]
65 #[cfg(feature = "alloc")]
many0c<I, O, E, F>(input: I, f: F) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,66 pub fn many0c<I, O, E, F>(input: I, f: F) -> IResult<I, Vec<O>, E>
67 where
68 I: Clone + PartialEq,
69 F: Fn(I) -> IResult<I, O, E>,
70 E: ParseError<I>,
71 {
72 many0(f)(input)
73 }
74
75 /// Runs the embedded parser until it fails and
76 /// returns the results in a `Vec`. Fails if
77 /// the embedded parser does not produce at least
78 /// one result.
79 ///
80 /// # Arguments
81 /// * `f` The parser to apply.
82 ///
83 /// *Note*: if the parser passed to `many1` accepts empty inputs
84 /// (like `alpha0` or `digit0`), `many1` will return an error,
85 /// to prevent going into an infinite loop
86 ///
87 /// ```rust
88 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
89 /// use nom::multi::many1;
90 /// use nom::bytes::complete::tag;
91 ///
92 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
93 /// many1(tag("abc"))(s)
94 /// }
95 ///
96 /// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
97 /// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
98 /// assert_eq!(parser("123123"), Err(Err::Error(("123123", ErrorKind::Tag))));
99 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
100 /// ```
101 #[cfg(feature = "alloc")]
many1<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,102 pub fn many1<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E>
103 where
104 I: Clone + PartialEq,
105 F: Fn(I) -> IResult<I, O, E>,
106 E: ParseError<I>,
107 {
108 move |i: I| {
109 let mut i = i.clone();
110 match f(i.clone()) {
111 Err(Err::Error(err)) => return Err(Err::Error(E::append(i, ErrorKind::Many1, err))),
112 Err(e) => return Err(e),
113 Ok((i1, o)) => {
114 let mut acc = crate::lib::std::vec::Vec::with_capacity(4);
115 acc.push(o);
116 i = i1;
117
118 loop {
119 match f(i.clone()) {
120 Err(Err::Error(_)) => return Ok((i, acc)),
121 Err(e) => return Err(e),
122 Ok((i1, o)) => {
123 if i1 == i {
124 return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1)));
125 }
126
127 i = i1;
128 acc.push(o);
129 }
130 }
131 }
132 }
133 }
134 }
135 }
136
137 // this implementation is used for type inference issues in macros
138 #[doc(hidden)]
139 #[cfg(feature = "alloc")]
many1c<I, O, E, F>(input: I, f: F) -> IResult<I, Vec<O>, E> where I: Clone + Copy + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,140 pub fn many1c<I, O, E, F>(input: I, f: F) -> IResult<I, Vec<O>, E>
141 where
142 I: Clone + Copy + PartialEq,
143 F: Fn(I) -> IResult<I, O, E>,
144 E: ParseError<I>,
145 {
146 many1(f)(input)
147 }
148
149 /// Applies the parser `f` until the parser `g` produces
150 /// a result. Returns a pair consisting of the results of
151 /// `f` in a `Vec` and the result of `g`.
152 /// ```rust
153 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
154 /// use nom::multi::many_till;
155 /// use nom::bytes::complete::tag;
156 ///
157 /// fn parser(s: &str) -> IResult<&str, (Vec<&str>, &str)> {
158 /// many_till(tag("abc"), tag("end"))(s)
159 /// };
160 ///
161 /// assert_eq!(parser("abcabcend"), Ok(("", (vec!["abc", "abc"], "end"))));
162 /// assert_eq!(parser("abc123end"), Err(Err::Error(("123end", ErrorKind::Tag))));
163 /// assert_eq!(parser("123123end"), Err(Err::Error(("123123end", ErrorKind::Tag))));
164 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
165 /// assert_eq!(parser("abcendefg"), Ok(("efg", (vec!["abc"], "end"))));
166 /// ```
167 #[cfg(feature = "alloc")]
many_till<I, O, P, E, F, G>(f: F, g: G) -> impl Fn(I) -> IResult<I, (Vec<O>, P), E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(I) -> IResult<I, P, E>, E: ParseError<I>,168 pub fn many_till<I, O, P, E, F, G>(f: F, g: G) -> impl Fn(I) -> IResult<I, (Vec<O>, P), E>
169 where
170 I: Clone + PartialEq,
171 F: Fn(I) -> IResult<I, O, E>,
172 G: Fn(I) -> IResult<I, P, E>,
173 E: ParseError<I>,
174 {
175 move |i: I| {
176 let mut res = crate::lib::std::vec::Vec::new();
177 let mut i = i.clone();
178 loop {
179 match g(i.clone()) {
180 Ok((i1, o)) => return Ok((i1, (res, o))),
181 Err(Err::Error(_)) => {
182 match f(i.clone()) {
183 Err(Err::Error(err)) =>
184 return Err(Err::Error(E::append(i, ErrorKind::ManyTill, err))),
185 Err(e) => return Err(e),
186 Ok((i1, o)) => {
187 // loop trip must always consume (otherwise infinite loops)
188 if i1 == i {
189 return Err(Err::Error(E::from_error_kind(i1, ErrorKind::ManyTill)));
190 }
191
192 res.push(o);
193 i = i1;
194 }
195 }
196 },
197 Err(e) => return Err(e),
198 }
199 }
200 }
201 }
202
203 // this implementation is used for type inference issues in macros
204 #[doc(hidden)]
205 #[cfg(feature = "alloc")]
many_tillc<I, O, P, E, F, G>(i: I, f: F, g: G) -> IResult<I, (Vec<O>, P), E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(I) -> IResult<I, P, E>, E: ParseError<I>,206 pub fn many_tillc<I, O, P, E, F, G>(i: I, f: F, g: G) -> IResult<I, (Vec<O>, P), E>
207 where
208 I: Clone + PartialEq,
209 F: Fn(I) -> IResult<I, O, E>,
210 G: Fn(I) -> IResult<I, P, E>,
211 E: ParseError<I>,
212 {
213 many_till(f, g)(i)
214 }
215
216 /// Alternates between two parsers to produce
217 /// a list of elements.
218 /// # Arguments
219 /// * `sep` Parses the separator between list elements.
220 /// * `f` Parses the elements of the list.
221 ///
222 /// ```rust
223 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
224 /// use nom::multi::separated_list;
225 /// use nom::bytes::complete::tag;
226 ///
227 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
228 /// separated_list(tag("|"), tag("abc"))(s)
229 /// }
230 ///
231 /// assert_eq!(parser("abc|abc|abc"), Ok(("", vec!["abc", "abc", "abc"])));
232 /// assert_eq!(parser("abc123abc"), Ok(("123abc", vec!["abc"])));
233 /// assert_eq!(parser("abc|def"), Ok(("|def", vec!["abc"])));
234 /// assert_eq!(parser(""), Ok(("", vec![])));
235 /// assert_eq!(parser("def|abc"), Ok(("def|abc", vec![])));
236 /// ```
237 #[cfg(feature = "alloc")]
separated_list<I, O, O2, E, F, G>(sep: G, f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(I) -> IResult<I, O2, E>, E: ParseError<I>,238 pub fn separated_list<I, O, O2, E, F, G>(sep: G, f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E>
239 where
240 I: Clone + PartialEq,
241 F: Fn(I) -> IResult<I, O, E>,
242 G: Fn(I) -> IResult<I, O2, E>,
243 E: ParseError<I>,
244 {
245 move |i: I| {
246 let mut res = Vec::new();
247 let mut i = i.clone();
248
249 match f(i.clone()) {
250 Err(Err::Error(_)) => return Ok((i, res)),
251 Err(e) => return Err(e),
252 Ok((i1, o)) => {
253 if i1 == i {
254 return Err(Err::Error(E::from_error_kind(i1, ErrorKind::SeparatedList)));
255 }
256
257 res.push(o);
258 i = i1;
259 }
260 }
261
262 loop {
263 match sep(i.clone()) {
264 Err(Err::Error(_)) => return Ok((i, res)),
265 Err(e) => return Err(e),
266 Ok((i1, _)) => {
267 if i1 == i {
268 return Err(Err::Error(E::from_error_kind(i1, ErrorKind::SeparatedList)));
269 }
270
271 match f(i1.clone()) {
272 Err(Err::Error(_)) => return Ok((i, res)),
273 Err(e) => return Err(e),
274 Ok((i2, o)) => {
275 if i2 == i {
276 return Err(Err::Error(E::from_error_kind(i2, ErrorKind::SeparatedList)));
277 }
278
279 res.push(o);
280 i = i2;
281 }
282 }
283 }
284 }
285 }
286 }
287 }
288
289 // this implementation is used for type inference issues in macros
290 #[doc(hidden)]
291 #[cfg(feature = "alloc")]
separated_listc<I, O, O2, E, F, G>(i: I, sep: G, f: F) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(I) -> IResult<I, O2, E>, E: ParseError<I>,292 pub fn separated_listc<I, O, O2, E, F, G>(i: I, sep: G, f: F) -> IResult<I, Vec<O>, E>
293 where
294 I: Clone + PartialEq,
295 F: Fn(I) -> IResult<I, O, E>,
296 G: Fn(I) -> IResult<I, O2, E>,
297 E: ParseError<I>,
298 {
299 separated_list(sep, f)(i)
300 }
301
302 /// Alternates between two parsers to produce
303 /// a list of elements. Fails if the element
304 /// parser does not produce at least one element.
305 /// # Arguments
306 /// * `sep` Parses the separator between list elements.
307 /// * `f` Parses the elements of the list.
308 /// ```rust
309 /// # #[macro_use] extern crate nom;
310 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
311 /// use nom::multi::separated_nonempty_list;
312 /// use nom::bytes::complete::tag;
313 ///
314 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
315 /// separated_nonempty_list(tag("|"), tag("abc"))(s)
316 /// }
317 ///
318 /// assert_eq!(parser("abc|abc|abc"), Ok(("", vec!["abc", "abc", "abc"])));
319 /// assert_eq!(parser("abc123abc"), Ok(("123abc", vec!["abc"])));
320 /// assert_eq!(parser("abc|def"), Ok(("|def", vec!["abc"])));
321 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
322 /// assert_eq!(parser("def|abc"), Err(Err::Error(("def|abc", ErrorKind::Tag))));
323 /// ```
324 #[cfg(feature = "alloc")]
separated_nonempty_list<I, O, O2, E, F, G>(sep: G, f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(I) -> IResult<I, O2, E>, E: ParseError<I>,325 pub fn separated_nonempty_list<I, O, O2, E, F, G>(sep: G, f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E>
326 where
327 I: Clone + PartialEq,
328 F: Fn(I) -> IResult<I, O, E>,
329 G: Fn(I) -> IResult<I, O2, E>,
330 E: ParseError<I>,
331 {
332 move |i: I| {
333 let mut res = Vec::new();
334 let mut i = i.clone();
335
336 // Parse the first element
337 match f(i.clone()) {
338 Err(e)=> return Err(e),
339 Ok((i1, o)) => {
340 if i1 == i {
341 return Err(Err::Error(E::from_error_kind(i1, ErrorKind::SeparatedList)));
342 }
343
344 res.push(o);
345 i = i1;
346 }
347 }
348
349 loop {
350 match sep(i.clone()) {
351 Err(Err::Error(_)) => return Ok((i, res)),
352 Err(e) => return Err(e),
353 Ok((i1, _)) => {
354 if i1 == i {
355 return Err(Err::Error(E::from_error_kind(i1, ErrorKind::SeparatedList)));
356 }
357
358 match f(i1.clone()) {
359 Err(Err::Error(_)) => return Ok((i, res)),
360 Err(e) => return Err(e),
361 Ok((i2, o)) => {
362 if i2 == i {
363 return Err(Err::Error(E::from_error_kind(i2, ErrorKind::SeparatedList)));
364 }
365
366 res.push(o);
367 i = i2;
368 }
369 }
370 }
371 }
372 }
373 }
374 }
375
376 // this implementation is used for type inference issues in macros
377 #[doc(hidden)]
378 #[cfg(feature = "alloc")]
separated_nonempty_listc<I, O, O2, E, F, G>(i: I, sep: G, f: F) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(I) -> IResult<I, O2, E>, E: ParseError<I>,379 pub fn separated_nonempty_listc<I, O, O2, E, F, G>(i: I, sep: G, f: F) -> IResult<I, Vec<O>, E>
380 where
381 I: Clone + PartialEq,
382 F: Fn(I) -> IResult<I, O, E>,
383 G: Fn(I) -> IResult<I, O2, E>,
384 E: ParseError<I>,
385 {
386 separated_nonempty_list(sep, f)(i)
387 }
388
389 /// Repeats the embedded parser `n` times or until it fails
390 /// and returns the results in a `Vec`. Fails if the
391 /// embedded parser does not succeed at least `m` times.
392 /// # Arguments
393 /// * `m` The minimum number of iterations.
394 /// * `n` The maximum number of iterations.
395 /// * `f` The parser to apply.
396 /// ```rust
397 /// # #[macro_use] extern crate nom;
398 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
399 /// use nom::multi::many_m_n;
400 /// use nom::bytes::complete::tag;
401 ///
402 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
403 /// many_m_n(0, 2, tag("abc"))(s)
404 /// }
405 ///
406 /// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
407 /// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
408 /// assert_eq!(parser("123123"), Ok(("123123", vec![])));
409 /// assert_eq!(parser(""), Ok(("", vec![])));
410 /// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
411 /// ```
412 #[cfg(feature = "alloc")]
many_m_n<I, O, E, F>(m: usize, n: usize, f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,413 pub fn many_m_n<I, O, E, F>(m: usize, n: usize, f: F) -> impl Fn(I) -> IResult<I, Vec<O>, E>
414 where
415 I: Clone + PartialEq,
416 F: Fn(I) -> IResult<I, O, E>,
417 E: ParseError<I>,
418 {
419 move |i: I| {
420 let mut res = crate::lib::std::vec::Vec::with_capacity(m);
421 let mut input = i.clone();
422 let mut count: usize = 0;
423
424 if n == 0 {
425 return Ok((i, vec!()))
426 }
427
428 loop {
429 let _i = input.clone();
430 match f(_i) {
431 Ok((i, o)) => {
432 // do not allow parsers that do not consume input (causes infinite loops)
433 if i == input {
434 return Err(Err::Error(E::from_error_kind(input, ErrorKind::ManyMN)));
435 }
436
437 res.push(o);
438 input = i;
439 count += 1;
440
441 if count == n {
442 return Ok((input, res));
443 }
444 }
445 Err(Err::Error(e)) => {
446 if count < m {
447 return Err(Err::Error(E::append(input, ErrorKind::ManyMN, e)));
448 } else {
449 return Ok((input, res));
450 }
451 }
452 Err(e) => {
453 return Err(e);
454 }
455 }
456 }
457 }
458 }
459
460 // this implementation is used for type inference issues in macros
461 #[doc(hidden)]
462 #[cfg(feature = "alloc")]
many_m_nc<I, O, E, F>(i: I, m: usize, n: usize, f: F) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,463 pub fn many_m_nc<I, O, E, F>(i: I, m: usize, n: usize, f: F) -> IResult<I, Vec<O>, E>
464 where
465 I: Clone + PartialEq,
466 F: Fn(I) -> IResult<I, O, E>,
467 E: ParseError<I>,
468 {
469 many_m_n(m, n, f)(i)
470 }
471
472 /// Repeats the embedded parser until it fails
473 /// and returns the number of successful iterations.
474 /// # Arguments
475 /// * `f` The parser to apply.
476 /// ```rust
477 /// # #[macro_use] extern crate nom;
478 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
479 /// use nom::multi::many0_count;
480 /// use nom::bytes::complete::tag;
481 ///
482 /// fn parser(s: &str) -> IResult<&str, usize> {
483 /// many0_count(tag("abc"))(s)
484 /// }
485 ///
486 /// assert_eq!(parser("abcabc"), Ok(("", 2)));
487 /// assert_eq!(parser("abc123"), Ok(("123", 1)));
488 /// assert_eq!(parser("123123"), Ok(("123123", 0)));
489 /// assert_eq!(parser(""), Ok(("", 0)));
490 /// ```
many0_count<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, usize, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,491 pub fn many0_count<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, usize, E>
492 where
493 I: Clone + PartialEq,
494 F: Fn(I) -> IResult<I, O, E>,
495 E: ParseError<I>,
496 {
497 move |i: I| {
498 let mut input = i.clone();
499 let mut count = 0;
500
501 loop {
502 let input_ = input.clone();
503 match f(input_) {
504 Ok((i, _)) => {
505 // loop trip must always consume (otherwise infinite loops)
506 if i == input {
507 return Err(Err::Error(E::from_error_kind(input, ErrorKind::Many0Count)));
508 }
509
510 input = i;
511 count += 1;
512 }
513
514 Err(Err::Error(_)) => return Ok((input, count)),
515
516 Err(e) => return Err(e),
517 }
518 }
519 }
520 }
521
522 #[doc(hidden)]
many0_countc<I, O, E, F>(i: I, f: F) -> IResult<I, usize, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,523 pub fn many0_countc<I, O, E, F>(i: I, f: F) -> IResult<I, usize, E>
524 where
525 I: Clone + PartialEq,
526 F: Fn(I) -> IResult<I, O, E>,
527 E: ParseError<I>,
528 {
529 many0_count(f)(i)
530 }
531
532 /// Repeats the embedded parser until it fails
533 /// and returns the number of successful iterations.
534 /// Fails if the embedded parser does not succeed
535 /// at least once.
536 /// # Arguments
537 /// * `f` The parser to apply.
538 /// ```rust
539 /// # #[macro_use] extern crate nom;
540 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
541 /// use nom::multi::many1_count;
542 /// use nom::bytes::complete::tag;
543 ///
544 /// fn parser(s: &str) -> IResult<&str, usize> {
545 /// many1_count(tag("abc"))(s)
546 /// }
547 ///
548 /// assert_eq!(parser("abcabc"), Ok(("", 2)));
549 /// assert_eq!(parser("abc123"), Ok(("123", 1)));
550 /// assert_eq!(parser("123123"), Err(Err::Error(("123123", ErrorKind::Many1Count))));
551 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Many1Count))));
552 /// ```
many1_count<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, usize, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,553 pub fn many1_count<I, O, E, F>(f: F) -> impl Fn(I) -> IResult<I, usize, E>
554 where
555 I: Clone + PartialEq,
556 F: Fn(I) -> IResult<I, O, E>,
557 E: ParseError<I>,
558 {
559 move |i: I| {
560 let i_ = i.clone();
561 match f(i_) {
562 Err(Err::Error(_)) => Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1Count))),
563 Err(i) => Err(i),
564 Ok((i1, _)) => {
565 let mut count = 1;
566 let mut input = i1;
567
568 loop {
569 let input_ = input.clone();
570 match f(input_) {
571 Err(Err::Error(_)) => return Ok((input, count)),
572 Err(e) => return Err(e),
573 Ok((i, _)) => {
574 if i == input {
575 return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1Count)));
576 }
577
578 count += 1;
579 input = i;
580 }
581 }
582 }
583 }
584 }
585 }
586 }
587
588 #[doc(hidden)]
many1_countc<I, O, E, F>(i: I, f: F) -> IResult<I, usize, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,589 pub fn many1_countc<I, O, E, F>(i: I, f: F) -> IResult<I, usize, E>
590 where
591 I: Clone + PartialEq,
592 F: Fn(I) -> IResult<I, O, E>,
593 E: ParseError<I>,
594 {
595 many1_count(f)(i)
596 }
597
598 /// Runs the embedded parser a specified number
599 /// of times. Returns the results in a `Vec`.
600 /// # Arguments
601 /// * `f` The parser to apply.
602 /// * `count` How often to apply the parser.
603 /// ```rust
604 /// # #[macro_use] extern crate nom;
605 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
606 /// use nom::multi::count;
607 /// use nom::bytes::complete::tag;
608 ///
609 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
610 /// count(tag("abc"), 2)(s)
611 /// }
612 ///
613 /// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
614 /// assert_eq!(parser("abc123"), Err(Err::Error(("123", ErrorKind::Tag))));
615 /// assert_eq!(parser("123123"), Err(Err::Error(("123123", ErrorKind::Tag))));
616 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
617 /// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
618 /// ```
619 #[cfg(feature = "alloc")]
count<I, O, E, F>(f: F, count: usize) -> impl Fn(I) -> IResult<I, Vec<O>, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,620 pub fn count<I, O, E, F>(f: F, count: usize) -> impl Fn(I) -> IResult<I, Vec<O>, E>
621 where
622 I: Clone + PartialEq,
623 F: Fn(I) -> IResult<I, O, E>,
624 E: ParseError<I>,
625 {
626 move |i: I | {
627 let mut input = i.clone();
628 let mut res = crate::lib::std::vec::Vec::new();
629
630 for _ in 0..count {
631 let input_ = input.clone();
632 match f(input_) {
633 Ok((i, o)) => {
634 res.push(o);
635 input = i;
636 }
637 Err(Err::Error(e)) => {
638 return Err(Err::Error(E::append(i, ErrorKind::Count, e)));
639 }
640 Err(e) => {
641 return Err(e);
642 }
643 }
644 }
645
646 Ok((input, res))
647 }
648 }
649
650 /// Applies a parser until it fails and accumulates
651 /// the results using a given function and initial value.
652 /// # Arguments
653 /// * `f` The parser to apply.
654 /// * `init` The initial value.
655 /// * `g` The function that combines a result of `f` with
656 /// the current accumulator.
657 /// ```rust
658 /// # #[macro_use] extern crate nom;
659 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
660 /// use nom::multi::fold_many0;
661 /// use nom::bytes::complete::tag;
662 ///
663 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
664 /// fold_many0(
665 /// tag("abc"),
666 /// Vec::new(),
667 /// |mut acc: Vec<_>, item| {
668 /// acc.push(item);
669 /// acc
670 /// }
671 /// )(s)
672 /// }
673 ///
674 /// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
675 /// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
676 /// assert_eq!(parser("123123"), Ok(("123123", vec![])));
677 /// assert_eq!(parser(""), Ok(("", vec![])));
678 /// ```
fold_many0<I, O, E, F, G, R>(f: F, init: R, g: G) -> impl Fn(I) -> IResult<I, R, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(R, O) -> R, E: ParseError<I>, R: Clone,679 pub fn fold_many0<I, O, E, F, G, R>(f: F, init: R, g: G) -> impl Fn(I) -> IResult<I, R, E>
680 where
681 I: Clone + PartialEq,
682 F: Fn(I) -> IResult<I, O, E>,
683 G: Fn(R, O) -> R,
684 E: ParseError<I>,
685 R: Clone,
686 {
687 move |i: I| {
688 let mut res = init.clone();
689 let mut input = i.clone();
690
691 loop {
692 let i_ = input.clone();
693 match f(i_) {
694 Ok((i, o)) => {
695 // loop trip must always consume (otherwise infinite loops)
696 if i == input {
697 return Err(Err::Error(E::from_error_kind(input, ErrorKind::Many0)));
698 }
699
700 res = g(res, o);
701 input = i;
702 }
703 Err(Err::Error(_)) => {
704 return Ok((input, res));
705 }
706 Err(e) => {
707 return Err(e);
708 }
709 }
710 }
711 }
712 }
713
714 #[doc(hidden)]
fold_many0c<I, O, E, F, G, R>(i: I, f: F, init: R, g: G) -> IResult<I, R, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(R, O) -> R, E: ParseError<I>, R: Clone,715 pub fn fold_many0c<I, O, E, F, G, R>(i: I, f: F, init: R, g: G) -> IResult<I, R, E>
716 where
717 I: Clone + PartialEq,
718 F: Fn(I) -> IResult<I, O, E>,
719 G: Fn(R, O) -> R,
720 E: ParseError<I>,
721 R: Clone,
722 {
723 fold_many0(f, init, g)(i)
724 }
725
726 /// Applies a parser until it fails and accumulates
727 /// the results using a given function and initial value.
728 /// Fails if the embedded parser does not succeed at least
729 /// once.
730 /// # Arguments
731 /// * `f` The parser to apply.
732 /// * `init` The initial value.
733 /// * `g` The function that combines a result of `f` with
734 /// the current accumulator.
735 /// ```rust
736 /// # #[macro_use] extern crate nom;
737 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
738 /// use nom::multi::fold_many1;
739 /// use nom::bytes::complete::tag;
740 ///
741 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
742 /// fold_many1(
743 /// tag("abc"),
744 /// Vec::new(),
745 /// |mut acc: Vec<_>, item| {
746 /// acc.push(item);
747 /// acc
748 /// }
749 /// )(s)
750 /// }
751 ///
752 /// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
753 /// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
754 /// assert_eq!(parser("123123"), Err(Err::Error(("123123", ErrorKind::Many1))));
755 /// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Many1))));
756 /// ```
fold_many1<I, O, E, F, G, R>(f: F, init: R, g: G) -> impl Fn(I) -> IResult<I, R, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(R, O) -> R, E: ParseError<I>, R: Clone,757 pub fn fold_many1<I, O, E, F, G, R>(f: F, init: R, g: G) -> impl Fn(I) -> IResult<I, R, E>
758 where
759 I: Clone + PartialEq,
760 F: Fn(I) -> IResult<I, O, E>,
761 G: Fn(R, O) -> R,
762 E: ParseError<I>,
763 R: Clone,
764 {
765 move |i: I| {
766 let _i = i.clone();
767 let init = init.clone();
768 match f(_i) {
769 Err(Err::Error(_)) => Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1))),
770 Err(e) => return Err(e),
771 Ok((i1, o1)) => {
772 let mut acc = g(init, o1);
773 let mut input = i1;
774
775 loop {
776 let _input = input.clone();
777 match f(_input) {
778 Err(Err::Error(_)) => {
779 break;
780 }
781 Err(e) => return Err(e),
782 Ok((i, o)) => {
783 if i == input {
784 return Err(Err::Failure(E::from_error_kind(i, ErrorKind::Many1)));
785 }
786
787 acc = g(acc, o);
788 input = i;
789 }
790 }
791 }
792
793 Ok((input, acc))
794 }
795 }
796 }
797 }
798
799 #[doc(hidden)]
fold_many1c<I, O, E, F, G, R>(i: I, f: F, init: R, g: G) -> IResult<I, R, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(R, O) -> R, E: ParseError<I>, R: Clone,800 pub fn fold_many1c<I, O, E, F, G, R>(i: I, f: F, init: R, g: G) -> IResult<I, R, E>
801 where
802 I: Clone + PartialEq,
803 F: Fn(I) -> IResult<I, O, E>,
804 G: Fn(R, O) -> R,
805 E: ParseError<I>,
806 R: Clone,
807 {
808 fold_many1(f, init, g)(i)
809 }
810
811 /// Applies a parser `n` times or until it fails and accumulates
812 /// the results using a given function and initial value.
813 /// Fails if the embedded parser does not succeed at least `m`
814 /// times.
815 /// # Arguments
816 /// * `m` The minimum number of iterations.
817 /// * `n` The maximum number of iterations.
818 /// * `f` The parser to apply.
819 /// * `init` The initial value.
820 /// * `g` The function that combines a result of `f` with
821 /// the current accumulator.
822 /// ```rust
823 /// # #[macro_use] extern crate nom;
824 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
825 /// use nom::multi::fold_many_m_n;
826 /// use nom::bytes::complete::tag;
827 ///
828 /// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
829 /// fold_many_m_n(
830 /// 0,
831 /// 2,
832 /// tag("abc"),
833 /// Vec::new(),
834 /// |mut acc: Vec<_>, item| {
835 /// acc.push(item);
836 /// acc
837 /// }
838 /// )(s)
839 /// }
840 ///
841 /// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
842 /// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
843 /// assert_eq!(parser("123123"), Ok(("123123", vec![])));
844 /// assert_eq!(parser(""), Ok(("", vec![])));
845 /// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
846 /// ```
fold_many_m_n<I, O, E, F, G, R>(m: usize, n: usize, f: F, init: R, g: G) -> impl Fn(I) ->IResult<I, R, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(R, O) -> R, E: ParseError<I>, R: Clone,847 pub fn fold_many_m_n<I, O, E, F, G, R>(m: usize, n: usize, f: F, init: R, g: G) -> impl Fn(I) ->IResult<I, R, E>
848 where
849 I: Clone + PartialEq,
850 F: Fn(I) -> IResult<I, O, E>,
851 G: Fn(R, O) -> R,
852 E: ParseError<I>,
853 R: Clone,
854 {
855 move |i: I| {
856 let mut acc = init.clone();
857 let mut input = i.clone();
858 for count in 0..n {
859 let _input = input.clone();
860 match f(_input) {
861 Ok((i, o)) => {
862 // do not allow parsers that do not consume input (causes infinite loops)
863 if i == input {
864 return Err(Err::Error(E::from_error_kind(i, ErrorKind::ManyMN)));
865 }
866
867 acc = g(acc, o);
868 input = i;
869 }
870 //FInputXMError: handle failure properly
871 Err(Err::Error(_)) => if count < m {
872 return Err(Err::Error(E::from_error_kind(i, ErrorKind::ManyMN)));
873 } else {
874 break;
875 }
876 Err(e) => return Err(e),
877 }
878 }
879
880 Ok((input, acc))
881 }
882 }
883
884 #[doc(hidden)]
fold_many_m_nc<I, O, E, F, G, R>(i: I, m: usize, n: usize, f: F, init: R, g: G) -> IResult<I, R, E> where I: Clone + PartialEq, F: Fn(I) -> IResult<I, O, E>, G: Fn(R, O) -> R, E: ParseError<I>, R: Clone,885 pub fn fold_many_m_nc<I, O, E, F, G, R>(i: I, m: usize, n: usize, f: F, init: R, g: G) -> IResult<I, R, E>
886 where
887 I: Clone + PartialEq,
888 F: Fn(I) -> IResult<I, O, E>,
889 G: Fn(R, O) -> R,
890 E: ParseError<I>,
891 R: Clone,
892 {
893 fold_many_m_n(m, n, f, init, g)(i)
894 }
895
896 /// Gets a number from the parser and returns a
897 /// subslice of the input of that size.
898 /// If the parser returns Incomplete,
899 /// length_data will return an error.
900 /// # Arguments
901 /// * `f` The parser to apply.
902 /// ```rust
903 /// # #[macro_use] extern crate nom;
904 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
905 /// # use nom::Needed::Size;
906 /// use nom::number::complete::be_u16;
907 /// use nom::multi::length_data;
908 /// use nom::bytes::complete::tag;
909 ///
910 /// fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {
911 /// length_data(be_u16)(s)
912 /// }
913 ///
914 /// assert_eq!(parser(b"\x00\x03abcefg"), Ok((&b"efg"[..], &b"abc"[..])));
915 /// assert_eq!(parser(b"\x00\x03"), Err(Err::Incomplete(Size(3))));
916 /// ```
length_data<I, N, E, F>(f: F) -> impl Fn(I) -> IResult<I, I, E> where I: Clone + InputLength + InputTake, N: Copy + ToUsize, F: Fn(I) -> IResult<I, N, E>, E: ParseError<I>,917 pub fn length_data<I, N, E, F>(f: F) -> impl Fn(I) -> IResult<I, I, E>
918 where
919 I: Clone + InputLength + InputTake,
920 N: Copy + ToUsize,
921 F: Fn(I) -> IResult<I, N, E>,
922 E: ParseError<I>,
923 {
924 move |i: I| {
925 let (i, length) = f(i)?;
926
927 let length: usize = length.to_usize();
928
929 if i.input_len() < length {
930 Err(Err::Incomplete(Needed::Size(length)))
931 } else {
932 Ok(i.take_split(length))
933 }
934 }
935 }
936
937 /// Gets a number from the first parser,
938 /// takes a subslice of the input of that size,
939 /// then applies the second parser on that subslice.
940 /// If the second parser returns Incomplete,
941 /// length_value will return an error.
942 /// # Arguments
943 /// * `f` The parser to apply.
944 /// ```rust
945 /// # #[macro_use] extern crate nom;
946 /// # use nom::{Err, error::ErrorKind, Needed, IResult};
947 /// # use nom::Needed::Size;
948 /// use nom::number::complete::be_u16;
949 /// use nom::multi::length_value;
950 /// use nom::bytes::complete::tag;
951 ///
952 /// fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {
953 /// length_value(be_u16, tag("abc"))(s)
954 /// }
955 ///
956 /// assert_eq!(parser(b"\x00\x03abcefg"), Ok((&b"efg"[..], &b"abc"[..])));
957 /// assert_eq!(parser(b"\x00\x03123123"), Err(Err::Error((&b"123"[..], ErrorKind::Tag))));
958 /// assert_eq!(parser(b"\x00\x03"), Err(Err::Incomplete(Size(3))));
959 /// ```
length_value<I, O, N, E, F, G>(f: F, g: G) -> impl Fn(I) -> IResult<I, O, E> where I: Clone + InputLength + InputTake, N: Copy + ToUsize, F: Fn(I) -> IResult<I, N, E>, G: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,960 pub fn length_value<I, O, N, E, F, G>(f: F, g: G) -> impl Fn(I) -> IResult<I, O, E>
961 where
962 I: Clone + InputLength + InputTake,
963 N: Copy + ToUsize,
964 F: Fn(I) -> IResult<I, N, E>,
965 G: Fn(I) -> IResult<I, O, E>,
966 E: ParseError<I>,
967 {
968 move |i: I| {
969 let (i, length) = f(i)?;
970
971 let length: usize = length.to_usize();
972
973 if i.input_len() < length {
974 Err(Err::Incomplete(Needed::Size(length)))
975 } else {
976 let (rest, i) = i.take_split(length);
977 match g(i.clone()) {
978 Err(Err::Incomplete(_)) =>
979 Err(Err::Error(E::from_error_kind(i, ErrorKind::Complete))),
980 Err(e) => Err(e),
981 Ok((_, o)) => Ok((rest,o)),
982 }
983 }
984 }
985 }
986
987 #[doc(hidden)]
length_valuec<I, O, N, E, F, G>(i: I, f: F, g: G) -> IResult<I, O, E> where I: Clone + InputLength + InputTake, N: Copy + ToUsize, F: Fn(I) -> IResult<I, N, E>, G: Fn(I) -> IResult<I, O, E>, E: ParseError<I>,988 pub fn length_valuec<I, O, N, E, F, G>(i: I, f: F, g: G) -> IResult<I, O, E>
989 where
990 I: Clone + InputLength + InputTake,
991 N: Copy + ToUsize,
992 F: Fn(I) -> IResult<I, N, E>,
993 G: Fn(I) -> IResult<I, O, E>,
994 E: ParseError<I>,
995 {
996 length_value(f, g)(i)
997 }
998