• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Basic types to build the parsers
2 
3 use crate::ascii::Caseless as AsciiCaseless;
4 use crate::combinator::impls;
5 #[cfg(feature = "unstable-recover")]
6 #[cfg(feature = "std")]
7 use crate::error::FromRecoverableError;
8 use crate::error::{AddContext, FromExternalError, PResult, ParseError, ParserError};
9 use crate::stream::{Compare, Location, ParseSlice, Stream, StreamIsPartial};
10 #[cfg(feature = "unstable-recover")]
11 #[cfg(feature = "std")]
12 use crate::stream::{Recover, Recoverable};
13 
14 /// Core trait for parsing
15 ///
16 /// The simplest way to implement a `Parser` is with a function
17 /// ```rust
18 /// use winnow::prelude::*;
19 ///
20 /// fn empty(input: &mut &str) -> PResult<()> {
21 ///     let output = ();
22 ///     Ok(output)
23 /// }
24 ///
25 /// let (input, output) = empty.parse_peek("Hello").unwrap();
26 /// assert_eq!(input, "Hello");  // We didn't consume any input
27 /// ```
28 ///
29 /// which can be made stateful by returning a function
30 /// ```rust
31 /// use winnow::prelude::*;
32 ///
33 /// fn empty<O: Clone>(output: O) -> impl FnMut(&mut &str) -> PResult<O> {
34 ///     move |input: &mut &str| {
35 ///         let output = output.clone();
36 ///         Ok(output)
37 ///     }
38 /// }
39 ///
40 /// let (input, output) = empty("World").parse_peek("Hello").unwrap();
41 /// assert_eq!(input, "Hello");  // We didn't consume any input
42 /// assert_eq!(output, "World");
43 /// ```
44 ///
45 /// Additionally, some basic types implement `Parser` as well, including
46 /// - `u8` and `char`, see [`winnow::token::one_of`][crate::token::one_of]
47 /// - `&[u8]` and `&str`, see [`winnow::token::literal`][crate::token::literal]
48 pub trait Parser<I, O, E> {
49     /// Parse all of `input`, generating `O` from it
50     #[inline]
parse(&mut self, mut input: I) -> Result<O, ParseError<I, E>> where Self: core::marker::Sized, I: Stream, I: StreamIsPartial, E: ParserError<I>,51     fn parse(&mut self, mut input: I) -> Result<O, ParseError<I, E>>
52     where
53         Self: core::marker::Sized,
54         I: Stream,
55         // Force users to deal with `Incomplete` when `StreamIsPartial<true>`
56         I: StreamIsPartial,
57         E: ParserError<I>,
58     {
59         debug_assert!(
60             !I::is_partial_supported(),
61             "partial streams need to handle `ErrMode::Incomplete`"
62         );
63 
64         let start = input.checkpoint();
65         let (o, _) = (self.by_ref(), crate::combinator::eof)
66             .parse_next(&mut input)
67             .map_err(|e| {
68                 let e = e
69                     .into_inner()
70                     .expect("complete parsers should not report `ErrMode::Incomplete(_)`");
71                 ParseError::new(input, start, e)
72             })?;
73         Ok(o)
74     }
75 
76     /// Take tokens from the [`Stream`], turning it into the output
77     ///
78     /// This includes advancing the [`Stream`] to the next location.
79     ///
80     /// On error, `input` will be left pointing at the error location.
parse_next(&mut self, input: &mut I) -> PResult<O, E>81     fn parse_next(&mut self, input: &mut I) -> PResult<O, E>;
82 
83     /// Take tokens from the [`Stream`], turning it into the output
84     ///
85     /// This returns a copy of the [`Stream`] advanced to the next location.
86     ///
87     /// <div class="warning">
88     ///
89     /// Generally, prefer [`Parser::parse_next`].
90     /// This is primarily intended for:
91     /// - Migrating from older versions / `nom`
92     /// - Testing [`Parser`]s
93     ///
94     /// For look-ahead parsing, see instead [`peek`][crate::combinator::peek].
95     ///
96     /// </div>
97     #[inline(always)]
parse_peek(&mut self, mut input: I) -> PResult<(I, O), E>98     fn parse_peek(&mut self, mut input: I) -> PResult<(I, O), E> {
99         match self.parse_next(&mut input) {
100             Ok(o) => Ok((input, o)),
101             Err(err) => Err(err),
102         }
103     }
104 
105     /// Treat `&mut Self` as a parser
106     ///
107     /// This helps when needing to move a `Parser` when all you have is a `&mut Parser`.
108     ///
109     /// # Example
110     ///
111     /// Because parsers are `FnMut`, they can be called multiple times. This prevents moving `f`
112     /// into [`length_take`][crate::binary::length_take] and `g` into
113     /// [`Parser::complete_err`]:
114     /// ```rust,compile_fail
115     /// # use winnow::prelude::*;
116     /// # use winnow::Parser;
117     /// # use winnow::error::ParserError;
118     /// # use winnow::binary::length_take;
119     /// pub fn length_value<'i, O, E: ParserError<&'i [u8]>>(
120     ///     mut f: impl Parser<&'i [u8], usize, E>,
121     ///     mut g: impl Parser<&'i [u8], O, E>
122     /// ) -> impl Parser<&'i [u8], O, E> {
123     ///   move |i: &mut &'i [u8]| {
124     ///     let mut data = length_take(f).parse_next(i)?;
125     ///     let o = g.complete_err().parse_next(&mut data)?;
126     ///     Ok(o)
127     ///   }
128     /// }
129     /// ```
130     ///
131     /// By adding `by_ref`, we can make this work:
132     /// ```rust
133     /// # use winnow::prelude::*;
134     /// # use winnow::Parser;
135     /// # use winnow::error::ParserError;
136     /// # use winnow::binary::length_take;
137     /// pub fn length_value<'i, O, E: ParserError<&'i [u8]>>(
138     ///     mut f: impl Parser<&'i [u8], usize, E>,
139     ///     mut g: impl Parser<&'i [u8], O, E>
140     /// ) -> impl Parser<&'i [u8], O, E> {
141     ///   move |i: &mut &'i [u8]| {
142     ///     let mut data = length_take(f.by_ref()).parse_next(i)?;
143     ///     let o = g.by_ref().complete_err().parse_next(&mut data)?;
144     ///     Ok(o)
145     ///   }
146     /// }
147     /// ```
148     #[inline(always)]
by_ref(&mut self) -> impls::ByRef<'_, Self> where Self: core::marker::Sized,149     fn by_ref(&mut self) -> impls::ByRef<'_, Self>
150     where
151         Self: core::marker::Sized,
152     {
153         impls::ByRef { p: self }
154     }
155 
156     /// Produce the provided value
157     ///
158     /// # Example
159     ///
160     /// ```rust
161     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
162     /// use winnow::ascii::alpha1;
163     /// # fn main() {
164     ///
165     /// let mut parser = alpha1.value(1234);
166     ///
167     /// assert_eq!(parser.parse_peek("abcd"), Ok(("", 1234)));
168     /// assert_eq!(parser.parse_peek("123abcd;"), Err(ErrMode::Backtrack(InputError::new("123abcd;", ErrorKind::Slice))));
169     /// # }
170     /// ```
171     #[doc(alias = "to")]
172     #[inline(always)]
value<O2>(self, val: O2) -> impls::Value<Self, I, O, O2, E> where Self: core::marker::Sized, O2: Clone,173     fn value<O2>(self, val: O2) -> impls::Value<Self, I, O, O2, E>
174     where
175         Self: core::marker::Sized,
176         O2: Clone,
177     {
178         impls::Value {
179             parser: self,
180             val,
181             i: Default::default(),
182             o: Default::default(),
183             e: Default::default(),
184         }
185     }
186 
187     /// Produce a type's default value
188     ///
189     /// # Example
190     ///
191     /// ```rust
192     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
193     /// use winnow::ascii::alpha1;
194     /// # fn main() {
195     ///
196     /// let mut parser = alpha1.default_value::<u32>();
197     ///
198     /// assert_eq!(parser.parse_peek("abcd"), Ok(("", 0)));
199     /// assert_eq!(parser.parse_peek("123abcd;"), Err(ErrMode::Backtrack(InputError::new("123abcd;", ErrorKind::Slice))));
200     /// # }
201     /// ```
202     #[inline(always)]
default_value<O2>(self) -> impls::DefaultValue<Self, I, O, O2, E> where Self: core::marker::Sized, O2: core::default::Default,203     fn default_value<O2>(self) -> impls::DefaultValue<Self, I, O, O2, E>
204     where
205         Self: core::marker::Sized,
206         O2: core::default::Default,
207     {
208         impls::DefaultValue {
209             parser: self,
210             o2: Default::default(),
211             i: Default::default(),
212             o: Default::default(),
213             e: Default::default(),
214         }
215     }
216 
217     /// Discards the output of the `Parser`
218     ///
219     /// # Example
220     ///
221     /// ```rust
222     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
223     /// use winnow::ascii::alpha1;
224     /// # fn main() {
225     ///
226     /// let mut parser = alpha1.void();
227     ///
228     /// assert_eq!(parser.parse_peek("abcd"), Ok(("", ())));
229     /// assert_eq!(parser.parse_peek("123abcd;"), Err(ErrMode::Backtrack(InputError::new("123abcd;", ErrorKind::Slice))));
230     /// # }
231     /// ```
232     #[inline(always)]
void(self) -> impls::Void<Self, I, O, E> where Self: core::marker::Sized,233     fn void(self) -> impls::Void<Self, I, O, E>
234     where
235         Self: core::marker::Sized,
236     {
237         impls::Void {
238             parser: self,
239             i: Default::default(),
240             o: Default::default(),
241             e: Default::default(),
242         }
243     }
244 
245     /// Convert the parser's output to another type using [`std::convert::From`]
246     ///
247     /// # Example
248     ///
249     /// ```rust
250     /// # use winnow::prelude::*;
251     /// # use winnow::error::InputError;
252     /// use winnow::ascii::alpha1;
253     /// # fn main() {
254     ///
255     /// fn parser1<'s>(i: &mut &'s str) -> PResult<&'s str, InputError<&'s str>> {
256     ///   alpha1(i)
257     /// }
258     ///
259     /// let mut parser2 = parser1.output_into();
260     ///
261     /// // the parser converts the &str output of the child parser into a Vec<u8>
262     /// let bytes: IResult<&str, Vec<u8>> = parser2.parse_peek("abcd");
263     /// assert_eq!(bytes, Ok(("", vec![97, 98, 99, 100])));
264     /// # }
265     /// ```
266     #[inline(always)]
output_into<O2>(self) -> impls::OutputInto<Self, I, O, O2, E> where Self: core::marker::Sized, O: Into<O2>,267     fn output_into<O2>(self) -> impls::OutputInto<Self, I, O, O2, E>
268     where
269         Self: core::marker::Sized,
270         O: Into<O2>,
271     {
272         impls::OutputInto {
273             parser: self,
274             i: Default::default(),
275             o: Default::default(),
276             o2: Default::default(),
277             e: Default::default(),
278         }
279     }
280 
281     /// Produce the consumed input as produced value.
282     ///
283     /// # Example
284     ///
285     /// ```rust
286     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
287     /// use winnow::ascii::{alpha1};
288     /// use winnow::combinator::separated_pair;
289     /// # fn main() {
290     ///
291     /// let mut parser = separated_pair(alpha1, ',', alpha1).take();
292     ///
293     /// assert_eq!(parser.parse_peek("abcd,efgh"), Ok(("", "abcd,efgh")));
294     /// assert_eq!(parser.parse_peek("abcd;"),Err(ErrMode::Backtrack(InputError::new(";", ErrorKind::Tag))));
295     /// # }
296     /// ```
297     #[doc(alias = "concat")]
298     #[doc(alias = "recognize")]
299     #[inline(always)]
take(self) -> impls::Take<Self, I, O, E> where Self: core::marker::Sized, I: Stream,300     fn take(self) -> impls::Take<Self, I, O, E>
301     where
302         Self: core::marker::Sized,
303         I: Stream,
304     {
305         impls::Take {
306             parser: self,
307             i: Default::default(),
308             o: Default::default(),
309             e: Default::default(),
310         }
311     }
312 
313     /// Replaced with [`Parser::take`]
314     #[inline(always)]
315     #[deprecated(since = "0.6.14", note = "Replaced with `Parser::take`")]
recognize(self) -> impls::Take<Self, I, O, E> where Self: core::marker::Sized, I: Stream,316     fn recognize(self) -> impls::Take<Self, I, O, E>
317     where
318         Self: core::marker::Sized,
319         I: Stream,
320     {
321         impls::Take {
322             parser: self,
323             i: Default::default(),
324             o: Default::default(),
325             e: Default::default(),
326         }
327     }
328 
329     /// Produce the consumed input with the output
330     ///
331     /// Functions similarly to [take][Parser::take] except it
332     /// returns the parser output as well.
333     ///
334     /// This can be useful especially in cases where the output is not the same type
335     /// as the input, or the input is a user defined type.
336     ///
337     /// Returned tuple is of the format `(produced output, consumed input)`.
338     ///
339     /// # Example
340     ///
341     /// ```rust
342     /// # use winnow::prelude::*;
343     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError};
344     /// use winnow::ascii::{alpha1};
345     /// use winnow::token::literal;
346     /// use winnow::combinator::separated_pair;
347     ///
348     /// fn inner_parser<'s>(input: &mut &'s str) -> PResult<bool, InputError<&'s str>> {
349     ///     "1234".value(true).parse_next(input)
350     /// }
351     ///
352     /// let mut consumed_parser = separated_pair(alpha1, ',', alpha1).value(true).with_taken();
353     ///
354     /// assert_eq!(consumed_parser.parse_peek("abcd,efgh1"), Ok(("1", (true, "abcd,efgh"))));
355     /// assert_eq!(consumed_parser.parse_peek("abcd;"),Err(ErrMode::Backtrack(InputError::new(";", ErrorKind::Tag))));
356     ///
357     /// // the second output (representing the consumed input)
358     /// // should be the same as that of the `take` parser.
359     /// let mut take_parser = inner_parser.take();
360     /// let mut consumed_parser = inner_parser.with_taken().map(|(output, consumed)| consumed);
361     ///
362     /// assert_eq!(take_parser.parse_peek("1234"), consumed_parser.parse_peek("1234"));
363     /// assert_eq!(take_parser.parse_peek("abcd"), consumed_parser.parse_peek("abcd"));
364     /// ```
365     #[doc(alias = "consumed")]
366     #[doc(alias = "with_recognized")]
367     #[inline(always)]
with_taken(self) -> impls::WithTaken<Self, I, O, E> where Self: core::marker::Sized, I: Stream,368     fn with_taken(self) -> impls::WithTaken<Self, I, O, E>
369     where
370         Self: core::marker::Sized,
371         I: Stream,
372     {
373         impls::WithTaken {
374             parser: self,
375             i: Default::default(),
376             o: Default::default(),
377             e: Default::default(),
378         }
379     }
380 
381     /// Replaced with [`Parser::with_taken`]
382     #[inline(always)]
383     #[deprecated(since = "0.6.14", note = "Replaced with `Parser::with_taken`")]
with_recognized(self) -> impls::WithTaken<Self, I, O, E> where Self: core::marker::Sized, I: Stream,384     fn with_recognized(self) -> impls::WithTaken<Self, I, O, E>
385     where
386         Self: core::marker::Sized,
387         I: Stream,
388     {
389         impls::WithTaken {
390             parser: self,
391             i: Default::default(),
392             o: Default::default(),
393             e: Default::default(),
394         }
395     }
396 
397     /// Produce the location of the consumed input as produced value.
398     ///
399     /// # Example
400     ///
401     /// ```rust
402     /// # use winnow::prelude::*;
403     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, stream::Stream};
404     /// use winnow::stream::LocatingSlice;
405     /// use winnow::ascii::alpha1;
406     /// use winnow::combinator::separated_pair;
407     ///
408     /// let mut parser = separated_pair(alpha1.span(), ',', alpha1.span());
409     ///
410     /// assert_eq!(parser.parse(LocatingSlice::new("abcd,efgh")), Ok((0..4, 5..9)));
411     /// assert_eq!(parser.parse_peek(LocatingSlice::new("abcd;")),Err(ErrMode::Backtrack(InputError::new(LocatingSlice::new("abcd;").peek_slice(4).0, ErrorKind::Tag))));
412     /// ```
413     #[inline(always)]
span(self) -> impls::Span<Self, I, O, E> where Self: core::marker::Sized, I: Stream + Location,414     fn span(self) -> impls::Span<Self, I, O, E>
415     where
416         Self: core::marker::Sized,
417         I: Stream + Location,
418     {
419         impls::Span {
420             parser: self,
421             i: Default::default(),
422             o: Default::default(),
423             e: Default::default(),
424         }
425     }
426 
427     /// Produce the location of consumed input with the output
428     ///
429     /// Functions similarly to [`Parser::span`] except it
430     /// returns the parser output as well.
431     ///
432     /// This can be useful especially in cases where the output is not the same type
433     /// as the input, or the input is a user defined type.
434     ///
435     /// Returned tuple is of the format `(produced output, consumed input)`.
436     ///
437     /// # Example
438     ///
439     /// ```rust
440     /// # use winnow::prelude::*;
441     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, stream::Stream};
442     /// use winnow::stream::LocatingSlice;
443     /// use winnow::ascii::alpha1;
444     /// use winnow::token::literal;
445     /// use winnow::combinator::separated_pair;
446     ///
447     /// fn inner_parser<'s>(input: &mut LocatingSlice<&'s str>) -> PResult<bool, InputError<LocatingSlice<&'s str>>> {
448     ///     "1234".value(true).parse_next(input)
449     /// }
450     ///
451     /// # fn main() {
452     ///
453     /// let mut consumed_parser = separated_pair(alpha1.value(1).with_span(), ',', alpha1.value(2).with_span());
454     ///
455     /// assert_eq!(consumed_parser.parse(LocatingSlice::new("abcd,efgh")), Ok(((1, 0..4), (2, 5..9))));
456     /// assert_eq!(consumed_parser.parse_peek(LocatingSlice::new("abcd;")),Err(ErrMode::Backtrack(InputError::new(LocatingSlice::new("abcd;").peek_slice(4).0, ErrorKind::Tag))));
457     ///
458     /// // the second output (representing the consumed input)
459     /// // should be the same as that of the `span` parser.
460     /// let mut span_parser = inner_parser.span();
461     /// let mut consumed_parser = inner_parser.with_span().map(|(output, consumed)| consumed);
462     ///
463     /// assert_eq!(span_parser.parse_peek(LocatingSlice::new("1234")), consumed_parser.parse_peek(LocatingSlice::new("1234")));
464     /// assert_eq!(span_parser.parse_peek(LocatingSlice::new("abcd")), consumed_parser.parse_peek(LocatingSlice::new("abcd")));
465     /// # }
466     /// ```
467     #[inline(always)]
with_span(self) -> impls::WithSpan<Self, I, O, E> where Self: core::marker::Sized, I: Stream + Location,468     fn with_span(self) -> impls::WithSpan<Self, I, O, E>
469     where
470         Self: core::marker::Sized,
471         I: Stream + Location,
472     {
473         impls::WithSpan {
474             parser: self,
475             i: Default::default(),
476             o: Default::default(),
477             e: Default::default(),
478         }
479     }
480 
481     /// Maps a function over the output of a parser
482     ///
483     /// # Example
484     ///
485     /// ```rust
486     /// use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
487     /// use winnow::ascii::digit1;
488     /// # fn main() {
489     ///
490     /// let mut parser = digit1.map(|s: &str| s.len());
491     ///
492     /// // the parser will count how many characters were returned by digit1
493     /// assert_eq!(parser.parse_peek("123456"), Ok(("", 6)));
494     ///
495     /// // this will fail if digit1 fails
496     /// assert_eq!(parser.parse_peek("abc"), Err(ErrMode::Backtrack(InputError::new("abc", ErrorKind::Slice))));
497     /// # }
498     /// ```
499     #[inline(always)]
map<G, O2>(self, map: G) -> impls::Map<Self, G, I, O, O2, E> where G: FnMut(O) -> O2, Self: core::marker::Sized,500     fn map<G, O2>(self, map: G) -> impls::Map<Self, G, I, O, O2, E>
501     where
502         G: FnMut(O) -> O2,
503         Self: core::marker::Sized,
504     {
505         impls::Map {
506             parser: self,
507             map,
508             i: Default::default(),
509             o: Default::default(),
510             o2: Default::default(),
511             e: Default::default(),
512         }
513     }
514 
515     /// Applies a function returning a `Result` over the output of a parser.
516     ///
517     /// # Example
518     ///
519     /// ```rust
520     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
521     /// use winnow::ascii::digit1;
522     /// # fn main() {
523     ///
524     /// let mut parse = digit1.try_map(|s: &str| s.parse::<u8>());
525     ///
526     /// // the parser will convert the result of digit1 to a number
527     /// assert_eq!(parse.parse_peek("123"), Ok(("", 123)));
528     ///
529     /// // this will fail if digit1 fails
530     /// assert_eq!(parse.parse_peek("abc"), Err(ErrMode::Backtrack(InputError::new("abc", ErrorKind::Slice))));
531     ///
532     /// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
533     /// assert_eq!(parse.parse_peek("123456"), Err(ErrMode::Backtrack(InputError::new("123456", ErrorKind::Verify))));
534     /// # }
535     /// ```
536     #[inline(always)]
try_map<G, O2, E2>(self, map: G) -> impls::TryMap<Self, G, I, O, O2, E, E2> where Self: core::marker::Sized, G: FnMut(O) -> Result<O2, E2>, I: Stream, E: FromExternalError<I, E2>,537     fn try_map<G, O2, E2>(self, map: G) -> impls::TryMap<Self, G, I, O, O2, E, E2>
538     where
539         Self: core::marker::Sized,
540         G: FnMut(O) -> Result<O2, E2>,
541         I: Stream,
542         E: FromExternalError<I, E2>,
543     {
544         impls::TryMap {
545             parser: self,
546             map,
547             i: Default::default(),
548             o: Default::default(),
549             o2: Default::default(),
550             e: Default::default(),
551             e2: Default::default(),
552         }
553     }
554 
555     /// Apply both [`Parser::verify`] and [`Parser::map`].
556     ///
557     /// # Example
558     ///
559     /// ```rust
560     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
561     /// use winnow::ascii::digit1;
562     /// # fn main() {
563     ///
564     /// let mut parse = digit1.verify_map(|s: &str| s.parse::<u8>().ok());
565     ///
566     /// // the parser will convert the result of digit1 to a number
567     /// assert_eq!(parse.parse_peek("123"), Ok(("", 123)));
568     ///
569     /// // this will fail if digit1 fails
570     /// assert_eq!(parse.parse_peek("abc"), Err(ErrMode::Backtrack(InputError::new("abc", ErrorKind::Slice))));
571     ///
572     /// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
573     /// assert_eq!(parse.parse_peek("123456"), Err(ErrMode::Backtrack(InputError::new("123456", ErrorKind::Verify))));
574     /// # }
575     /// ```
576     #[doc(alias = "satisfy_map")]
577     #[doc(alias = "filter_map")]
578     #[doc(alias = "map_opt")]
579     #[inline(always)]
verify_map<G, O2>(self, map: G) -> impls::VerifyMap<Self, G, I, O, O2, E> where Self: core::marker::Sized, G: FnMut(O) -> Option<O2>, I: Stream, E: ParserError<I>,580     fn verify_map<G, O2>(self, map: G) -> impls::VerifyMap<Self, G, I, O, O2, E>
581     where
582         Self: core::marker::Sized,
583         G: FnMut(O) -> Option<O2>,
584         I: Stream,
585         E: ParserError<I>,
586     {
587         impls::VerifyMap {
588             parser: self,
589             map,
590             i: Default::default(),
591             o: Default::default(),
592             o2: Default::default(),
593             e: Default::default(),
594         }
595     }
596 
597     /// Creates a parser from the output of this one
598     ///
599     /// # Example
600     ///
601     /// ```rust
602     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, PResult, Parser};
603     /// use winnow::token::take;
604     /// use winnow::binary::u8;
605     ///
606     /// fn length_take<'s>(input: &mut &'s [u8]) -> PResult<&'s [u8], InputError<&'s [u8]>> {
607     ///     u8.flat_map(take).parse_next(input)
608     /// }
609     ///
610     /// assert_eq!(length_take.parse_peek(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..])));
611     /// assert_eq!(length_take.parse_peek(&[4, 0, 1, 2][..]), Err(ErrMode::Backtrack(InputError::new(&[0, 1, 2][..], ErrorKind::Slice))));
612     /// ```
613     ///
614     /// which is the same as
615     /// ```rust
616     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, PResult, Parser};
617     /// use winnow::token::take;
618     /// use winnow::binary::u8;
619     ///
620     /// fn length_take<'s>(input: &mut &'s [u8]) -> PResult<&'s [u8], InputError<&'s [u8]>> {
621     ///     let length = u8.parse_next(input)?;
622     ///     let data = take(length).parse_next(input)?;
623     ///     Ok(data)
624     /// }
625     ///
626     /// assert_eq!(length_take.parse_peek(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..])));
627     /// assert_eq!(length_take.parse_peek(&[4, 0, 1, 2][..]), Err(ErrMode::Backtrack(InputError::new(&[0, 1, 2][..], ErrorKind::Slice))));
628     /// ```
629     #[inline(always)]
flat_map<G, H, O2>(self, map: G) -> impls::FlatMap<Self, G, H, I, O, O2, E> where Self: core::marker::Sized, G: FnMut(O) -> H, H: Parser<I, O2, E>,630     fn flat_map<G, H, O2>(self, map: G) -> impls::FlatMap<Self, G, H, I, O, O2, E>
631     where
632         Self: core::marker::Sized,
633         G: FnMut(O) -> H,
634         H: Parser<I, O2, E>,
635     {
636         impls::FlatMap {
637             f: self,
638             g: map,
639             h: Default::default(),
640             i: Default::default(),
641             o: Default::default(),
642             o2: Default::default(),
643             e: Default::default(),
644         }
645     }
646 
647     /// Applies a second parser over the output of the first one
648     ///
649     /// # Example
650     ///
651     /// ```rust
652     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
653     /// use winnow::ascii::digit1;
654     /// use winnow::token::take;
655     /// # fn main() {
656     ///
657     /// let mut digits = take(5u8).and_then(digit1);
658     ///
659     /// assert_eq!(digits.parse_peek("12345"), Ok(("", "12345")));
660     /// assert_eq!(digits.parse_peek("123ab"), Ok(("", "123")));
661     /// assert_eq!(digits.parse_peek("123"), Err(ErrMode::Backtrack(InputError::new("123", ErrorKind::Slice))));
662     /// # }
663     /// ```
664     #[inline(always)]
and_then<G, O2>(self, inner: G) -> impls::AndThen<Self, G, I, O, O2, E> where Self: core::marker::Sized, G: Parser<O, O2, E>, O: StreamIsPartial, I: Stream,665     fn and_then<G, O2>(self, inner: G) -> impls::AndThen<Self, G, I, O, O2, E>
666     where
667         Self: core::marker::Sized,
668         G: Parser<O, O2, E>,
669         O: StreamIsPartial,
670         I: Stream,
671     {
672         impls::AndThen {
673             outer: self,
674             inner,
675             i: Default::default(),
676             o: Default::default(),
677             o2: Default::default(),
678             e: Default::default(),
679         }
680     }
681 
682     /// Apply [`std::str::FromStr`] to the output of the parser
683     ///
684     /// # Example
685     ///
686     /// ```rust
687     /// # use winnow::prelude::*;
688     /// use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
689     /// use winnow::ascii::digit1;
690     ///
691     /// fn parser<'s>(input: &mut &'s str) -> PResult<u64, InputError<&'s str>> {
692     ///     digit1.parse_to().parse_next(input)
693     /// }
694     ///
695     /// // the parser will count how many characters were returned by digit1
696     /// assert_eq!(parser.parse_peek("123456"), Ok(("", 123456)));
697     ///
698     /// // this will fail if digit1 fails
699     /// assert_eq!(parser.parse_peek("abc"), Err(ErrMode::Backtrack(InputError::new("abc", ErrorKind::Slice))));
700     /// ```
701     #[doc(alias = "from_str")]
702     #[inline(always)]
parse_to<O2>(self) -> impls::ParseTo<Self, I, O, O2, E> where Self: core::marker::Sized, I: Stream, O: ParseSlice<O2>, E: ParserError<I>,703     fn parse_to<O2>(self) -> impls::ParseTo<Self, I, O, O2, E>
704     where
705         Self: core::marker::Sized,
706         I: Stream,
707         O: ParseSlice<O2>,
708         E: ParserError<I>,
709     {
710         impls::ParseTo {
711             p: self,
712             i: Default::default(),
713             o: Default::default(),
714             o2: Default::default(),
715             e: Default::default(),
716         }
717     }
718 
719     /// Returns the output of the child parser if it satisfies a verification function.
720     ///
721     /// The verification function takes as argument a reference to the output of the
722     /// parser.
723     ///
724     /// # Example
725     ///
726     /// ```rust
727     /// # use winnow::{error::ErrMode,error::ErrorKind, error::InputError, Parser};
728     /// # use winnow::ascii::alpha1;
729     /// # fn main() {
730     ///
731     /// let mut parser = alpha1.verify(|s: &str| s.len() == 4);
732     ///
733     /// assert_eq!(parser.parse_peek("abcd"), Ok(("", "abcd")));
734     /// assert_eq!(parser.parse_peek("abcde"), Err(ErrMode::Backtrack(InputError::new("abcde", ErrorKind::Verify))));
735     /// assert_eq!(parser.parse_peek("123abcd;"),Err(ErrMode::Backtrack(InputError::new("123abcd;", ErrorKind::Slice))));
736     /// # }
737     /// ```
738     #[doc(alias = "satisfy")]
739     #[doc(alias = "filter")]
740     #[inline(always)]
verify<G, O2>(self, filter: G) -> impls::Verify<Self, G, I, O, O2, E> where Self: core::marker::Sized, G: FnMut(&O2) -> bool, I: Stream, O: crate::lib::std::borrow::Borrow<O2>, O2: ?Sized, E: ParserError<I>,741     fn verify<G, O2>(self, filter: G) -> impls::Verify<Self, G, I, O, O2, E>
742     where
743         Self: core::marker::Sized,
744         G: FnMut(&O2) -> bool,
745         I: Stream,
746         O: crate::lib::std::borrow::Borrow<O2>,
747         O2: ?Sized,
748         E: ParserError<I>,
749     {
750         impls::Verify {
751             parser: self,
752             filter,
753             i: Default::default(),
754             o: Default::default(),
755             o2: Default::default(),
756             e: Default::default(),
757         }
758     }
759 
760     /// If parsing fails, add context to the error
761     ///
762     /// This is used mainly to add user friendly information
763     /// to errors when backtracking through a parse tree.
764     #[doc(alias = "labelled")]
765     #[inline(always)]
context<C>(self, context: C) -> impls::Context<Self, I, O, E, C> where Self: core::marker::Sized, I: Stream, E: AddContext<I, C>, C: Clone + crate::lib::std::fmt::Debug,766     fn context<C>(self, context: C) -> impls::Context<Self, I, O, E, C>
767     where
768         Self: core::marker::Sized,
769         I: Stream,
770         E: AddContext<I, C>,
771         C: Clone + crate::lib::std::fmt::Debug,
772     {
773         impls::Context {
774             parser: self,
775             context,
776             i: Default::default(),
777             o: Default::default(),
778             e: Default::default(),
779         }
780     }
781 
782     /// Transforms [`Incomplete`][crate::error::ErrMode::Incomplete] into [`Backtrack`][crate::error::ErrMode::Backtrack]
783     ///
784     /// # Example
785     ///
786     /// ```rust
787     /// # use winnow::{error::ErrMode, error::ErrorKind, error::InputError, stream::Partial, Parser};
788     /// # use winnow::token::take;
789     /// # fn main() {
790     ///
791     /// let mut parser = take(5u8).complete_err();
792     ///
793     /// assert_eq!(parser.parse_peek(Partial::new("abcdefg")), Ok((Partial::new("fg"), "abcde")));
794     /// assert_eq!(parser.parse_peek(Partial::new("abcd")), Err(ErrMode::Backtrack(InputError::new(Partial::new("abcd"), ErrorKind::Complete))));
795     /// # }
796     /// ```
797     #[inline(always)]
complete_err(self) -> impls::CompleteErr<Self> where Self: core::marker::Sized,798     fn complete_err(self) -> impls::CompleteErr<Self>
799     where
800         Self: core::marker::Sized,
801     {
802         impls::CompleteErr { f: self }
803     }
804 
805     /// Convert the parser's error to another type using [`std::convert::From`]
806     #[inline(always)]
err_into<E2>(self) -> impls::ErrInto<Self, I, O, E, E2> where Self: core::marker::Sized, E: Into<E2>,807     fn err_into<E2>(self) -> impls::ErrInto<Self, I, O, E, E2>
808     where
809         Self: core::marker::Sized,
810         E: Into<E2>,
811     {
812         impls::ErrInto {
813             parser: self,
814             i: Default::default(),
815             o: Default::default(),
816             e: Default::default(),
817             e2: Default::default(),
818         }
819     }
820 
821     /// Recover from an error by skipping everything `recover` consumes and trying again
822     ///
823     /// If `recover` consumes nothing, the error is returned, allowing an alternative recovery
824     /// method.
825     ///
826     /// This commits the parse result, preventing alternative branch paths like with
827     /// [`winnow::combinator::alt`][crate::combinator::alt].
828     #[inline(always)]
829     #[cfg(feature = "unstable-recover")]
830     #[cfg(feature = "std")]
retry_after<R>(self, recover: R) -> impls::RetryAfter<Self, R, I, O, E> where Self: core::marker::Sized, R: Parser<I, (), E>, I: Stream, I: Recover<E>, E: FromRecoverableError<I, E>,831     fn retry_after<R>(self, recover: R) -> impls::RetryAfter<Self, R, I, O, E>
832     where
833         Self: core::marker::Sized,
834         R: Parser<I, (), E>,
835         I: Stream,
836         I: Recover<E>,
837         E: FromRecoverableError<I, E>,
838     {
839         impls::RetryAfter {
840             parser: self,
841             recover,
842             i: Default::default(),
843             o: Default::default(),
844             e: Default::default(),
845         }
846     }
847 
848     /// Recover from an error by skipping this parse and everything `recover` consumes
849     ///
850     /// This commits the parse result, preventing alternative branch paths like with
851     /// [`winnow::combinator::alt`][crate::combinator::alt].
852     #[inline(always)]
853     #[cfg(feature = "unstable-recover")]
854     #[cfg(feature = "std")]
resume_after<R>(self, recover: R) -> impls::ResumeAfter<Self, R, I, O, E> where Self: core::marker::Sized, R: Parser<I, (), E>, I: Stream, I: Recover<E>, E: FromRecoverableError<I, E>,855     fn resume_after<R>(self, recover: R) -> impls::ResumeAfter<Self, R, I, O, E>
856     where
857         Self: core::marker::Sized,
858         R: Parser<I, (), E>,
859         I: Stream,
860         I: Recover<E>,
861         E: FromRecoverableError<I, E>,
862     {
863         impls::ResumeAfter {
864             parser: self,
865             recover,
866             i: Default::default(),
867             o: Default::default(),
868             e: Default::default(),
869         }
870     }
871 }
872 
873 impl<I, O, E, F> Parser<I, O, E> for F
874 where
875     F: FnMut(&mut I) -> PResult<O, E>,
876     I: Stream,
877 {
878     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<O, E>879     fn parse_next(&mut self, i: &mut I) -> PResult<O, E> {
880         self(i)
881     }
882 }
883 
884 /// This is a shortcut for [`one_of`][crate::token::one_of].
885 ///
886 /// # Example
887 ///
888 /// ```
889 /// # use winnow::prelude::*;
890 /// # use winnow::{error::ErrMode, error::{ErrorKind, InputError}};
891 /// fn parser<'s>(i: &mut &'s [u8]) -> PResult<u8, InputError<&'s [u8]>>  {
892 ///     b'a'.parse_next(i)
893 /// }
894 /// assert_eq!(parser.parse_peek(&b"abc"[..]), Ok((&b"bc"[..], b'a')));
895 /// assert_eq!(parser.parse_peek(&b" abc"[..]), Err(ErrMode::Backtrack(InputError::new(&b" abc"[..], ErrorKind::Tag))));
896 /// assert_eq!(parser.parse_peek(&b"bc"[..]), Err(ErrMode::Backtrack(InputError::new(&b"bc"[..], ErrorKind::Tag))));
897 /// assert_eq!(parser.parse_peek(&b""[..]), Err(ErrMode::Backtrack(InputError::new(&b""[..], ErrorKind::Tag))));
898 /// ```
899 impl<I, E> Parser<I, u8, E> for u8
900 where
901     I: StreamIsPartial,
902     I: Stream,
903     I: Compare<u8>,
904     E: ParserError<I>,
905 {
906     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<u8, E>907     fn parse_next(&mut self, i: &mut I) -> PResult<u8, E> {
908         crate::token::literal(*self).value(*self).parse_next(i)
909     }
910 }
911 
912 /// This is a shortcut for [`one_of`][crate::token::one_of].
913 ///
914 /// # Example
915 ///
916 /// ```
917 /// # use winnow::prelude::*;
918 /// # use winnow::{error::ErrMode, error::{ErrorKind, InputError}};
919 /// fn parser<'s>(i: &mut &'s str) -> PResult<char, InputError<&'s str>> {
920 ///     'a'.parse_next(i)
921 /// }
922 /// assert_eq!(parser.parse_peek("abc"), Ok(("bc", 'a')));
923 /// assert_eq!(parser.parse_peek(" abc"), Err(ErrMode::Backtrack(InputError::new(" abc", ErrorKind::Tag))));
924 /// assert_eq!(parser.parse_peek("bc"), Err(ErrMode::Backtrack(InputError::new("bc", ErrorKind::Tag))));
925 /// assert_eq!(parser.parse_peek(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Tag))));
926 /// ```
927 impl<I, E> Parser<I, char, E> for char
928 where
929     I: StreamIsPartial,
930     I: Stream,
931     I: Compare<char>,
932     E: ParserError<I>,
933 {
934     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<char, E>935     fn parse_next(&mut self, i: &mut I) -> PResult<char, E> {
936         crate::token::literal(*self).value(*self).parse_next(i)
937     }
938 }
939 
940 /// This is a shortcut for [`literal`][crate::token::literal].
941 ///
942 /// # Example
943 /// ```rust
944 /// # use winnow::prelude::*;
945 /// # use winnow::{error::ErrMode, error::{InputError, ErrorKind}, error::Needed};
946 /// # use winnow::combinator::alt;
947 /// # use winnow::token::take;
948 ///
949 /// fn parser<'s>(s: &mut &'s [u8]) -> PResult<&'s [u8], InputError<&'s [u8]>> {
950 ///   alt((&"Hello"[..], take(5usize))).parse_next(s)
951 /// }
952 ///
953 /// assert_eq!(parser.parse_peek(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..])));
954 /// assert_eq!(parser.parse_peek(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..])));
955 /// assert_eq!(parser.parse_peek(&b"Some"[..]), Err(ErrMode::Backtrack(InputError::new(&b"Some"[..], ErrorKind::Slice))));
956 /// assert_eq!(parser.parse_peek(&b""[..]), Err(ErrMode::Backtrack(InputError::new(&b""[..], ErrorKind::Slice))));
957 /// ```
958 impl<'s, I, E: ParserError<I>> Parser<I, <I as Stream>::Slice, E> for &'s [u8]
959 where
960     I: Compare<&'s [u8]> + StreamIsPartial,
961     I: Stream,
962 {
963     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E>964     fn parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E> {
965         crate::token::literal(*self).parse_next(i)
966     }
967 }
968 
969 /// This is a shortcut for [`literal`][crate::token::literal].
970 ///
971 /// # Example
972 /// ```rust
973 /// # use winnow::prelude::*;
974 /// # use winnow::{error::ErrMode, error::{InputError, ErrorKind}, error::Needed};
975 /// # use winnow::combinator::alt;
976 /// # use winnow::token::take;
977 /// use winnow::ascii::Caseless;
978 ///
979 /// fn parser<'s>(s: &mut &'s [u8]) -> PResult<&'s [u8], InputError<&'s [u8]>> {
980 ///   alt((Caseless(&"hello"[..]), take(5usize))).parse_next(s)
981 /// }
982 ///
983 /// assert_eq!(parser.parse_peek(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..])));
984 /// assert_eq!(parser.parse_peek(&b"hello, World!"[..]), Ok((&b", World!"[..], &b"hello"[..])));
985 /// assert_eq!(parser.parse_peek(&b"HeLlo, World!"[..]), Ok((&b", World!"[..], &b"HeLlo"[..])));
986 /// assert_eq!(parser.parse_peek(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..])));
987 /// assert_eq!(parser.parse_peek(&b"Some"[..]), Err(ErrMode::Backtrack(InputError::new(&b"Some"[..], ErrorKind::Slice))));
988 /// assert_eq!(parser.parse_peek(&b""[..]), Err(ErrMode::Backtrack(InputError::new(&b""[..], ErrorKind::Slice))));
989 /// ```
990 impl<'s, I, E: ParserError<I>> Parser<I, <I as Stream>::Slice, E> for AsciiCaseless<&'s [u8]>
991 where
992     I: Compare<AsciiCaseless<&'s [u8]>> + StreamIsPartial,
993     I: Stream,
994 {
995     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E>996     fn parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E> {
997         crate::token::literal(*self).parse_next(i)
998     }
999 }
1000 
1001 /// This is a shortcut for [`literal`][crate::token::literal].
1002 ///
1003 /// # Example
1004 /// ```rust
1005 /// # use winnow::prelude::*;
1006 /// # use winnow::{error::ErrMode, error::{InputError, ErrorKind}, error::Needed};
1007 /// # use winnow::combinator::alt;
1008 /// # use winnow::token::take;
1009 ///
1010 /// fn parser<'s>(s: &mut &'s [u8]) -> PResult<&'s [u8], InputError<&'s [u8]>> {
1011 ///   alt((b"Hello", take(5usize))).parse_next(s)
1012 /// }
1013 ///
1014 /// assert_eq!(parser.parse_peek(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..])));
1015 /// assert_eq!(parser.parse_peek(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..])));
1016 /// assert_eq!(parser.parse_peek(&b"Some"[..]), Err(ErrMode::Backtrack(InputError::new(&b"Some"[..], ErrorKind::Slice))));
1017 /// assert_eq!(parser.parse_peek(&b""[..]), Err(ErrMode::Backtrack(InputError::new(&b""[..], ErrorKind::Slice))));
1018 /// ```
1019 impl<'s, I, E: ParserError<I>, const N: usize> Parser<I, <I as Stream>::Slice, E> for &'s [u8; N]
1020 where
1021     I: Compare<&'s [u8; N]> + StreamIsPartial,
1022     I: Stream,
1023 {
1024     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E>1025     fn parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E> {
1026         crate::token::literal(*self).parse_next(i)
1027     }
1028 }
1029 
1030 /// This is a shortcut for [`literal`][crate::token::literal].
1031 ///
1032 /// # Example
1033 /// ```rust
1034 /// # use winnow::prelude::*;
1035 /// # use winnow::{error::ErrMode, error::{InputError, ErrorKind}, error::Needed};
1036 /// # use winnow::combinator::alt;
1037 /// # use winnow::token::take;
1038 /// use winnow::ascii::Caseless;
1039 ///
1040 /// fn parser<'s>(s: &mut &'s [u8]) -> PResult<&'s [u8], InputError<&'s [u8]>> {
1041 ///   alt((Caseless(b"hello"), take(5usize))).parse_next(s)
1042 /// }
1043 ///
1044 /// assert_eq!(parser.parse_peek(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..])));
1045 /// assert_eq!(parser.parse_peek(&b"hello, World!"[..]), Ok((&b", World!"[..], &b"hello"[..])));
1046 /// assert_eq!(parser.parse_peek(&b"HeLlo, World!"[..]), Ok((&b", World!"[..], &b"HeLlo"[..])));
1047 /// assert_eq!(parser.parse_peek(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..])));
1048 /// assert_eq!(parser.parse_peek(&b"Some"[..]), Err(ErrMode::Backtrack(InputError::new(&b"Some"[..], ErrorKind::Slice))));
1049 /// assert_eq!(parser.parse_peek(&b""[..]), Err(ErrMode::Backtrack(InputError::new(&b""[..], ErrorKind::Slice))));
1050 /// ```
1051 impl<'s, I, E: ParserError<I>, const N: usize> Parser<I, <I as Stream>::Slice, E>
1052     for AsciiCaseless<&'s [u8; N]>
1053 where
1054     I: Compare<AsciiCaseless<&'s [u8; N]>> + StreamIsPartial,
1055     I: Stream,
1056 {
1057     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E>1058     fn parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E> {
1059         crate::token::literal(*self).parse_next(i)
1060     }
1061 }
1062 
1063 /// This is a shortcut for [`literal`][crate::token::literal].
1064 ///
1065 /// # Example
1066 /// ```rust
1067 /// # use winnow::prelude::*;
1068 /// # use winnow::{error::ErrMode, error::{InputError, ErrorKind}};
1069 /// # use winnow::combinator::alt;
1070 /// # use winnow::token::take;
1071 ///
1072 /// fn parser<'s>(s: &mut &'s str) -> PResult<&'s str, InputError<&'s str>> {
1073 ///   alt(("Hello", take(5usize))).parse_next(s)
1074 /// }
1075 ///
1076 /// assert_eq!(parser.parse_peek("Hello, World!"), Ok((", World!", "Hello")));
1077 /// assert_eq!(parser.parse_peek("Something"), Ok(("hing", "Somet")));
1078 /// assert_eq!(parser.parse_peek("Some"), Err(ErrMode::Backtrack(InputError::new("Some", ErrorKind::Slice))));
1079 /// assert_eq!(parser.parse_peek(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Slice))));
1080 /// ```
1081 impl<'s, I, E: ParserError<I>> Parser<I, <I as Stream>::Slice, E> for &'s str
1082 where
1083     I: Compare<&'s str> + StreamIsPartial,
1084     I: Stream,
1085 {
1086     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E>1087     fn parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E> {
1088         crate::token::literal(*self).parse_next(i)
1089     }
1090 }
1091 
1092 /// This is a shortcut for [`literal`][crate::token::literal].
1093 ///
1094 /// # Example
1095 /// ```rust
1096 /// # use winnow::prelude::*;
1097 /// # use winnow::{error::ErrMode, error::{InputError, ErrorKind}};
1098 /// # use winnow::combinator::alt;
1099 /// # use winnow::token::take;
1100 /// # use winnow::ascii::Caseless;
1101 ///
1102 /// fn parser<'s>(s: &mut &'s str) -> PResult<&'s str, InputError<&'s str>> {
1103 ///   alt((Caseless("hello"), take(5usize))).parse_next(s)
1104 /// }
1105 ///
1106 /// assert_eq!(parser.parse_peek("Hello, World!"), Ok((", World!", "Hello")));
1107 /// assert_eq!(parser.parse_peek("hello, World!"), Ok((", World!", "hello")));
1108 /// assert_eq!(parser.parse_peek("HeLlo, World!"), Ok((", World!", "HeLlo")));
1109 /// assert_eq!(parser.parse_peek("Something"), Ok(("hing", "Somet")));
1110 /// assert_eq!(parser.parse_peek("Some"), Err(ErrMode::Backtrack(InputError::new("Some", ErrorKind::Slice))));
1111 /// assert_eq!(parser.parse_peek(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Slice))));
1112 /// ```
1113 impl<'s, I, E: ParserError<I>> Parser<I, <I as Stream>::Slice, E> for AsciiCaseless<&'s str>
1114 where
1115     I: Compare<AsciiCaseless<&'s str>> + StreamIsPartial,
1116     I: Stream,
1117 {
1118     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E>1119     fn parse_next(&mut self, i: &mut I) -> PResult<<I as Stream>::Slice, E> {
1120         crate::token::literal(*self).parse_next(i)
1121     }
1122 }
1123 
1124 impl<I: Stream, E: ParserError<I>> Parser<I, (), E> for () {
1125     #[inline(always)]
parse_next(&mut self, _i: &mut I) -> PResult<(), E>1126     fn parse_next(&mut self, _i: &mut I) -> PResult<(), E> {
1127         Ok(())
1128     }
1129 }
1130 
1131 macro_rules! impl_parser_for_tuple {
1132   ($($parser:ident $output:ident),+) => (
1133     #[allow(non_snake_case)]
1134     impl<I: Stream, $($output),+, E: ParserError<I>, $($parser),+> Parser<I, ($($output),+,), E> for ($($parser),+,)
1135     where
1136       $($parser: Parser<I, $output, E>),+
1137     {
1138       #[inline(always)]
1139       fn parse_next(&mut self, i: &mut I) -> PResult<($($output),+,), E> {
1140         let ($(ref mut $parser),+,) = *self;
1141 
1142         $(let $output = $parser.parse_next(i)?;)+
1143 
1144         Ok(($($output),+,))
1145       }
1146     }
1147   )
1148 }
1149 
1150 macro_rules! impl_parser_for_tuples {
1151     ($parser1:ident $output1:ident, $($parser:ident $output:ident),+) => {
1152         impl_parser_for_tuples!(__impl $parser1 $output1; $($parser $output),+);
1153     };
1154     (__impl $($parser:ident $output:ident),+; $parser1:ident $output1:ident $(,$parser2:ident $output2:ident)*) => {
1155         impl_parser_for_tuple!($($parser $output),+);
1156         impl_parser_for_tuples!(__impl $($parser $output),+, $parser1 $output1; $($parser2 $output2),*);
1157     };
1158     (__impl $($parser:ident $output:ident),+;) => {
1159         impl_parser_for_tuple!($($parser $output),+);
1160     }
1161 }
1162 
1163 /// Trait alias for [`Parser`] to ease the transition to the next release
1164 pub trait ModalParser<I, O, E>: Parser<I, O, E> {}
1165 
1166 impl<I, O, E, P> ModalParser<I, O, E> for P where P: Parser<I, O, E> {}
1167 
1168 /// Collect all errors when parsing the input
1169 ///
1170 /// [`Parser`]s will need to use [`Recoverable<I, _>`] for their input.
1171 #[cfg(feature = "unstable-recover")]
1172 #[cfg(feature = "std")]
1173 pub trait RecoverableParser<I, O, R, E> {
1174     /// Collect all errors when parsing the input
1175     ///
1176     /// If `self` fails, this acts like [`Parser::resume_after`] and returns `Ok(None)`.
1177     /// Generally, this should be avoided by using
1178     /// [`Parser::retry_after`] and [`Parser::resume_after`] throughout your parser.
1179     ///
1180     /// The empty `input` is returned to allow turning the errors into [`ParserError`]s.
recoverable_parse(&mut self, input: I) -> (I, Option<O>, Vec<R>)1181     fn recoverable_parse(&mut self, input: I) -> (I, Option<O>, Vec<R>);
1182 }
1183 
1184 #[cfg(feature = "unstable-recover")]
1185 #[cfg(feature = "std")]
1186 impl<P, I, O, R, E> RecoverableParser<I, O, R, E> for P
1187 where
1188     P: Parser<Recoverable<I, R>, O, E>,
1189     I: Stream,
1190     I: StreamIsPartial,
1191     R: FromRecoverableError<Recoverable<I, R>, E>,
1192     R: crate::lib::std::fmt::Debug,
1193     E: FromRecoverableError<Recoverable<I, R>, E>,
1194     E: ParserError<Recoverable<I, R>>,
1195     E: crate::lib::std::fmt::Debug,
1196 {
recoverable_parse(&mut self, input: I) -> (I, Option<O>, Vec<R>)1197     fn recoverable_parse(&mut self, input: I) -> (I, Option<O>, Vec<R>) {
1198         debug_assert!(
1199             !I::is_partial_supported(),
1200             "partial streams need to handle `ErrMode::Incomplete`"
1201         );
1202 
1203         let start = input.checkpoint();
1204         let mut input = Recoverable::new(input);
1205         let start_token = input.checkpoint();
1206         let result = (
1207             self.by_ref(),
1208             crate::combinator::eof.resume_after(crate::token::rest.void()),
1209         )
1210             .parse_next(&mut input);
1211 
1212         let (o, err) = match result {
1213             Ok((o, _)) => (Some(o), None),
1214             Err(err) => {
1215                 let err = err
1216                     .into_inner()
1217                     .expect("complete parsers should not report `ErrMode::Incomplete(_)`");
1218                 let err_start = input.checkpoint();
1219                 let err = R::from_recoverable_error(&start_token, &err_start, &input, err);
1220                 (None, Some(err))
1221             }
1222         };
1223 
1224         let (mut input, mut errs) = input.into_parts();
1225         input.reset(&start);
1226         if let Some(err) = err {
1227             errs.push(err);
1228         }
1229 
1230         (input, o, errs)
1231     }
1232 }
1233 
1234 impl_parser_for_tuples!(
1235   P1 O1,
1236   P2 O2,
1237   P3 O3,
1238   P4 O4,
1239   P5 O5,
1240   P6 O6,
1241   P7 O7,
1242   P8 O8,
1243   P9 O9,
1244   P10 O10,
1245   P11 O11,
1246   P12 O12,
1247   P13 O13,
1248   P14 O14,
1249   P15 O15,
1250   P16 O16,
1251   P17 O17,
1252   P18 O18,
1253   P19 O19,
1254   P20 O20,
1255   P21 O21
1256 );
1257 
1258 #[cfg(feature = "alloc")]
1259 use crate::lib::std::boxed::Box;
1260 
1261 #[cfg(feature = "alloc")]
1262 impl<I, O, E> Parser<I, O, E> for Box<dyn Parser<I, O, E> + '_> {
1263     #[inline(always)]
parse_next(&mut self, i: &mut I) -> PResult<O, E>1264     fn parse_next(&mut self, i: &mut I) -> PResult<O, E> {
1265         (**self).parse_next(i)
1266     }
1267 }
1268 
1269 /// Deprecated
1270 #[inline(always)]
1271 #[deprecated(since = "0.6.23")]
1272 #[allow(deprecated)]
unpeek<'a, I, O, E>( mut peek: impl FnMut(I) -> crate::error::IResult<I, O, E> + 'a, ) -> impl FnMut(&mut I) -> PResult<O, E> where I: Clone,1273 pub fn unpeek<'a, I, O, E>(
1274     mut peek: impl FnMut(I) -> crate::error::IResult<I, O, E> + 'a,
1275 ) -> impl FnMut(&mut I) -> PResult<O, E>
1276 where
1277     I: Clone,
1278 {
1279     move |input| match peek((*input).clone()) {
1280         Ok((i, o)) => {
1281             *input = i;
1282             Ok(o)
1283         }
1284         Err(err) => Err(err),
1285     }
1286 }
1287 
1288 #[cfg(test)]
1289 mod tests {
1290     use super::*;
1291     use crate::binary::be_u16;
1292     use crate::error::ErrMode;
1293     use crate::error::ErrorKind;
1294     use crate::error::IResult;
1295     use crate::error::InputError;
1296     use crate::error::Needed;
1297     use crate::token::take;
1298     use crate::Partial;
1299 
1300     #[doc(hidden)]
1301     #[macro_export]
1302     macro_rules! assert_size (
1303     ($t:ty, $sz:expr) => (
1304       assert!($crate::lib::std::mem::size_of::<$t>() <= $sz, "{} <= {} failed", $crate::lib::std::mem::size_of::<$t>(), $sz);
1305     );
1306   );
1307 
1308     #[test]
1309     #[cfg(target_pointer_width = "64")]
size_test()1310     fn size_test() {
1311         assert_size!(IResult<&[u8], &[u8], (&[u8], u32)>, 40);
1312         assert_size!(IResult<&str, &str, u32>, 40);
1313         assert_size!(Needed, 8);
1314         assert_size!(ErrMode<u32>, 16);
1315         assert_size!(ErrorKind, 1);
1316     }
1317 
1318     #[test]
err_map_test()1319     fn err_map_test() {
1320         let e = ErrMode::Backtrack(1);
1321         assert_eq!(e.map(|v| v + 1), ErrMode::Backtrack(2));
1322     }
1323 
1324     #[test]
single_element_tuples()1325     fn single_element_tuples() {
1326         use crate::ascii::alpha1;
1327         use crate::error::ErrorKind;
1328 
1329         let mut parser = (alpha1,);
1330         assert_eq!(parser.parse_peek("abc123def"), Ok(("123def", ("abc",))));
1331         assert_eq!(
1332             parser.parse_peek("123def"),
1333             Err(ErrMode::Backtrack(InputError::new(
1334                 "123def",
1335                 ErrorKind::Slice
1336             )))
1337         );
1338     }
1339 
1340     #[test]
tuple_test()1341     fn tuple_test() {
1342         #[allow(clippy::type_complexity)]
1343         fn tuple_3(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, (u16, &[u8], &[u8])> {
1344             (be_u16, take(3u8), "fg").parse_peek(i)
1345         }
1346 
1347         assert_eq!(
1348             tuple_3(Partial::new(&b"abcdefgh"[..])),
1349             Ok((
1350                 Partial::new(&b"h"[..]),
1351                 (0x6162u16, &b"cde"[..], &b"fg"[..])
1352             ))
1353         );
1354         assert_eq!(
1355             tuple_3(Partial::new(&b"abcd"[..])),
1356             Err(ErrMode::Incomplete(Needed::new(1)))
1357         );
1358         assert_eq!(
1359             tuple_3(Partial::new(&b"abcde"[..])),
1360             Err(ErrMode::Incomplete(Needed::new(2)))
1361         );
1362         assert_eq!(
1363             tuple_3(Partial::new(&b"abcdejk"[..])),
1364             Err(ErrMode::Backtrack(error_position!(
1365                 &Partial::new(&b"jk"[..]),
1366                 ErrorKind::Tag
1367             )))
1368         );
1369     }
1370 
1371     #[test]
unit_type()1372     fn unit_type() {
1373         fn parser(i: &mut &str) -> PResult<()> {
1374             ().parse_next(i)
1375         }
1376         assert_eq!(parser.parse_peek("abxsbsh"), Ok(("abxsbsh", ())));
1377         assert_eq!(parser.parse_peek("sdfjakdsas"), Ok(("sdfjakdsas", ())));
1378         assert_eq!(parser.parse_peek(""), Ok(("", ())));
1379     }
1380 }
1381