1//! General purpose combinators
2
3#![allow(unused_imports)]
4
5#[cfg(feature = "alloc")]
6use crate::lib::std::boxed::Box;
7
8use crate::error::{ErrorKind, FromExternalError, ParseError};
9use crate::internal::*;
10use crate::lib::std::borrow::Borrow;
11use crate::lib::std::convert::Into;
12#[cfg(feature = "std")]
13use crate::lib::std::fmt::Debug;
14use crate::lib::std::mem::transmute;
15use crate::lib::std::ops::{Range, RangeFrom, RangeTo};
16use crate::traits::{AsChar, InputIter, InputLength, InputTakeAtPosition, ParseTo};
17use crate::traits::{Compare, CompareResult, Offset, Slice};
18
19#[cfg(test)]
20mod tests;
21
22/// Return the remaining input.
23///
24/// ```rust
25/// # use nom::error::ErrorKind;
26/// use nom::combinator::rest;
27/// assert_eq!(rest::<_,(_, ErrorKind)>("abc"), Ok(("", "abc")));
28/// assert_eq!(rest::<_,(_, ErrorKind)>(""), Ok(("", "")));
29/// ```
30#[inline]
31pub fn rest<T, E: ParseError<T>>(input: T) -> IResult<T, T, E>
32where
33 T: Slice<RangeFrom<usize>>,
34 T: InputLength,
35{
36 Ok((input.slice(range:input.input_len()..), input))
37}
38
39/// Return the length of the remaining input.
40///
41/// ```rust
42/// # use nom::error::ErrorKind;
43/// use nom::combinator::rest_len;
44/// assert_eq!(rest_len::<_,(_, ErrorKind)>("abc"), Ok(("abc", 3)));
45/// assert_eq!(rest_len::<_,(_, ErrorKind)>(""), Ok(("", 0)));
46/// ```
47#[inline]
48pub fn rest_len<T, E: ParseError<T>>(input: T) -> IResult<T, usize, E>
49where
50 T: InputLength,
51{
52 let len: usize = input.input_len();
53 Ok((input, len))
54}
55
56/// Maps a function on the result of a parser.
57///
58/// ```rust
59/// use nom::{Err,error::ErrorKind, IResult,Parser};
60/// use nom::character::complete::digit1;
61/// use nom::combinator::map;
62/// # fn main() {
63///
64/// let mut parser = map(digit1, |s: &str| s.len());
65///
66/// // the parser will count how many characters were returned by digit1
67/// assert_eq!(parser.parse("123456"), Ok(("", 6)));
68///
69/// // this will fail if digit1 fails
70/// assert_eq!(parser.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
71/// # }
72/// ```
73pub fn map<I, O1, O2, E, F, G>(mut parser: F, mut f: G) -> impl FnMut(I) -> IResult<I, O2, E>
74where
75 F: Parser<I, O1, E>,
76 G: FnMut(O1) -> O2,
77{
78 move |input: I| {
79 let (input: I, o1: O1) = parser.parse(input)?;
80 Ok((input, f(o1)))
81 }
82}
83
84/// Applies a function returning a `Result` over the result of a parser.
85///
86/// ```rust
87/// # use nom::{Err,error::ErrorKind, IResult};
88/// use nom::character::complete::digit1;
89/// use nom::combinator::map_res;
90/// # fn main() {
91///
92/// let mut parse = map_res(digit1, |s: &str| s.parse::<u8>());
93///
94/// // the parser will convert the result of digit1 to a number
95/// assert_eq!(parse("123"), Ok(("", 123)));
96///
97/// // this will fail if digit1 fails
98/// assert_eq!(parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
99///
100/// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
101/// assert_eq!(parse("123456"), Err(Err::Error(("123456", ErrorKind::MapRes))));
102/// # }
103/// ```
104pub fn map_res<I: Clone, O1, O2, E: FromExternalError<I, E2>, E2, F, G>(
105 mut parser: F,
106 mut f: G,
107) -> impl FnMut(I) -> IResult<I, O2, E>
108where
109 F: Parser<I, O1, E>,
110 G: FnMut(O1) -> Result<O2, E2>,
111{
112 move |input: I| {
113 let i: I = input.clone();
114 let (input: I, o1: O1) = parser.parse(input)?;
115 match f(o1) {
116 Ok(o2: O2) => Ok((input, o2)),
117 Err(e: E2) => Err(Err::Error(E::from_external_error(input:i, kind:ErrorKind::MapRes, e))),
118 }
119 }
120}
121
122/// Applies a function returning an `Option` over the result of a parser.
123///
124/// ```rust
125/// # use nom::{Err,error::ErrorKind, IResult};
126/// use nom::character::complete::digit1;
127/// use nom::combinator::map_opt;
128/// # fn main() {
129///
130/// let mut parse = map_opt(digit1, |s: &str| s.parse::<u8>().ok());
131///
132/// // the parser will convert the result of digit1 to a number
133/// assert_eq!(parse("123"), Ok(("", 123)));
134///
135/// // this will fail if digit1 fails
136/// assert_eq!(parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
137///
138/// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
139/// assert_eq!(parse("123456"), Err(Err::Error(("123456", ErrorKind::MapOpt))));
140/// # }
141/// ```
142pub fn map_opt<I: Clone, O1, O2, E: ParseError<I>, F, G>(
143 mut parser: F,
144 mut f: G,
145) -> impl FnMut(I) -> IResult<I, O2, E>
146where
147 F: Parser<I, O1, E>,
148 G: FnMut(O1) -> Option<O2>,
149{
150 move |input: I| {
151 let i: I = input.clone();
152 let (input: I, o1: O1) = parser.parse(input)?;
153 match f(o1) {
154 Some(o2: O2) => Ok((input, o2)),
155 None => Err(Err::Error(E::from_error_kind(input:i, kind:ErrorKind::MapOpt))),
156 }
157 }
158}
159
160/// Applies a parser over the result of another one.
161///
162/// ```rust
163/// # use nom::{Err,error::ErrorKind, IResult};
164/// use nom::character::complete::digit1;
165/// use nom::bytes::complete::take;
166/// use nom::combinator::map_parser;
167/// # fn main() {
168///
169/// let mut parse = map_parser(take(5u8), digit1);
170///
171/// assert_eq!(parse("12345"), Ok(("", "12345")));
172/// assert_eq!(parse("123ab"), Ok(("", "123")));
173/// assert_eq!(parse("123"), Err(Err::Error(("123", ErrorKind::Eof))));
174/// # }
175/// ```
176pub fn map_parser<I, O1, O2, E: ParseError<I>, F, G>(
177 mut parser: F,
178 mut applied_parser: G,
179) -> impl FnMut(I) -> IResult<I, O2, E>
180where
181 F: Parser<I, O1, E>,
182 G: Parser<O1, O2, E>,
183{
184 move |input: I| {
185 let (input: I, o1: O1) = parser.parse(input)?;
186 let (_, o2: O2) = applied_parser.parse(input:o1)?;
187 Ok((input, o2))
188 }
189}
190
191/// Creates a new parser from the output of the first parser, then apply that parser over the rest of the input.
192///
193/// ```rust
194/// # use nom::{Err,error::ErrorKind, IResult};
195/// use nom::bytes::complete::take;
196/// use nom::number::complete::u8;
197/// use nom::combinator::flat_map;
198/// # fn main() {
199///
200/// let mut parse = flat_map(u8, take);
201///
202/// assert_eq!(parse(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..])));
203/// assert_eq!(parse(&[4, 0, 1, 2][..]), Err(Err::Error((&[0, 1, 2][..], ErrorKind::Eof))));
204/// # }
205/// ```
206pub fn flat_map<I, O1, O2, E: ParseError<I>, F, G, H>(
207 mut parser: F,
208 mut applied_parser: G,
209) -> impl FnMut(I) -> IResult<I, O2, E>
210where
211 F: Parser<I, O1, E>,
212 G: FnMut(O1) -> H,
213 H: Parser<I, O2, E>,
214{
215 move |input: I| {
216 let (input: I, o1: O1) = parser.parse(input)?;
217 applied_parser(o1).parse(input)
218 }
219}
220
221/// Optional parser, will return `None` on [`Err::Error`].
222///
223/// To chain an error up, see [`cut`].
224///
225/// ```rust
226/// # use nom::{Err,error::ErrorKind, IResult};
227/// use nom::combinator::opt;
228/// use nom::character::complete::alpha1;
229/// # fn main() {
230///
231/// fn parser(i: &str) -> IResult<&str, Option<&str>> {
232/// opt(alpha1)(i)
233/// }
234///
235/// assert_eq!(parser("abcd;"), Ok((";", Some("abcd"))));
236/// assert_eq!(parser("123;"), Ok(("123;", None)));
237/// # }
238/// ```
239pub fn opt<I: Clone, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, Option<O>, E>
240where
241 F: Parser<I, O, E>,
242{
243 move |input: I| {
244 let i: I = input.clone();
245 match f.parse(input) {
246 Ok((i: I, o: O)) => Ok((i, Some(o))),
247 Err(Err::Error(_)) => Ok((i, None)),
248 Err(e: Err) => Err(e),
249 }
250 }
251}
252
253/// Calls the parser if the condition is met.
254///
255/// ```rust
256/// # use nom::{Err, error::{Error, ErrorKind}, IResult};
257/// use nom::combinator::cond;
258/// use nom::character::complete::alpha1;
259/// # fn main() {
260///
261/// fn parser(b: bool, i: &str) -> IResult<&str, Option<&str>> {
262/// cond(b, alpha1)(i)
263/// }
264///
265/// assert_eq!(parser(true, "abcd;"), Ok((";", Some("abcd"))));
266/// assert_eq!(parser(false, "abcd;"), Ok(("abcd;", None)));
267/// assert_eq!(parser(true, "123;"), Err(Err::Error(Error::new("123;", ErrorKind::Alpha))));
268/// assert_eq!(parser(false, "123;"), Ok(("123;", None)));
269/// # }
270/// ```
271pub fn cond<I, O, E: ParseError<I>, F>(
272 b: bool,
273 mut f: F,
274) -> impl FnMut(I) -> IResult<I, Option<O>, E>
275where
276 F: Parser<I, O, E>,
277{
278 move |input: I| {
279 if b {
280 match f.parse(input) {
281 Ok((i: I, o: O)) => Ok((i, Some(o))),
282 Err(e: Err) => Err(e),
283 }
284 } else {
285 Ok((input, None))
286 }
287 }
288}
289
290/// Tries to apply its parser without consuming the input.
291///
292/// ```rust
293/// # use nom::{Err,error::ErrorKind, IResult};
294/// use nom::combinator::peek;
295/// use nom::character::complete::alpha1;
296/// # fn main() {
297///
298/// let mut parser = peek(alpha1);
299///
300/// assert_eq!(parser("abcd;"), Ok(("abcd;", "abcd")));
301/// assert_eq!(parser("123;"), Err(Err::Error(("123;", ErrorKind::Alpha))));
302/// # }
303/// ```
304pub fn peek<I: Clone, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>
305where
306 F: Parser<I, O, E>,
307{
308 move |input: I| {
309 let i: I = input.clone();
310 match f.parse(input) {
311 Ok((_, o: O)) => Ok((i, o)),
312 Err(e: Err) => Err(e),
313 }
314 }
315}
316
317/// returns its input if it is at the end of input data
318///
319/// When we're at the end of the data, this combinator
320/// will succeed
321///
322/// ```
323/// # use std::str;
324/// # use nom::{Err, error::ErrorKind, IResult};
325/// # use nom::combinator::eof;
326///
327/// # fn main() {
328/// let parser = eof;
329/// assert_eq!(parser("abc"), Err(Err::Error(("abc", ErrorKind::Eof))));
330/// assert_eq!(parser(""), Ok(("", "")));
331/// # }
332/// ```
333pub fn eof<I: InputLength + Clone, E: ParseError<I>>(input: I) -> IResult<I, I, E> {
334 if input.input_len() == 0 {
335 let clone: I = input.clone();
336 Ok((input, clone))
337 } else {
338 Err(Err::Error(E::from_error_kind(input, kind:ErrorKind::Eof)))
339 }
340}
341
342/// Transforms Incomplete into `Error`.
343///
344/// ```rust
345/// # use nom::{Err,error::ErrorKind, IResult};
346/// use nom::bytes::streaming::take;
347/// use nom::combinator::complete;
348/// # fn main() {
349///
350/// let mut parser = complete(take(5u8));
351///
352/// assert_eq!(parser("abcdefg"), Ok(("fg", "abcde")));
353/// assert_eq!(parser("abcd"), Err(Err::Error(("abcd", ErrorKind::Complete))));
354/// # }
355/// ```
356pub fn complete<I: Clone, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>
357where
358 F: Parser<I, O, E>,
359{
360 move |input: I| {
361 let i: I = input.clone();
362 match f.parse(input) {
363 Err(Err::Incomplete(_)) => Err(Err::Error(E::from_error_kind(input:i, kind:ErrorKind::Complete))),
364 rest: Result<(I, O), Err> => rest,
365 }
366 }
367}
368
369/// Succeeds if all the input has been consumed by its child parser.
370///
371/// ```rust
372/// # use nom::{Err,error::ErrorKind, IResult};
373/// use nom::combinator::all_consuming;
374/// use nom::character::complete::alpha1;
375/// # fn main() {
376///
377/// let mut parser = all_consuming(alpha1);
378///
379/// assert_eq!(parser("abcd"), Ok(("", "abcd")));
380/// assert_eq!(parser("abcd;"),Err(Err::Error((";", ErrorKind::Eof))));
381/// assert_eq!(parser("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
382/// # }
383/// ```
384pub fn all_consuming<I, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>
385where
386 I: InputLength,
387 F: Parser<I, O, E>,
388{
389 move |input: I| {
390 let (input: I, res: O) = f.parse(input)?;
391 if input.input_len() == 0 {
392 Ok((input, res))
393 } else {
394 Err(Err::Error(E::from_error_kind(input, kind:ErrorKind::Eof)))
395 }
396 }
397}
398
399/// Returns the result of the child parser if it satisfies a verification function.
400///
401/// The verification function takes as argument a reference to the output of the
402/// parser.
403///
404/// ```rust
405/// # use nom::{Err,error::ErrorKind, IResult};
406/// use nom::combinator::verify;
407/// use nom::character::complete::alpha1;
408/// # fn main() {
409///
410/// let mut parser = verify(alpha1, |s: &str| s.len() == 4);
411///
412/// assert_eq!(parser("abcd"), Ok(("", "abcd")));
413/// assert_eq!(parser("abcde"), Err(Err::Error(("abcde", ErrorKind::Verify))));
414/// assert_eq!(parser("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
415/// # }
416/// ```
417pub fn verify<I: Clone, O1, O2, E: ParseError<I>, F, G>(
418 mut first: F,
419 second: G,
420) -> impl FnMut(I) -> IResult<I, O1, E>
421where
422 F: Parser<I, O1, E>,
423 G: Fn(&O2) -> bool,
424 O1: Borrow<O2>,
425 O2: ?Sized,
426{
427 move |input: I| {
428 let i: I = input.clone();
429 let (input: I, o: O1) = first.parse(input)?;
430
431 if second(o.borrow()) {
432 Ok((input, o))
433 } else {
434 Err(Err::Error(E::from_error_kind(input:i, kind:ErrorKind::Verify)))
435 }
436 }
437}
438
439/// Returns the provided value if the child parser succeeds.
440///
441/// ```rust
442/// # use nom::{Err,error::ErrorKind, IResult};
443/// use nom::combinator::value;
444/// use nom::character::complete::alpha1;
445/// # fn main() {
446///
447/// let mut parser = value(1234, alpha1);
448///
449/// assert_eq!(parser("abcd"), Ok(("", 1234)));
450/// assert_eq!(parser("123abcd;"), Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
451/// # }
452/// ```
453pub fn value<I, O1: Clone, O2, E: ParseError<I>, F>(
454 val: O1,
455 mut parser: F,
456) -> impl FnMut(I) -> IResult<I, O1, E>
457where
458 F: Parser<I, O2, E>,
459{
460 move |input: I| parser.parse(input).map(|(i: I, _)| (i, val.clone()))
461}
462
463/// Succeeds if the child parser returns an error.
464///
465/// ```rust
466/// # use nom::{Err,error::ErrorKind, IResult};
467/// use nom::combinator::not;
468/// use nom::character::complete::alpha1;
469/// # fn main() {
470///
471/// let mut parser = not(alpha1);
472///
473/// assert_eq!(parser("123"), Ok(("123", ())));
474/// assert_eq!(parser("abcd"), Err(Err::Error(("abcd", ErrorKind::Not))));
475/// # }
476/// ```
477pub fn not<I: Clone, O, E: ParseError<I>, F>(mut parser: F) -> impl FnMut(I) -> IResult<I, (), E>
478where
479 F: Parser<I, O, E>,
480{
481 move |input: I| {
482 let i: I = input.clone();
483 match parser.parse(input) {
484 Ok(_) => Err(Err::Error(E::from_error_kind(input:i, kind:ErrorKind::Not))),
485 Err(Err::Error(_)) => Ok((i, ())),
486 Err(e: Err) => Err(e),
487 }
488 }
489}
490
491/// If the child parser was successful, return the consumed input as produced value.
492///
493/// ```rust
494/// # use nom::{Err,error::ErrorKind, IResult};
495/// use nom::combinator::recognize;
496/// use nom::character::complete::{char, alpha1};
497/// use nom::sequence::separated_pair;
498/// # fn main() {
499///
500/// let mut parser = recognize(separated_pair(alpha1, char(','), alpha1));
501///
502/// assert_eq!(parser("abcd,efgh"), Ok(("", "abcd,efgh")));
503/// assert_eq!(parser("abcd;"),Err(Err::Error((";", ErrorKind::Char))));
504/// # }
505/// ```
506pub fn recognize<I: Clone + Offset + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(
507 mut parser: F,
508) -> impl FnMut(I) -> IResult<I, I, E>
509where
510 F: Parser<I, O, E>,
511{
512 move |input: I| {
513 let i: I = input.clone();
514 match parser.parse(input:i) {
515 Ok((i: I, _)) => {
516 let index: usize = input.offset(&i);
517 Ok((i, input.slice(..index)))
518 }
519 Err(e: Err) => Err(e),
520 }
521 }
522}
523
524/// if the child parser was successful, return the consumed input with the output
525/// as a tuple. Functions similarly to [recognize](fn.recognize.html) except it
526/// returns the parser output as well.
527///
528/// This can be useful especially in cases where the output is not the same type
529/// as the input, or the input is a user defined type.
530///
531/// Returned tuple is of the format `(consumed input, produced output)`.
532///
533/// ```rust
534/// # use nom::{Err,error::ErrorKind, IResult};
535/// use nom::combinator::{consumed, value, recognize, map};
536/// use nom::character::complete::{char, alpha1};
537/// use nom::bytes::complete::tag;
538/// use nom::sequence::separated_pair;
539///
540/// fn inner_parser(input: &str) -> IResult<&str, bool> {
541/// value(true, tag("1234"))(input)
542/// }
543///
544/// # fn main() {
545///
546/// let mut consumed_parser = consumed(value(true, separated_pair(alpha1, char(','), alpha1)));
547///
548/// assert_eq!(consumed_parser("abcd,efgh1"), Ok(("1", ("abcd,efgh", true))));
549/// assert_eq!(consumed_parser("abcd;"),Err(Err::Error((";", ErrorKind::Char))));
550///
551///
552/// // the first output (representing the consumed input)
553/// // should be the same as that of the `recognize` parser.
554/// let mut recognize_parser = recognize(inner_parser);
555/// let mut consumed_parser = map(consumed(inner_parser), |(consumed, output)| consumed);
556///
557/// assert_eq!(recognize_parser("1234"), consumed_parser("1234"));
558/// assert_eq!(recognize_parser("abcd"), consumed_parser("abcd"));
559/// # }
560/// ```
561pub fn consumed<I, O, F, E>(mut parser: F) -> impl FnMut(I) -> IResult<I, (I, O), E>
562where
563 I: Clone + Offset + Slice<RangeTo<usize>>,
564 E: ParseError<I>,
565 F: Parser<I, O, E>,
566{
567 move |input: I| {
568 let i: I = input.clone();
569 match parser.parse(input:i) {
570 Ok((remaining: I, result: O)) => {
571 let index: usize = input.offset(&remaining);
572 let consumed: I = input.slice(..index);
573 Ok((remaining, (consumed, result)))
574 }
575 Err(e: Err) => Err(e),
576 }
577 }
578}
579
580/// Transforms an [`Err::Error`] (recoverable) to [`Err::Failure`] (unrecoverable)
581///
582/// This commits the parse result, preventing alternative branch paths like with
583/// [`nom::branch::alt`][crate::branch::alt].
584///
585/// # Example
586///
587/// Without `cut`:
588/// ```rust
589/// # use nom::{Err,error::ErrorKind, IResult};
590/// # use nom::character::complete::{one_of, digit1};
591/// # use nom::combinator::rest;
592/// # use nom::branch::alt;
593/// # use nom::sequence::preceded;
594/// # fn main() {
595///
596/// fn parser(input: &str) -> IResult<&str, &str> {
597/// alt((
598/// preceded(one_of("+-"), digit1),
599/// rest
600/// ))(input)
601/// }
602///
603/// assert_eq!(parser("+10 ab"), Ok((" ab", "10")));
604/// assert_eq!(parser("ab"), Ok(("", "ab")));
605/// assert_eq!(parser("+"), Ok(("", "+")));
606/// # }
607/// ```
608///
609/// With `cut`:
610/// ```rust
611/// # use nom::{Err,error::ErrorKind, IResult, error::Error};
612/// # use nom::character::complete::{one_of, digit1};
613/// # use nom::combinator::rest;
614/// # use nom::branch::alt;
615/// # use nom::sequence::preceded;
616/// use nom::combinator::cut;
617/// # fn main() {
618///
619/// fn parser(input: &str) -> IResult<&str, &str> {
620/// alt((
621/// preceded(one_of("+-"), cut(digit1)),
622/// rest
623/// ))(input)
624/// }
625///
626/// assert_eq!(parser("+10 ab"), Ok((" ab", "10")));
627/// assert_eq!(parser("ab"), Ok(("", "ab")));
628/// assert_eq!(parser("+"), Err(Err::Failure(Error { input: "", code: ErrorKind::Digit })));
629/// # }
630/// ```
631pub fn cut<I, O, E: ParseError<I>, F>(mut parser: F) -> impl FnMut(I) -> IResult<I, O, E>
632where
633 F: Parser<I, O, E>,
634{
635 move |input: I| match parser.parse(input) {
636 Err(Err::Error(e: E)) => Err(Err::Failure(e)),
637 rest: Result<(I, O), Err> => rest,
638 }
639}
640
641/// automatically converts the child parser's result to another type
642///
643/// it will be able to convert the output value and the error value
644/// as long as the `Into` implementations are available
645///
646/// ```rust
647/// # use nom::IResult;
648/// use nom::combinator::into;
649/// use nom::character::complete::alpha1;
650/// # fn main() {
651///
652/// fn parser1(i: &str) -> IResult<&str, &str> {
653/// alpha1(i)
654/// }
655///
656/// let mut parser2 = into(parser1);
657///
658/// // the parser converts the &str output of the child parser into a Vec<u8>
659/// let bytes: IResult<&str, Vec<u8>> = parser2("abcd");
660/// assert_eq!(bytes, Ok(("", vec![97, 98, 99, 100])));
661/// # }
662/// ```
663pub fn into<I, O1, O2, E1, E2, F>(mut parser: F) -> impl FnMut(I) -> IResult<I, O2, E2>
664where
665 O1: Into<O2>,
666 E1: Into<E2>,
667 E1: ParseError<I>,
668 E2: ParseError<I>,
669 F: Parser<I, O1, E1>,
670{
671 //map(parser, Into::into)
672 move |input: I| match parser.parse(input) {
673 Ok((i: I, o: O1)) => Ok((i, o.into())),
674 Err(Err::Error(e: E1)) => Err(Err::Error(e.into())),
675 Err(Err::Failure(e: E1)) => Err(Err::Failure(e.into())),
676 Err(Err::Incomplete(e: Needed)) => Err(Err::Incomplete(e)),
677 }
678}
679
680/// Creates an iterator from input data and a parser.
681///
682/// Call the iterator's [ParserIterator::finish] method to get the remaining input if successful,
683/// or the error value if we encountered an error.
684///
685/// On [`Err::Error`], iteration will stop. To instead chain an error up, see [`cut`].
686///
687/// ```rust
688/// use nom::{combinator::iterator, IResult, bytes::complete::tag, character::complete::alpha1, sequence::terminated};
689/// use std::collections::HashMap;
690///
691/// let data = "abc|defg|hijkl|mnopqr|123";
692/// let mut it = iterator(data, terminated(alpha1, tag("|")));
693///
694/// let parsed = it.map(|v| (v, v.len())).collect::<HashMap<_,_>>();
695/// let res: IResult<_,_> = it.finish();
696///
697/// assert_eq!(parsed, [("abc", 3usize), ("defg", 4), ("hijkl", 5), ("mnopqr", 6)].iter().cloned().collect());
698/// assert_eq!(res, Ok(("123", ())));
699/// ```
700pub fn iterator<Input, Output, Error, F>(input: Input, f: F) -> ParserIterator<Input, Error, F>
701where
702 F: Parser<Input, Output, Error>,
703 Error: ParseError<Input>,
704{
705 ParserIterator {
706 iterator: f,
707 input,
708 state: Some(State::Running),
709 }
710}
711
712/// Main structure associated to the [iterator] function.
713pub struct ParserIterator<I, E, F> {
714 iterator: F,
715 input: I,
716 state: Option<State<E>>,
717}
718
719impl<I: Clone, E, F> ParserIterator<I, E, F> {
720 /// Returns the remaining input if parsing was successful, or the error if we encountered an error.
721 pub fn finish(mut self) -> IResult<I, (), E> {
722 match self.state.take().unwrap() {
723 State::Running | State::Done => Ok((self.input, ())),
724 State::Failure(e: E) => Err(Err::Failure(e)),
725 State::Incomplete(i: Needed) => Err(Err::Incomplete(i)),
726 }
727 }
728}
729
730impl<'a, Input, Output, Error, F> core::iter::Iterator for &'a mut ParserIterator<Input, Error, F>
731where
732 F: FnMut(Input) -> IResult<Input, Output, Error>,
733 Input: Clone,
734{
735 type Item = Output;
736
737 fn next(&mut self) -> Option<Self::Item> {
738 if let State::Running = self.state.take().unwrap() {
739 let input = self.input.clone();
740
741 match (self.iterator)(input) {
742 Ok((i, o)) => {
743 self.input = i;
744 self.state = Some(State::Running);
745 Some(o)
746 }
747 Err(Err::Error(_)) => {
748 self.state = Some(State::Done);
749 None
750 }
751 Err(Err::Failure(e)) => {
752 self.state = Some(State::Failure(e));
753 None
754 }
755 Err(Err::Incomplete(i)) => {
756 self.state = Some(State::Incomplete(i));
757 None
758 }
759 }
760 } else {
761 None
762 }
763 }
764}
765
766enum State<E> {
767 Running,
768 Done,
769 Failure(E),
770 Incomplete(Needed),
771}
772
773/// a parser which always succeeds with given value without consuming any input.
774///
775/// It can be used for example as the last alternative in `alt` to
776/// specify the default case.
777///
778/// ```rust
779/// # use nom::{Err,error::ErrorKind, IResult};
780/// use nom::branch::alt;
781/// use nom::combinator::{success, value};
782/// use nom::character::complete::char;
783/// # fn main() {
784///
785/// let mut parser = success::<_,_,(_,ErrorKind)>(10);
786/// assert_eq!(parser("xyz"), Ok(("xyz", 10)));
787///
788/// let mut sign = alt((value(-1, char('-')), value(1, char('+')), success::<_,_,(_,ErrorKind)>(1)));
789/// assert_eq!(sign("+10"), Ok(("10", 1)));
790/// assert_eq!(sign("-10"), Ok(("10", -1)));
791/// assert_eq!(sign("10"), Ok(("10", 1)));
792/// # }
793/// ```
794pub fn success<I, O: Clone, E: ParseError<I>>(val: O) -> impl Fn(I) -> IResult<I, O, E> {
795 move |input: I| Ok((input, val.clone()))
796}
797
798/// A parser which always fails.
799///
800/// ```rust
801/// # use nom::{Err, error::ErrorKind, IResult};
802/// use nom::combinator::fail;
803///
804/// let s = "string";
805/// assert_eq!(fail::<_, &str, _>(s), Err(Err::Error((s, ErrorKind::Fail))));
806/// ```
807pub fn fail<I, O, E: ParseError<I>>(i: I) -> IResult<I, O, E> {
808 Err(Err::Error(E::from_error_kind(input:i, kind:ErrorKind::Fail)))
809}
810