nom_supreme/
parser_ext.rs

1//! Extensions to the nom [`Parser`][nom::Parser] trait which add postfix
2//! versions of the common combinators. See [`ParserExt`] for details.
3
4use core::{marker::PhantomData, ops::RangeTo, str::FromStr};
5
6use nom::{
7    error::{ErrorKind as NomErrorKind, FromExternalError, ParseError},
8    Err as NomErr, InputLength, Offset, Parser, Slice,
9};
10
11use crate::context::ContextError;
12
13/// No-op function that typechecks that its argument is a parser. Used to
14/// ensure there are no accidentally missing type bounds on the `ParserExt`
15/// methods
16#[inline(always)]
17fn must_be_a_parser<I, O, E, P: Parser<I, O, E>>(parser: P) -> P {
18    parser
19}
20
21/// Additional postfix parser combinators, as a complement to [`Parser`].
22/// Mostly these are postfix versions of the combinators in [`nom::combinator`]
23/// and [`nom::sequence`], with some additional combinators original to
24/// `nom-supreme`.
25///
26/// Compatibility note: it is expected that eventually many of these postfix
27/// methods will eventually be added directly to the [`Parser`] trait. It will
28/// therefore *not* be considered a compatibility break to remove those methods
29/// from [`ParserExt`], *if* they have the same name and signature.
30pub trait ParserExt<I, O, E>: Parser<I, O, E> + Sized {
31    /// Borrow a parser. This allows building parser combinators while still
32    /// retaining ownership of the original parser. This is necessary because
33    /// `impl<T: Parser> Parser for &mut T` is impossible due to conflicts
34    /// with `impl<T: FnMut> Parser for T`.
35    ///
36    /// # Example
37    ///
38    /// ```rust
39    /// # use nom::{Err, Parser};
40    /// # use nom::error::{Error, ErrorKind};
41    /// use nom_supreme::parser_ext::ParserExt;
42    /// use nom_supreme::tag::complete::tag;
43    ///
44    /// let mut parser = tag("Hello");
45    ///
46    /// let mut subparser = parser.by_ref().terminated(tag(", World"));
47    ///
48    /// assert_eq!(subparser.parse("Hello, World!"), Ok(("!", "Hello")));
49    /// assert_eq!(
50    ///     subparser.parse("Hello"),
51    ///     Err(Err::Error(Error{input: "", code: ErrorKind::Tag}))
52    /// );
53    ///
54    /// // We still have ownership of the original parser
55    ///
56    /// assert_eq!(parser.parse("Hello, World!"), Ok((", World!", "Hello")));
57    /// assert_eq!(parser.parse("Hello"), Ok(("", "Hello")));
58    /// ```
59    #[inline]
60    #[must_use = "Parsers do nothing unless used"]
61    fn by_ref(&mut self) -> RefParser<Self> {
62        must_be_a_parser(RefParser { parser: self })
63    }
64
65    /// Create a parser that must consume all of the input, or else return an
66    /// error.
67    ///
68    /// # Example
69    ///
70    /// ```rust
71    /// # use nom::{Err, Parser};
72    /// # use nom::error::{Error, ErrorKind};
73    /// use nom_supreme::parser_ext::ParserExt;
74    /// use nom_supreme::tag::complete::tag;
75    ///
76    /// let mut parser = tag("Hello").all_consuming();
77    ///
78    /// assert_eq!(parser.parse("Hello"), Ok(("", "Hello")));
79    /// assert_eq!(
80    ///     parser.parse("World"),
81    ///     Err(Err::Error(Error{input: "World", code: ErrorKind::Tag}))
82    /// );
83    /// assert_eq!(
84    ///     parser.parse("Hello World"),
85    ///     Err(Err::Error(Error{input: " World", code: ErrorKind::Eof}))
86    /// );
87    /// ```
88    #[inline]
89    #[must_use = "Parsers do nothing unless used"]
90    fn all_consuming(self) -> AllConsuming<Self>
91    where
92        I: InputLength,
93        E: ParseError<I>,
94    {
95        must_be_a_parser(AllConsuming { parser: self })
96    }
97
98    /// Create a parser that transforms `Incomplete` into `Error`.
99    ///
100    /// # Example
101    ///
102    /// ```rust
103    /// # use nom::{Err, Parser};
104    /// # use nom::error::{Error, ErrorKind};
105    /// use nom_supreme::parser_ext::ParserExt;
106    /// use nom_supreme::tag::streaming::tag;
107    ///
108    /// let mut parser = tag("Hello").complete();
109    ///
110    /// assert_eq!(parser.parse("Hello"), Ok(("", "Hello")));
111    /// assert_eq!(
112    ///     parser.parse("World"),
113    ///     Err(Err::Error(Error{input: "World", code: ErrorKind::Tag}))
114    /// );
115    /// assert_eq!(
116    ///     parser.parse("Hel"),
117    ///     Err(Err::Error(Error{input: "Hel", code: ErrorKind::Complete}))
118    /// );
119    /// ```
120    #[inline]
121    #[must_use = "Parsers do nothing unless used"]
122    fn complete(self) -> Complete<Self>
123    where
124        I: Clone,
125        E: ParseError<I>,
126    {
127        must_be_a_parser(Complete { parser: self })
128    }
129
130    /**
131    Create a parser that transforms `Error` into `Failure`. This will
132    end the parse immediately, even if there are other branches that
133    could occur.
134
135    # Example
136
137    ```rust
138    use cool_asserts::assert_matches;
139    # use nom::{Err, Parser};
140    # use nom::error::{Error, ErrorKind};
141    use nom::branch::alt;
142    use nom::character::complete::char;
143    use nom_supreme::parser_ext::ParserExt;
144    use nom_supreme::tag::complete::tag;
145    use nom_supreme::error::{ErrorTree, BaseErrorKind, Expectation};
146
147    let mut parser = alt((
148        tag("Hello").terminated(char(']')).cut().preceded_by(char('[')),
149        tag("World").terminated(char(')')).cut().preceded_by(char('(')),
150    ));
151
152    assert_matches!(parser.parse("[Hello]"), Ok(("", "Hello")));
153    assert_matches!(parser.parse("(World)"), Ok(("", "World")));
154
155    let branches = assert_matches!(
156        parser.parse("ABC"),
157        Err(Err::Error(ErrorTree::Alt(branches))) => branches
158    );
159
160    assert_matches!(
161        branches.as_slice(),
162        [
163            ErrorTree::Base {
164                kind: BaseErrorKind::Expected(Expectation::Char('[')),
165                location: "ABC",
166            },
167            ErrorTree::Base {
168                kind: BaseErrorKind::Expected(Expectation::Char('(')),
169                location: "ABC",
170            },
171        ]
172    );
173
174    // Notice in this example that there's no error for [Hello]. The cut after
175    // [ prevented the other branch from being attempted, and prevented earlier
176    // errors from being retained
177    assert_matches!(
178        parser.parse("(Hello)"),
179        Err(Err::Failure(ErrorTree::Base {
180            kind: BaseErrorKind::Expected(Expectation::Tag("World")),
181            location: "Hello)",
182        }))
183    );
184    ```
185    */
186    #[inline]
187    #[must_use = "Parsers do nothing unless used"]
188    fn cut(self) -> Cut<Self> {
189        must_be_a_parser(Cut { parser: self })
190    }
191
192    /// Create a parser that applies a mapping function `func` to the output
193    /// of the subparser. Any errors from `func` will be transformed into
194    /// parse errors via [`FromExternalError`].
195    ///
196    /// # Example
197    ///
198    /// ```rust
199    /// # use nom::{Err, Parser};
200    /// # use nom::error::{Error, ErrorKind};
201    /// use nom::character::complete::alphanumeric1;
202    /// use nom_supreme::parser_ext::ParserExt;
203    ///
204    /// let mut parser = alphanumeric1.map_res(|s: &str| s.parse());
205    ///
206    /// assert_eq!(parser.parse("10 abc"), Ok((" abc", 10)));
207    /// assert_eq!(
208    ///     parser.parse("<===>"),
209    ///     Err(Err::Error(Error{input: "<===>", code: ErrorKind::AlphaNumeric})),
210    /// );
211    /// assert_eq!(
212    ///     parser.parse("abc abc"),
213    ///     Err(Err::Error(Error{input: "abc abc", code: ErrorKind::MapRes})),
214    /// );
215    /// ```
216    #[inline]
217    #[must_use = "Parsers do nothing unless used"]
218    fn map_res<F, O2, E2>(self, func: F) -> MapRes<Self, F, O, E2>
219    where
220        F: FnMut(O) -> Result<O2, E2>,
221        E: FromExternalError<I, E2>,
222        I: Clone,
223    {
224        must_be_a_parser(MapRes {
225            parser: self,
226            func,
227            phantom: PhantomData,
228        })
229    }
230
231    /// Create a parser that applies a mapping function `func` to the output
232    /// of the subparser. Any errors from `func` will be transformed into
233    /// parse failures via [`FromExternalError`]. This will
234    /// end the parse immediately, even if there are other branches that
235    /// could occur.
236    ///
237    /// # Example
238    ///
239    /// ```rust
240    /// # use nom::{Err, Parser};
241    /// # use nom::error::{Error, ErrorKind};
242    /// use nom::character::complete::alphanumeric1;
243    /// use nom_supreme::parser_ext::ParserExt;
244    ///
245    /// let mut parser = alphanumeric1.map_res_cut(|s: &str| s.parse());
246    ///
247    /// assert_eq!(parser.parse("10 abc"), Ok((" abc", 10)));
248    /// assert_eq!(
249    ///     parser.parse("<===>"),
250    ///     Err(Err::Error(Error{input: "<===>", code: ErrorKind::AlphaNumeric})),
251    /// );
252    /// assert_eq!(
253    ///     parser.parse("abc abc"),
254    ///     Err(Err::Failure(Error{input: "abc abc", code: ErrorKind::MapRes})),
255    /// );
256    /// ```
257    #[inline]
258    #[must_use = "Parsers do nothing unless used"]
259    fn map_res_cut<F, O2, E2>(self, func: F) -> MapResCut<Self, F, O, E2>
260    where
261        F: FnMut(O) -> Result<O2, E2>,
262        E: FromExternalError<I, E2>,
263        I: Clone,
264    {
265        must_be_a_parser(MapResCut {
266            parser: self,
267            func,
268            phantom: PhantomData,
269        })
270    }
271
272    /// Make this parser optional; if it fails to parse, instead it returns
273    /// `None` with the input in the original position.
274    ///
275    /// # Example
276    ///
277    /// ```rust
278    /// # use nom::{Err, Parser, IResult};
279    /// # use nom::error::{Error, ErrorKind};
280    /// use nom_supreme::parser_ext::ParserExt;
281    /// use nom_supreme::tag::complete::tag;
282    ///
283    /// fn parser(input: &str) -> IResult<&str, Option<&str>> {
284    ///     tag("Hello").opt().parse(input)
285    /// }
286    ///
287    /// assert_eq!(parser.parse("Hello, World"), Ok((", World", Some("Hello"))));
288    /// assert_eq!(parser.parse("World"), Ok(("World", None)));
289    ///
290    /// let mut parser = tag("Hello").cut().opt();
291    /// assert_eq!(
292    ///     parser.parse("World"),
293    ///     Err(Err::Failure(Error{input: "World", code: ErrorKind::Tag}))
294    /// )
295    /// ```
296    #[inline]
297    #[must_use = "Parsers do nothing unless used"]
298    fn opt(self) -> Optional<Self>
299    where
300        I: Clone,
301    {
302        must_be_a_parser(Optional { parser: self })
303    }
304
305    /// Replace this parser's output with the entire input that was consumed
306    /// by the parser.
307    ///
308    /// # Example
309    ///
310    /// ```rust
311    /// # use nom::{Err, Parser};
312    /// # use nom::error::{Error, ErrorKind};
313    /// use nom::character::complete::space1;
314    /// use nom_supreme::parser_ext::ParserExt;
315    /// use nom_supreme::tag::complete::tag;
316    ///
317    /// let mut parser = tag("Hello").delimited_by(space1).recognize();
318    ///
319    /// assert_eq!(parser.parse("   Hello   World!"), Ok(("World!", "   Hello   ")));
320    /// assert_eq!(
321    ///     parser.parse("Hello"),
322    ///     Err(Err::Error(Error{input: "Hello", code: ErrorKind::Space}))
323    /// )
324    /// ```
325    #[inline]
326    #[must_use = "Parsers do nothing unless used"]
327    fn recognize(self) -> Recognize<Self, O>
328    where
329        I: Clone + Slice<RangeTo<usize>> + Offset,
330    {
331        must_be_a_parser(Recognize {
332            parser: self.with_recognized(),
333            phantom: PhantomData,
334        })
335    }
336
337    /// Return the parsed value, but also return the entire input that was
338    /// consumed by the parse
339    ///
340    /// # Example
341    ///
342    /// ```rust
343    /// # use nom::{Err, Parser};
344    /// # use nom::error::{Error, ErrorKind};
345    /// use nom::character::complete::space1;
346    /// use nom_supreme::parser_ext::ParserExt;
347    /// use nom_supreme::tag::complete::tag;
348    ///
349    /// let mut parser = tag("Hello").delimited_by(space1).with_recognized();
350    ///
351    /// assert_eq!(parser.parse("   Hello   World!"), Ok(("World!", ("   Hello   ", "Hello"))));
352    /// assert_eq!(
353    ///     parser.parse("Hello"),
354    ///     Err(Err::Error(Error{input: "Hello", code: ErrorKind::Space}))
355    /// )
356    /// ```
357    #[inline]
358    #[must_use = "Parsers do nothing unless used"]
359    fn with_recognized(self) -> WithRecognized<Self>
360    where
361        I: Clone + Slice<RangeTo<usize>> + Offset,
362    {
363        must_be_a_parser(WithRecognized { parser: self })
364    }
365
366    /// Replace this parser's output with a clone of `value` every time it
367    /// finishes successfully.
368    ///
369    /// # Example
370    ///
371    /// ```rust
372    /// use cool_asserts::assert_matches;
373    /// # use nom::{Err, Parser};
374    /// # use nom::error::{Error, ErrorKind};
375    /// use nom::branch::alt;
376    /// use nom_supreme::parser_ext::ParserExt;
377    /// use nom_supreme::tag::complete::tag;
378    /// use nom_supreme::error::{ErrorTree, BaseErrorKind, Expectation};
379    ///
380    ///
381    /// let mut parser = alt((
382    ///     tag("true").value(true),
383    ///     tag("false").value(false),
384    /// ));
385    ///
386    /// assert_eq!(parser.parse("true abc").unwrap(), (" abc", true));
387    /// assert_eq!(parser.parse("false abc").unwrap(), (" abc", false));
388    ///
389    /// // ErrorTree gives much better error reports for alt and tag.
390    /// let choices = assert_matches!(
391    ///     parser.parse("null"),
392    ///     Err(Err::Error(ErrorTree::Alt(choices))) => choices
393    /// );
394    ///
395    /// assert_matches!(
396    ///     choices.as_slice(),
397    ///     [
398    ///         ErrorTree::Base {
399    ///             kind: BaseErrorKind::Expected(Expectation::Tag("true")),
400    ///             location: "null",
401    ///         },
402    ///         ErrorTree::Base {
403    ///             kind: BaseErrorKind::Expected(Expectation::Tag("false")),
404    ///             location: "null",
405    ///         },
406    ///     ]
407    /// )
408    /// ```
409    #[inline]
410    #[must_use = "Parsers do nothing unless used"]
411    fn value<T: Clone>(self, value: T) -> Value<T, Self, O> {
412        must_be_a_parser(Value {
413            parser: self,
414            value,
415            phantom: PhantomData,
416        })
417    }
418
419    /// Require the output of this parser to pass a verifier function, or
420    /// else return a parse error.
421    ///
422    /// ```rust
423    /// # use nom::{Err, Parser};
424    /// # use nom::error::{Error, ErrorKind};
425    /// use nom::character::complete::alpha1;
426    /// use nom_supreme::parser_ext::ParserExt;
427    ///
428    /// let mut parser = alpha1.verify(|s: &&str| s.len() == 5);
429    ///
430    /// assert_eq!(parser.parse("Hello"), Ok(("", "Hello")));
431    /// assert_eq!(parser.parse("Hello, World"), Ok((", World", "Hello")));
432    /// assert_eq!(
433    ///     parser.parse("abc"),
434    ///     Err(Err::Error(Error{input: "abc", code: ErrorKind::Verify}))
435    /// );
436    /// assert_eq!(
437    ///     parser.parse("abcabcabc"),
438    ///     Err(Err::Error(Error{input: "abcabcabc", code: ErrorKind::Verify}))
439    /// );
440    /// assert_eq!(
441    ///     parser.parse("123"),
442    ///     Err(Err::Error(Error{input: "123", code: ErrorKind::Alpha}))
443    /// );
444    /// ```
445    #[inline]
446    #[must_use = "Parsers do nothing unless used"]
447    fn verify<F>(self, verifier: F) -> Verify<Self, F>
448    where
449        F: Fn(&O) -> bool,
450        I: Clone,
451        E: ParseError<I>,
452    {
453        must_be_a_parser(Verify {
454            parser: self,
455            verifier,
456        })
457    }
458
459    /// Add some context to the parser. This context will be added to any
460    /// errors that are returned from the parser via [`ContextError`].
461    ///
462    /// # Example
463    ///
464    /// ```rust
465    /// # use nom::{Err, Parser};
466    /// # use nom::error::{VerboseError, ErrorKind, VerboseErrorKind};
467    /// use nom::sequence::separated_pair;
468    /// use nom::character::complete::space1;
469    /// use nom_supreme::parser_ext::ParserExt;
470    /// use nom_supreme::tag::complete::tag;
471    ///
472    /// let mut parser = separated_pair(
473    ///     tag("Hello").context("hello"),
474    ///     space1,
475    ///     tag("World").context("world"),
476    /// )
477    /// .context("hello world");
478    ///
479    /// assert_eq!(parser.parse("Hello World"), Ok(("", ("Hello", "World"))));
480    /// assert_eq!(
481    ///     parser.parse("Hel"),
482    ///     Err(Err::Error(VerboseError {errors: vec![
483    ///         ("Hel", VerboseErrorKind::Nom(ErrorKind::Tag)),
484    ///         ("Hel", VerboseErrorKind::Context("hello")),
485    ///         ("Hel", VerboseErrorKind::Context("hello world")),
486    ///     ]}))
487    /// );
488    /// assert_eq!(
489    ///     parser.parse("Hello"),
490    ///     Err(Err::Error(VerboseError {errors: vec![
491    ///         ("", VerboseErrorKind::Nom(ErrorKind::Space)),
492    ///         ("Hello", VerboseErrorKind::Context("hello world")),
493    ///     ]}))
494    /// );
495    /// assert_eq!(
496    ///     parser.parse("Hello Wor"),
497    ///     Err(Err::Error(VerboseError {errors: vec![
498    ///         ("Wor", VerboseErrorKind::Nom(ErrorKind::Tag)),
499    ///         ("Wor", VerboseErrorKind::Context("world")),
500    ///         ("Hello Wor", VerboseErrorKind::Context("hello world")),
501    ///     ]}))
502    /// );
503    /// ```
504    #[inline]
505    #[must_use = "Parsers do nothing unless used"]
506    fn context<C>(self, context: C) -> Context<Self, C>
507    where
508        E: ContextError<I, C>,
509        I: Clone,
510        C: Clone,
511    {
512        must_be_a_parser(Context {
513            context,
514            parser: self,
515        })
516    }
517
518    /// Add a terminator parser. The terminator will run after this parser,
519    /// returning any errors, but its output will otherwise be discarded.
520    ///
521    /// # Example
522    ///
523    /// ```rust
524    /// # use nom::{Err, Parser};
525    /// # use nom::error::{Error, ErrorKind};
526    /// use nom_supreme::parser_ext::ParserExt;
527    /// use nom_supreme::tag::complete::tag;
528    ///
529    /// let mut parser = tag("Hello").terminated(tag(" World"));
530    ///
531    /// assert_eq!(parser.parse("Hello World!"), Ok(("!", "Hello")));
532    /// assert_eq!(
533    ///     parser.parse("Hello"),
534    ///     Err(Err::Error(Error{input: "", code: ErrorKind::Tag}))
535    /// );
536    /// ```
537    #[inline]
538    #[must_use = "Parsers do nothing unless used"]
539    fn terminated<F, O2>(self, terminator: F) -> Terminated<Self, F, O2>
540    where
541        F: Parser<I, O2, E>,
542    {
543        must_be_a_parser(Terminated {
544            parser: self,
545            terminator,
546            phantom: PhantomData,
547        })
548    }
549
550    /// Make this parser precede another one. The successor parser will run
551    /// after this one succeeds, and the successor's output will be returned.
552    ///
553    /// # Example
554    ///
555    /// ```rust
556    /// # use nom::{Err, Parser};
557    /// # use nom::error::{Error, ErrorKind};
558    /// use nom::character::complete::digit1;
559    /// use nom_supreme::parser_ext::ParserExt;
560    /// use nom_supreme::tag::complete::tag;
561    ///
562    /// let mut parser = tag("Value: ").precedes(digit1);
563    ///
564    /// assert_eq!(parser.parse("Value: 25;"), Ok((";", "25")));
565    /// assert_eq!(
566    ///     parser.parse("Value: "),
567    ///     Err(Err::Error(Error{input: "", code: ErrorKind::Digit}))
568    /// );
569    /// assert_eq!(
570    ///     parser.parse("25"),
571    ///     Err(Err::Error(Error{input: "25", code: ErrorKind::Tag}))
572    /// );
573    /// ```
574    #[inline]
575    #[must_use = "Parsers do nothing unless used"]
576    fn precedes<F, O2>(self, successor: F) -> Preceded<F, Self, O>
577    where
578        F: Parser<I, O2, E>,
579    {
580        must_be_a_parser(successor.preceded_by(self))
581    }
582
583    /// Make this parser preceded by another one. The `prefix` will run first,
584    /// and if it succeeds, its output will be discard and this parser will
585    /// be run.
586    ///
587    /// # Example
588    ///
589    /// ```rust
590    /// # use nom::{Err, Parser};
591    /// # use nom::error::{Error, ErrorKind};
592    /// use nom::character::complete::digit1;
593    /// use nom_supreme::parser_ext::ParserExt;
594    /// use nom_supreme::tag::complete::tag;
595    ///
596    /// let mut parser = digit1.preceded_by(tag("Value: "));
597    ///
598    /// assert_eq!(parser.parse("Value: 25;"), Ok((";", "25")));
599    /// assert_eq!(
600    ///     parser.parse("Value: "),
601    ///     Err(Err::Error(Error{input: "", code: ErrorKind::Digit}))
602    /// );
603    /// assert_eq!(
604    ///     parser.parse("25"),
605    ///     Err(Err::Error(Error{input: "25", code: ErrorKind::Tag}))
606    /// );
607    /// ```
608    #[inline]
609    #[must_use = "Parsers do nothing unless used"]
610    fn preceded_by<F, O2>(self, prefix: F) -> Preceded<Self, F, O2>
611    where
612        F: Parser<I, O2, E>,
613    {
614        must_be_a_parser(Preceded {
615            parser: self,
616            prefix,
617            phantom: PhantomData,
618        })
619    }
620
621    /**
622    Make this parser optionally precede by another one. `self` will
623    run first, and then the `successor` will run even if `self` returns an
624    error. Both outputs will be returned. This is functionally equivalent
625    to `self.opt().and(successor)`, but it has the added benefit that if
626    *both* parsers return an error, the error from the `prefix` will be
627    retained, rather than discarded.
628
629    ```rust
630    use cool_asserts::assert_matches;
631    # use nom::{Err, Parser, IResult};
632    use nom::character::complete::{digit1, char};
633    use nom_supreme::parser_ext::ParserExt;
634    use nom_supreme::error::{ErrorTree, BaseErrorKind, Expectation};
635
636    let mut parser = char('-').or(char('+')).opt_precedes(digit1);
637
638    assert_matches!(parser.parse("123"), Ok(("", (None, "123"))));
639    assert_matches!(parser.parse("-123"), Ok(("", (Some('-'), "123"))));
640
641    let choices = assert_matches!(
642        parser.parse("abc"),
643        Err(Err::Error(ErrorTree::Alt(choices))) => choices,
644    );
645
646    assert_matches!(choices.as_slice(), [
647        ErrorTree::Base {
648            location: "abc",
649            kind: BaseErrorKind::Expected(Expectation::Char('-'))
650        },
651        ErrorTree::Base {
652            location: "abc",
653            kind: BaseErrorKind::Expected(Expectation::Char('+'))
654        },
655        ErrorTree::Base {
656            location: "abc",
657            kind: BaseErrorKind::Expected(Expectation::Digit)
658        },
659    ]);
660    ```
661    */
662    fn opt_precedes<F, O2>(self, successor: F) -> OptionalPreceded<Self, F>
663    where
664        E: ParseError<I>,
665        I: Clone,
666        F: Parser<I, O2, E>,
667    {
668        must_be_a_parser(OptionalPreceded {
669            prefix: self,
670            parser: successor,
671        })
672    }
673
674    /**
675    Make this parser optionally preceded by another one. The `prefix` will
676    run first, and then this parser will run even if the `prefix` returned
677    an error. Both outputs will be returned. This is functionally equivalent
678    to `prefix.opt().and(self)`, but it has the added benefit that if *both*
679    parsers return an error, the error from the `prefix` will be retained,
680    rather than discarded.
681
682    ```rust
683    use cool_asserts::assert_matches;
684    # use nom::{Err, Parser, IResult};
685    use nom::character::complete::{digit1, char};
686    use nom_supreme::parser_ext::ParserExt;
687    use nom_supreme::error::{ErrorTree, BaseErrorKind, Expectation};
688
689    let mut parser = digit1.opt_preceded_by(char('-'));
690
691    assert_matches!(parser.parse("123"), Ok(("", (None, "123"))));
692    assert_matches!(parser.parse("-123"), Ok(("", (Some('-'), "123"))));
693
694    let choices = assert_matches!(
695        parser.parse("abc"),
696        Err(Err::Error(ErrorTree::Alt(choices))) => choices,
697    );
698
699    assert_matches!(choices.as_slice(), [
700        ErrorTree::Base {
701            location: "abc",
702            kind: BaseErrorKind::Expected(Expectation::Char('-'))
703        },
704        ErrorTree::Base {
705            location: "abc",
706            kind: BaseErrorKind::Expected(Expectation::Digit)
707        },
708    ]);
709    ```
710    */
711    fn opt_preceded_by<F, O2>(self, prefix: F) -> OptionalPreceded<F, Self>
712    where
713        E: ParseError<I>,
714        I: Clone,
715        F: Parser<I, O2, E>,
716    {
717        must_be_a_parser(OptionalPreceded {
718            parser: self,
719            prefix,
720        })
721    }
722
723    /// Make this parser delimited, requiring a `delimiter` as both a prefix and
724    /// a suffix. The output of the delimiters is discarded.
725    ///
726    /// # Example
727    ///
728    /// ```rust
729    /// # use nom::{Err, Parser};
730    /// # use nom::error::{Error, ErrorKind};
731    /// use nom::character::complete::{char, digit1};
732    /// use nom_supreme::parser_ext::ParserExt;
733    ///
734    /// let mut parser = digit1.delimited_by(char('\''));
735    ///
736    /// assert_eq!(parser.parse("'123' '456'"), Ok((" '456'", "123")));
737    /// assert_eq!(
738    ///     parser.parse("'' ''"),
739    ///     Err(Err::Error(Error{input: "' ''", code: ErrorKind::Digit}))
740    /// );
741    /// assert_eq!(
742    ///     parser.parse("'123 '"),
743    ///     Err(Err::Error(Error{input: " '", code: ErrorKind::Char}))
744    /// );
745    /// ```
746    #[inline]
747    #[must_use = "Parsers do nothing unless used"]
748    fn delimited_by<D, O2>(self, delimiter: D) -> Delimited<Self, D, O2>
749    where
750        D: Parser<I, O2, E>,
751    {
752        must_be_a_parser(Delimited {
753            parser: self,
754            delimiter,
755            phantom: PhantomData,
756        })
757    }
758
759    /// Make this parser peeking: it runs normally but consumes no input.
760    ///
761    /// # Example
762    ///
763    /// ```rust
764    /// # use nom::{Err, Parser};
765    /// # use nom::error::{Error, ErrorKind};
766    /// use nom_supreme::parser_ext::ParserExt;
767    /// use nom_supreme::tag::complete::tag;
768    ///
769    /// let mut parser = tag("Hello").peek();
770    ///
771    /// assert_eq!(parser.parse("Hello World"), Ok(("Hello World", "Hello")));
772    /// assert_eq!(
773    ///     parser.parse("World"),
774    ///     Err(Err::Error(Error{input: "World", code: ErrorKind::Tag}))
775    /// );
776    /// ```
777    #[inline]
778    #[must_use = "Parsers do nothing unless used"]
779    fn peek(self) -> Peek<Self>
780    where
781        I: Clone,
782    {
783        must_be_a_parser(Peek { parser: self })
784    }
785
786    /// Make this parser a negative lookahead: it will succeed if the subparser
787    /// fails, and fail if the subparser succeeds.
788    ///
789    /// # Example
790    ///
791    /// ```rust
792    /// # use nom::{Err, Parser};
793    /// # use nom::error::{Error, ErrorKind};
794    /// use nom_supreme::parser_ext::ParserExt;
795    /// use nom_supreme::tag::complete::tag;
796    ///
797    /// let mut parser = tag("Hello").not();
798    ///
799    /// assert_eq!(parser.parse("World"), Ok(("World", ())));
800    /// assert_eq!(
801    ///     parser.parse("Hello World"),
802    ///     Err(Err::Error(Error{input: "Hello World", code: ErrorKind::Not})),
803    /// );
804    /// ```
805    #[inline]
806    #[must_use = "Parsers do nothing unless used"]
807    fn not(self) -> Not<Self, O>
808    where
809        I: Clone,
810        E: ParseError<I>,
811    {
812        must_be_a_parser(Not {
813            parser: self,
814            phantom: PhantomData,
815        })
816    }
817
818    /// Create a parser that parses something via [`FromStr`], using this
819    /// parser as a recognizer for the string to pass to
820    /// [`from_str`][FromStr::from_str].
821    ///
822    /// # Example
823    ///
824    /// ```rust
825    /// # use nom::{Err, Parser, IResult};
826    /// # use nom::error::{Error, ErrorKind};
827    /// use nom::character::complete::digit1;
828    /// use nom_supreme::parser_ext::ParserExt;
829    ///
830    /// let mut parser = digit1.parse_from_str();
831    ///
832    /// assert_eq!(parser.parse("123 abc"), Ok((" abc", 123)));
833    /// assert_eq!(
834    ///     parser.parse("abc"),
835    ///     Err(Err::Error(Error{input: "abc", code: ErrorKind::Digit})),
836    /// );
837    /// ```
838    ///
839    /// # Parse error example
840    ///
841    /// If the [`FromStr`] parser fails, the error is recoverable from via
842    /// [`FromExternalError`]. In general, though, it's better practice to
843    /// ensure your recognizer won't allow invalid strings to be forwarded to
844    /// the [`FromStr`] parser
845    ///
846    /// ```rust
847    /// use std::num::ParseIntError;
848    /// use cool_asserts::assert_matches;
849    /// # use nom::{Err, Parser, IResult};
850    /// # use nom::error::{ErrorKind};
851    /// use nom::character::complete::alphanumeric1;
852    /// use nom_supreme::parser_ext::ParserExt;
853    /// use nom_supreme::error::{ErrorTree, BaseErrorKind};
854    ///
855    /// let mut parser = alphanumeric1.parse_from_str();
856    ///
857    /// assert_matches!(parser.parse("123 abc"), Ok((" abc", 123)));
858    /// assert_matches!(
859    ///     parser.parse("abc"),
860    ///     Err(Err::Error(ErrorTree::Base{
861    ///         location: "abc",
862    ///         kind: BaseErrorKind::External(err),
863    ///     })) => {
864    ///         let _err: &ParseIntError = err.downcast_ref().unwrap();
865    ///     },
866    /// );
867    /// ```
868    #[inline]
869    #[must_use = "Parsers do nothing unless used"]
870    fn parse_from_str<'a, T>(self) -> FromStrParser<Self, T>
871    where
872        Self: Parser<I, &'a str, E>,
873        I: Clone,
874        T: FromStr,
875        E: FromExternalError<I, T::Err>,
876    {
877        must_be_a_parser(FromStrParser {
878            parser: self,
879            phantom: PhantomData,
880        })
881    }
882
883    /// Create a parser that parses something via [`FromStr`], using this
884    /// parser as a recognizer for the string to pass to
885    /// [`from_str`][FromStr::from_str]. This parser transforms any errors
886    /// from [`FromStr`] into [`Err::Failure`][NomErr::Failure], which will
887    /// end the overall parse immediately, even if there are other branches
888    /// that could be tried.
889    ///
890    /// # Example
891    ///
892    /// ```rust
893    /// # use nom::{Err, Parser, IResult};
894    /// # use nom::error::{Error, ErrorKind};
895    /// use nom::character::complete::alphanumeric1;
896    /// use nom_supreme::parser_ext::ParserExt;
897    ///
898    /// let mut parser = alphanumeric1.parse_from_str_cut();
899    ///
900    /// assert_eq!(parser.parse("123 abc"), Ok((" abc", 123)));
901    /// assert_eq!(
902    ///     parser.parse("<===>"),
903    ///     Err(Err::Error(Error{input: "<===>", code: ErrorKind::AlphaNumeric})),
904    /// );
905    /// assert_eq!(
906    ///     parser.parse("abc"),
907    ///     Err(Err::Failure(Error{input: "abc", code: ErrorKind::MapRes})),
908    /// );
909    /// ```
910    ///
911    /// # Parse error example
912    ///
913    /// If the [`FromStr`] parser fails, the error is recoverable from via
914    /// [`FromExternalError`]. In general, though, it's better practice to
915    /// ensure your recognizer won't allow invalid strings to be forwarded to
916    /// the [`FromStr`] parser
917    ///
918    /// ```rust
919    /// use std::num::ParseIntError;
920    /// use cool_asserts::assert_matches;
921    /// # use nom::{Err, Parser, IResult};
922    /// # use nom::error::{ErrorKind};
923    /// use nom::character::complete::alphanumeric1;
924    /// use nom_supreme::parser_ext::ParserExt;
925    /// use nom_supreme::error::{ErrorTree, BaseErrorKind};
926    ///
927    /// let mut parser = alphanumeric1.parse_from_str_cut();
928    ///
929    /// assert_matches!(parser.parse("123 abc"), Ok((" abc", 123)));
930    /// assert_matches!(
931    ///     parser.parse("abc"),
932    ///     Err(Err::Failure(ErrorTree::Base{
933    ///         location: "abc",
934    ///         kind: BaseErrorKind::External(err),
935    ///     })) => {
936    ///         let _err: &ParseIntError = err.downcast_ref().unwrap();
937    ///     },
938    /// );
939    /// ```
940    #[inline]
941    #[must_use = "Parsers do nothing unless used"]
942    fn parse_from_str_cut<'a, T>(self) -> FromStrCutParser<Self, T>
943    where
944        Self: Parser<I, &'a str, E>,
945        I: Clone,
946        T: FromStr,
947        E: FromExternalError<I, T::Err>,
948    {
949        must_be_a_parser(FromStrCutParser {
950            parser: self,
951            phantom: PhantomData,
952        })
953    }
954
955    /// Create a parser that parses a fixed-size array by running this parser
956    /// in a loop.
957    ///
958    /// The returned parser implements [`Parser`] generically over any
959    /// `const N: usize`, which means it can be used to parse arrays of any
960    /// length
961    ///
962    /// # Example
963    ///
964    /// ```rust
965    /// use cool_asserts::assert_matches;
966    /// use nom::character::complete::digit1;
967    /// # use nom::{Parser, Err, IResult};
968    /// # use nom::error::{ErrorKind, Error};
969    /// use nom_supreme::ParserExt;
970    /// use nom_supreme::tag::complete::tag;
971    ///
972    /// let mut parser = digit1
973    ///     .terminated(tag(", "))
974    ///     .parse_from_str()
975    ///     .array();
976    ///
977    /// assert_matches!(parser.parse("123, 456, 789, abc"), Ok(("789, abc", [123, 456])));
978    /// assert_matches!(parser.parse("123, 456, 789, abc"), Ok(("abc", [123, 456, 789])));
979    ///
980    /// let res: Result<(&str, [u16; 4]), Err<Error<&str>>> = parser.parse("123, 456, 789, abc");
981    /// assert_matches!(
982    ///     res,
983    ///     Err(Err::Error(Error{input: "abc", code: ErrorKind::Digit}))
984    /// );
985    /// ```
986    ///
987    /// Note that this parser does not attach any additional context to the
988    /// error in the event of a parser; consider using [`context`][Self::context]
989    /// on the item parser or array parser to add additional information about
990    /// where in the input there was a parse failure.
991    #[inline]
992    #[must_use = "Parsers do nothing unless used"]
993    fn array(self) -> ArrayParser<Self> {
994        ArrayParser { parser: self }
995    }
996
997    /// Create a parser that parses a fixed-size array by running this parser
998    /// in a loop, parsing a separator in between each element.
999    ///
1000    /// The returned parser implements [`Parser`] generically over any
1001    /// `const N: usize`, which means it can be used to parse arrays of any
1002    /// length
1003    ///
1004    /// # Example
1005    ///
1006    /// ```rust
1007    /// use std::net::{Ipv4Addr, SocketAddrV4};
1008    /// use cool_asserts::assert_matches;
1009    /// use nom::character::complete::{char, digit1};
1010    /// # use nom::{Parser, Err, IResult};
1011    /// # use nom::error::{ErrorKind, Error};
1012    /// use nom_supreme::ParserExt;
1013    /// use nom_supreme::tag::complete::tag;
1014    ///
1015    /// let mut parser = digit1
1016    ///     .parse_from_str()
1017    ///     .separated_array(char('.'))
1018    ///     .map(Ipv4Addr::from)
1019    ///     .terminated(char(':'))
1020    ///     .and(digit1.parse_from_str())
1021    ///     .map(|(ip, port)| SocketAddrV4::new(ip, port));
1022    ///
1023    /// let (_tail, socket_addr) = parser.parse("192.168.0.1:80").unwrap();
1024    /// assert_eq!(socket_addr.ip().octets(), [192, 168, 0, 1]);
1025    /// assert_eq!(socket_addr.port(), 80);
1026    ///
1027    /// assert_matches!(
1028    ///     parser.parse("192.168.0.abc:80"),
1029    ///     Err(Err::Error(Error{input: "abc:80", code: ErrorKind::Digit})),
1030    /// );
1031    ///
1032    /// assert_matches!(
1033    ///     parser.parse("192.168.0.1"),
1034    ///     Err(Err::Error(Error{input: "", code: ErrorKind::Char})),
1035    /// );
1036    ///
1037    /// assert_matches!(
1038    ///     parser.parse("192.168.0.1000:80"),
1039    ///     Err(Err::Error(Error{input: "1000:80", code: ErrorKind::MapRes})),
1040    /// );
1041    ///
1042    /// assert_matches!(
1043    ///     parser.parse("192.168.10abc"),
1044    ///     Err(Err::Error(Error{input: "abc", code: ErrorKind::Char})),
1045    /// );
1046    /// ```
1047    ///
1048    /// Note that this parser does not attach any additional context to the
1049    /// error in the event of a parser; consider using [`context`][Self::context]
1050    /// on the item, separator, or array parsers to add additional information
1051    /// about where in the input there was a parse failure.
1052    #[inline]
1053    #[must_use = "Parsers do nothing unless used"]
1054    fn separated_array<F, O2>(self, separator: F) -> SeparatedArrayParser<Self, F, O2>
1055    where
1056        F: Parser<I, O2, E>,
1057    {
1058        SeparatedArrayParser {
1059            parser: self,
1060            separator,
1061            phantom: PhantomData,
1062        }
1063    }
1064}
1065
1066impl<I, O, E, P> ParserExt<I, O, E> for P where P: Parser<I, O, E> {}
1067
1068/// Parser wrapping a mutable reference to a subparser.
1069#[derive(Debug)]
1070pub struct RefParser<'a, P> {
1071    parser: &'a mut P,
1072}
1073
1074impl<'a, I, O, E, P> Parser<I, O, E> for RefParser<'a, P>
1075where
1076    P: Parser<I, O, E>,
1077{
1078    #[inline]
1079    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1080        self.parser.parse(input)
1081    }
1082}
1083
1084/// Parser which returns an error if the subparser didn't consume the whole
1085/// input.
1086#[derive(Debug, Clone, Copy)]
1087pub struct AllConsuming<P> {
1088    parser: P,
1089}
1090
1091impl<I, O, E, P> Parser<I, O, E> for AllConsuming<P>
1092where
1093    P: Parser<I, O, E>,
1094    E: ParseError<I>,
1095    I: InputLength,
1096{
1097    #[inline]
1098    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1099        let (tail, value) = self.parser.parse(input)?;
1100
1101        if tail.input_len() > 0 {
1102            Err(NomErr::Error(E::from_error_kind(tail, NomErrorKind::Eof)))
1103        } else {
1104            Ok((tail, value))
1105        }
1106    }
1107}
1108
1109/// Parser which returns an error if the subparser returned
1110/// [`Incomplete`][nom::Err::Incomplete].
1111#[derive(Debug, Clone, Copy)]
1112pub struct Complete<P> {
1113    parser: P,
1114}
1115
1116impl<I, O, E, P> Parser<I, O, E> for Complete<P>
1117where
1118    P: Parser<I, O, E>,
1119    E: ParseError<I>,
1120    I: Clone,
1121{
1122    #[inline]
1123    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1124        self.parser
1125            .parse(input.clone())
1126            .map_err(move |err| match err {
1127                NomErr::Incomplete(..) => {
1128                    // TODO: should this error be reported at the very end
1129                    // of the input? Since the error occurred at the eof?
1130                    NomErr::Error(E::from_error_kind(input, NomErrorKind::Complete))
1131                }
1132                err => err,
1133            })
1134    }
1135}
1136
1137/// Parser which returns a [`Failure`][nom::Err::Failure] if the subparser
1138/// returned an error. This prevents other branches from being tried.
1139#[derive(Debug, Clone, Copy)]
1140pub struct Cut<P> {
1141    parser: P,
1142}
1143
1144impl<I, O, E, P> Parser<I, O, E> for Cut<P>
1145where
1146    P: Parser<I, O, E>,
1147{
1148    #[inline]
1149    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1150        self.parser.parse(input).map_err(|err| match err {
1151            NomErr::Error(err) => NomErr::Failure(err),
1152            err => err,
1153        })
1154    }
1155}
1156
1157/// Parser which wraps the subparser output in an [`Option`], and returns a
1158/// successful [`None`] output if it fails.
1159#[derive(Debug, Clone, Copy)]
1160pub struct Optional<P> {
1161    parser: P,
1162}
1163
1164impl<I, O, E, P> Parser<I, Option<O>, E> for Optional<P>
1165where
1166    P: Parser<I, O, E>,
1167    I: Clone,
1168{
1169    #[inline]
1170    fn parse(&mut self, input: I) -> nom::IResult<I, Option<O>, E> {
1171        match self.parser.parse(input.clone()) {
1172            Ok((tail, value)) => Ok((tail, Some(value))),
1173            Err(NomErr::Error(_)) => Ok((input, None)),
1174            Err(e) => Err(e),
1175        }
1176    }
1177}
1178
1179/// Parser which, when successful, discards the output of the subparser and
1180/// instead returns the consumed input.
1181#[derive(Debug, Clone, Copy)]
1182pub struct Recognize<P, O> {
1183    parser: WithRecognized<P>,
1184    phantom: PhantomData<O>,
1185}
1186
1187impl<I, O, E, P> Parser<I, I, E> for Recognize<P, O>
1188where
1189    P: Parser<I, O, E>,
1190    I: Clone + Slice<RangeTo<usize>> + Offset,
1191{
1192    #[inline]
1193    fn parse(&mut self, input: I) -> nom::IResult<I, I, E> {
1194        self.parser
1195            .parse(input)
1196            .map(|(tail, (recognized, _))| (tail, recognized))
1197    }
1198}
1199
1200/// Parser which, when successful, returns the result of the inner parser and
1201/// also the consumed input
1202#[derive(Debug, Clone, Copy)]
1203pub struct WithRecognized<P> {
1204    parser: P,
1205}
1206
1207impl<I, O, E, P> Parser<I, (I, O), E> for WithRecognized<P>
1208where
1209    P: Parser<I, O, E>,
1210    I: Clone + Slice<RangeTo<usize>> + Offset,
1211{
1212    #[inline]
1213    fn parse(&mut self, input: I) -> nom::IResult<I, (I, O), E> {
1214        let (tail, output) = self.parser.parse(input.clone())?;
1215        let index = input.offset(&tail);
1216        Ok((tail, (input.slice(..index), output)))
1217    }
1218}
1219
1220/// Parser which, when successful, discards the output of the subparser and
1221/// instead returns a clone of a value.
1222#[derive(Debug, Clone, Copy)]
1223pub struct Value<T, P, O> {
1224    parser: P,
1225    value: T,
1226    phantom: PhantomData<O>,
1227}
1228
1229impl<I, O, E, T, P> Parser<I, T, E> for Value<T, P, O>
1230where
1231    P: Parser<I, O, E>,
1232    T: Clone,
1233{
1234    #[inline]
1235    fn parse(&mut self, input: I) -> nom::IResult<I, T, E> {
1236        self.parser
1237            .parse(input)
1238            .map(|(input, _)| (input, self.value.clone()))
1239    }
1240}
1241
1242/// Parser which checks the output of its subparser against a verifier function.
1243#[derive(Debug, Clone, Copy)]
1244pub struct Verify<P, F> {
1245    parser: P,
1246    verifier: F,
1247}
1248
1249impl<I, O, E, P, F> Parser<I, O, E> for Verify<P, F>
1250where
1251    P: Parser<I, O, E>,
1252    E: ParseError<I>,
1253    F: Fn(&O) -> bool,
1254    I: Clone,
1255{
1256    #[inline]
1257    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1258        let (tail, value) = self.parser.parse(input.clone())?;
1259
1260        match (self.verifier)(&value) {
1261            true => Ok((tail, value)),
1262            false => Err(NomErr::Error(E::from_error_kind(
1263                input,
1264                NomErrorKind::Verify,
1265            ))),
1266        }
1267    }
1268}
1269
1270/// Parser which attaches additional context to any errors returned by the
1271/// subparser.
1272#[derive(Debug, Clone, Copy)]
1273pub struct Context<P, C> {
1274    context: C,
1275    parser: P,
1276}
1277
1278impl<I, O, E, P, C> Parser<I, O, E> for Context<P, C>
1279where
1280    P: Parser<I, O, E>,
1281    E: ContextError<I, C>,
1282    I: Clone,
1283    C: Clone,
1284{
1285    #[inline]
1286    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1287        self.parser.parse(input.clone()).map_err(move |err| {
1288            err.map(move |err| E::add_context(input, self.context.clone(), err))
1289        })
1290    }
1291}
1292
1293/// Parser which replaces errors coming from the inner parser.
1294#[derive(Debug, Clone, Copy)]
1295pub struct ReplaceError<P, E> {
1296    new_error: E,
1297    parser: P,
1298}
1299
1300impl<I, O, F, E, P> Parser<I, O, E> for ReplaceError<P, F>
1301where
1302    P: Parser<I, O, ()>,
1303    F: FnMut() -> E,
1304{
1305    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1306        self.parser
1307            .parse(input)
1308            .map_err(|err| err.map(|()| (self.new_error)()))
1309    }
1310}
1311
1312/// Parser which gets and discards an output from a second subparser,
1313/// returning the output from the original parser if both were successful.
1314#[derive(Debug, Clone, Copy)]
1315pub struct Terminated<P1, P2, O2> {
1316    parser: P1,
1317    terminator: P2,
1318    phantom: PhantomData<O2>,
1319}
1320
1321impl<I, O1, O2, E, P1, P2> Parser<I, O1, E> for Terminated<P1, P2, O2>
1322where
1323    P1: Parser<I, O1, E>,
1324    P2: Parser<I, O2, E>,
1325{
1326    #[inline]
1327    fn parse(&mut self, input: I) -> nom::IResult<I, O1, E> {
1328        let (input, value) = self.parser.parse(input)?;
1329        let (input, _) = self.terminator.parse(input)?;
1330
1331        Ok((input, value))
1332    }
1333}
1334
1335/// Parser which gets and discards an output from a prefix subparser before
1336/// running the main subparser. Returns the output from the main subparser if
1337/// both were successful.
1338#[derive(Debug, Clone, Copy)]
1339pub struct Preceded<P1, P2, O2> {
1340    parser: P1,
1341    prefix: P2,
1342    phantom: PhantomData<O2>,
1343}
1344
1345impl<I, O1, O2, E, P1, P2> Parser<I, O1, E> for Preceded<P1, P2, O2>
1346where
1347    P1: Parser<I, O1, E>,
1348    P2: Parser<I, O2, E>,
1349{
1350    #[inline]
1351    fn parse(&mut self, input: I) -> nom::IResult<I, O1, E> {
1352        let (input, _) = self.prefix.parse(input)?;
1353        self.parser.parse(input)
1354    }
1355}
1356
1357/// Parser which gets an optional output from a prefix subparser before running
1358/// the main subparser. Returns the output even if the prefix subparser returns
1359/// error.
1360#[derive(Debug, Clone, Copy)]
1361pub struct OptionalPreceded<P1, P2> {
1362    parser: P2,
1363    prefix: P1,
1364}
1365
1366impl<I, O1, O2, E, P1, P2> Parser<I, (Option<O1>, O2), E> for OptionalPreceded<P1, P2>
1367where
1368    P1: Parser<I, O1, E>,
1369    P2: Parser<I, O2, E>,
1370    I: Clone,
1371    E: ParseError<I>,
1372{
1373    #[inline]
1374    fn parse(&mut self, input: I) -> nom::IResult<I, (Option<O1>, O2), E> {
1375        match self.prefix.parse(input.clone()) {
1376            Ok((input, o1)) => self
1377                .parser
1378                .parse(input)
1379                .map(|(tail, o2)| (tail, (Some(o1), o2))),
1380            Err(NomErr::Error(err1)) => self
1381                .parser
1382                .parse(input)
1383                .map(|(tail, o2)| (tail, (None, o2)))
1384                .map_err(|err2| err2.map(|err2| err1.or(err2))),
1385            Err(err) => Err(err),
1386        }
1387    }
1388}
1389
1390/// Parser which gets and discards a delimiting value both before and after the
1391/// main subparser. Returns the output from the main subparser if all were
1392/// successful.
1393#[derive(Debug, Clone, Copy)]
1394pub struct Delimited<P, D, O2> {
1395    parser: P,
1396    delimiter: D,
1397    phantom: PhantomData<O2>,
1398}
1399
1400impl<P, D, I, O, E, O2> Parser<I, O, E> for Delimited<P, D, O2>
1401where
1402    P: Parser<I, O, E>,
1403    D: Parser<I, O2, E>,
1404{
1405    #[inline]
1406    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1407        let (input, _) = self.delimiter.parse(input)?;
1408        let (input, value) = self.parser.parse(input)?;
1409        let (input, _) = self.delimiter.parse(input)?;
1410
1411        Ok((input, value))
1412    }
1413}
1414
1415/// Parser which runs a fallible mapping function on the output of the
1416/// subparser. Any errors returned by the mapping function are transformed
1417/// into a parse error.
1418///
1419#[derive(Debug, Clone, Copy)]
1420pub struct MapRes<P, F, O, E2> {
1421    parser: P,
1422    func: F,
1423    phantom: PhantomData<(O, E2)>,
1424}
1425
1426impl<P, F, I, O, E, O2, E2> Parser<I, O2, E> for MapRes<P, F, O, E2>
1427where
1428    P: Parser<I, O, E>,
1429    F: FnMut(O) -> Result<O2, E2>,
1430    E: FromExternalError<I, E2>,
1431    I: Clone,
1432{
1433    #[inline]
1434    fn parse(&mut self, input: I) -> nom::IResult<I, O2, E> {
1435        let (tail, value) = self.parser.parse(input.clone())?;
1436
1437        (self.func)(value)
1438            .map(move |value| (tail, value))
1439            .map_err(move |err| {
1440                NomErr::Error(E::from_external_error(input, NomErrorKind::MapRes, err))
1441            })
1442    }
1443}
1444
1445/// Parser which runs a fallible mapping function on the output of the
1446/// subparser. Any errors returned by the mapping function are transformed
1447/// into a parse failure.
1448///
1449#[derive(Debug, Clone, Copy)]
1450pub struct MapResCut<P, F, O, E2> {
1451    parser: P,
1452    func: F,
1453    phantom: PhantomData<(O, E2)>,
1454}
1455
1456impl<P, F, I, O, E, O2, E2> Parser<I, O2, E> for MapResCut<P, F, O, E2>
1457where
1458    P: Parser<I, O, E>,
1459    F: FnMut(O) -> Result<O2, E2>,
1460    E: FromExternalError<I, E2>,
1461    I: Clone,
1462{
1463    #[inline]
1464    fn parse(&mut self, input: I) -> nom::IResult<I, O2, E> {
1465        let (tail, value) = self.parser.parse(input.clone())?;
1466
1467        (self.func)(value)
1468            .map(move |value| (tail, value))
1469            .map_err(move |err| {
1470                NomErr::Failure(E::from_external_error(input, NomErrorKind::MapRes, err))
1471            })
1472    }
1473}
1474/// Parser which runs a subparser but doesn't consume any input
1475#[derive(Debug, Clone, Copy)]
1476pub struct Peek<P> {
1477    parser: P,
1478}
1479
1480impl<I, O, E, P> Parser<I, O, E> for Peek<P>
1481where
1482    P: Parser<I, O, E>,
1483    I: Clone,
1484{
1485    #[inline]
1486    fn parse(&mut self, input: I) -> nom::IResult<I, O, E> {
1487        self.parser
1488            .parse(input.clone())
1489            .map(|(_, value)| (input, value))
1490    }
1491}
1492
1493/// Parser which returns failure if the subparser succeeds, and succeeds if the
1494/// subparser fails.
1495#[derive(Debug, Clone, Copy)]
1496pub struct Not<P, O> {
1497    parser: P,
1498    phantom: PhantomData<O>,
1499}
1500
1501impl<I, O, E, P> Parser<I, (), E> for Not<P, O>
1502where
1503    P: Parser<I, O, E>,
1504    I: Clone,
1505    E: ParseError<I>,
1506{
1507    #[inline]
1508    fn parse(&mut self, input: I) -> nom::IResult<I, (), E> {
1509        match self.parser.parse(input.clone()) {
1510            Ok(..) => Err(NomErr::Error(E::from_error_kind(input, NomErrorKind::Not))),
1511            Err(NomErr::Error(..)) => Ok((input, ())),
1512            Err(err) => Err(err),
1513        }
1514    }
1515}
1516
1517/// Parser which parses something via [`FromStr`], using a subparser as a
1518/// recognizer for the string to pass to [`from_str`][FromStr::from_str].
1519#[derive(Debug, Clone, Copy)]
1520pub struct FromStrParser<P, T> {
1521    parser: P,
1522    phantom: PhantomData<T>,
1523}
1524
1525impl<'a, T, I, E, P> Parser<I, T, E> for FromStrParser<P, T>
1526where
1527    P: Parser<I, &'a str, E>,
1528    I: Clone,
1529    T: FromStr,
1530    E: FromExternalError<I, T::Err>,
1531{
1532    #[inline]
1533    fn parse(&mut self, input: I) -> nom::IResult<I, T, E> {
1534        let (tail, value_str) = self.parser.parse(input.clone())?;
1535        match value_str.parse() {
1536            Ok(value) => Ok((tail, value)),
1537            Err(parse_err) => Err(NomErr::Error(E::from_external_error(
1538                input,
1539                NomErrorKind::MapRes,
1540                parse_err,
1541            ))),
1542        }
1543    }
1544}
1545
1546#[cfg(feature = "error")]
1547#[test]
1548fn from_str_parser_non_str_input() {
1549    use core::str::from_utf8;
1550
1551    use cool_asserts::assert_matches;
1552    use nom::{
1553        character::complete::{char, digit1},
1554        Err as NomErr,
1555    };
1556
1557    use crate::error::{BaseErrorKind, ErrorTree, Expectation};
1558
1559    let mut parser = digit1
1560        .opt_preceded_by(char('-'))
1561        .recognize()
1562        .map_res(from_utf8)
1563        .parse_from_str();
1564
1565    assert_matches!(parser.parse(b"-123"), Ok((b"", -123)));
1566
1567    let branches = assert_matches!(parser.parse(b"abc"), Err(NomErr::Error(ErrorTree::Alt(branches))) => branches);
1568
1569    assert_matches!(
1570        branches.as_slice(),
1571        [
1572            ErrorTree::Base {
1573                location: b"abc",
1574                kind: BaseErrorKind::Expected(Expectation::Char('-'))
1575            },
1576            ErrorTree::Base {
1577                location: b"abc",
1578                kind: BaseErrorKind::Expected(Expectation::Digit)
1579            }
1580        ]
1581    )
1582}
1583
1584/// Parser which parses something via [`FromStr`], using a subparser as a
1585/// recognizer for the string to pass to [`from_str`][FromStr::from_str].
1586/// Returns [`Err::Failure`][NomErr::Failure] if the [`FromStr`] parse fails.
1587#[derive(Debug, Clone, Copy)]
1588pub struct FromStrCutParser<P, T> {
1589    parser: P,
1590    phantom: PhantomData<T>,
1591}
1592
1593impl<'a, I, T, E, P> Parser<I, T, E> for FromStrCutParser<P, T>
1594where
1595    P: Parser<I, &'a str, E>,
1596    I: Clone,
1597    T: FromStr,
1598    E: FromExternalError<I, T::Err>,
1599{
1600    #[inline]
1601    fn parse(&mut self, input: I) -> nom::IResult<I, T, E> {
1602        let (tail, value_str) = self.parser.parse(input.clone())?;
1603        match value_str.parse() {
1604            Ok(value) => Ok((tail, value)),
1605            Err(parse_err) => Err(NomErr::Failure(E::from_external_error(
1606                input,
1607                NomErrorKind::MapRes,
1608                parse_err,
1609            ))),
1610        }
1611    }
1612}
1613
1614/// Parser which parses an array by running a subparser in a loop a fixed
1615/// number of times.
1616#[derive(Debug, Clone, Copy)]
1617pub struct ArrayParser<P> {
1618    parser: P,
1619}
1620
1621impl<P, I, O, E, const N: usize> Parser<I, [O; N], E> for ArrayParser<P>
1622where
1623    P: Parser<I, O, E>,
1624{
1625    fn parse(&mut self, mut input: I) -> nom::IResult<I, [O; N], E> {
1626        let array = brownstone::build![{
1627            let (tail, value) = self.parser.parse(input)?;
1628            input = tail;
1629            value
1630        }];
1631
1632        Ok((input, array))
1633    }
1634}
1635
1636/// Parser which parses an array by running a subparser in a loop a fixed
1637/// number of times, parsing a separator between each item.
1638#[derive(Debug, Clone, Copy)]
1639pub struct SeparatedArrayParser<P1, P2, O2> {
1640    parser: P1,
1641    separator: P2,
1642    phantom: PhantomData<O2>,
1643}
1644
1645impl<I, O1, O2, E, P1, P2, const N: usize> Parser<I, [O1; N], E>
1646    for SeparatedArrayParser<P1, P2, O2>
1647where
1648    P1: Parser<I, O1, E>,
1649    P2: Parser<I, O2, E>,
1650{
1651    fn parse(&mut self, mut input: I) -> nom::IResult<I, [O1; N], E> {
1652        // TODO: create a folding version of brownstone::try_build so that
1653        // this Some trick isn't necessary
1654        let array = brownstone::build!(|index: usize| {
1655            let tail = match index {
1656                0 => input,
1657                _ => self.separator.parse(input)?.0,
1658            };
1659
1660            let (tail, value) = self.parser.parse(tail)?;
1661            input = tail;
1662            value
1663        });
1664
1665        Ok((input, array))
1666    }
1667}