chumsky/
combinator.rs

1//! Combinators that allow combining and extending existing parsers.
2//!
3//! *“Ford... you're turning into a penguin. Stop it.”*
4//!
5//! Although it's *sometimes* useful to be able to name their type, most of these parsers are much easier to work with
6//! when accessed through their respective methods on [`Parser`].
7
8use inspector::Inspector;
9
10use super::*;
11
12/// The type of a lazy parser.
13pub type Lazy<'src, A, I, E> =
14    ThenIgnore<A, Repeated<Any<I, E>, <I as Input<'src>>::Token, I, E>, (), E>;
15
16/// Alter the configuration of a struct using parse-time context
17#[derive(Copy, Clone)]
18pub struct Configure<A, F> {
19    pub(crate) parser: A,
20    pub(crate) cfg: F,
21}
22
23impl<'src, I, O, E, A, F> Parser<'src, I, O, E> for Configure<A, F>
24where
25    A: ConfigParser<'src, I, O, E>,
26    F: Fn(A::Config, &E::Context) -> A::Config,
27    I: Input<'src>,
28    E: ParserExtra<'src, I>,
29{
30    #[inline(always)]
31    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
32    where
33        Self: Sized,
34    {
35        let cfg = (self.cfg)(A::Config::default(), inp.ctx());
36        self.parser.go_cfg::<M>(inp, cfg)
37    }
38
39    go_extra!(O);
40}
41
42/// See [`ConfigIterParser::configure`]
43pub struct IterConfigure<A, F, OA> {
44    pub(crate) parser: A,
45    pub(crate) cfg: F,
46    #[allow(dead_code)]
47    pub(crate) phantom: EmptyPhantom<OA>,
48}
49
50impl<A: Copy, F: Copy, OA> Copy for IterConfigure<A, F, OA> {}
51impl<A: Clone, F: Clone, OA> Clone for IterConfigure<A, F, OA> {
52    fn clone(&self) -> Self {
53        IterConfigure {
54            parser: self.parser.clone(),
55            cfg: self.cfg.clone(),
56            phantom: EmptyPhantom::new(),
57        }
58    }
59}
60
61impl<'src, I, OA, E, A, F> Parser<'src, I, (), E> for IterConfigure<A, F, OA>
62where
63    A: ConfigIterParser<'src, I, OA, E>,
64    F: Fn(A::Config, &E::Context) -> A::Config,
65    I: Input<'src>,
66    E: ParserExtra<'src, I>,
67{
68    #[inline(always)]
69    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
70        let mut state = self.make_iter::<Check>(inp)?;
71        loop {
72            match self.next::<Check>(inp, &mut state, IterParserDebug::new(false)) {
73                Ok(Some(())) => {}
74                Ok(None) => break Ok(M::bind(|| ())),
75                Err(()) => break Err(()),
76            }
77        }
78    }
79
80    go_extra!(());
81}
82
83impl<'src, I, O, E, A, F> IterParser<'src, I, O, E> for IterConfigure<A, F, O>
84where
85    A: ConfigIterParser<'src, I, O, E>,
86    F: Fn(A::Config, &E::Context) -> A::Config,
87    I: Input<'src>,
88    E: ParserExtra<'src, I>,
89{
90    type IterState<M: Mode>
91        = (A::IterState<M>, A::Config)
92    where
93        I: 'src;
94
95    #[inline(always)]
96    fn make_iter<M: Mode>(
97        &self,
98        inp: &mut InputRef<'src, '_, I, E>,
99    ) -> PResult<Emit, Self::IterState<M>> {
100        Ok((
101            A::make_iter(&self.parser, inp)?,
102            (self.cfg)(A::Config::default(), inp.ctx()),
103        ))
104    }
105
106    #[inline(always)]
107    fn next<M: Mode>(
108        &self,
109        inp: &mut InputRef<'src, '_, I, E>,
110        state: &mut Self::IterState<M>,
111        debug: IterParserDebug,
112    ) -> IPResult<M, O> {
113        self.parser.next_cfg(inp, &mut state.0, &state.1, debug)
114    }
115}
116
117/// See [`ConfigIterParser::try_configure`]
118pub struct TryIterConfigure<A, F, O> {
119    pub(crate) parser: A,
120    pub(crate) cfg: F,
121    #[allow(dead_code)]
122    pub(crate) phantom: EmptyPhantom<O>,
123}
124
125impl<A: Copy, F: Copy, O> Copy for TryIterConfigure<A, F, O> {}
126impl<A: Clone, F: Clone, O> Clone for TryIterConfigure<A, F, O> {
127    fn clone(&self) -> Self {
128        TryIterConfigure {
129            parser: self.parser.clone(),
130            cfg: self.cfg.clone(),
131            phantom: EmptyPhantom::new(),
132        }
133    }
134}
135
136impl<'src, I, OA, E, A, F> Parser<'src, I, (), E> for TryIterConfigure<A, F, OA>
137where
138    A: ConfigIterParser<'src, I, OA, E>,
139    F: Fn(A::Config, &E::Context, I::Span) -> Result<A::Config, E::Error>,
140    I: Input<'src>,
141    E: ParserExtra<'src, I>,
142{
143    #[inline(always)]
144    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
145        let mut state = self.make_iter::<Check>(inp)?;
146        loop {
147            match self.next::<Check>(inp, &mut state, IterParserDebug::new(false)) {
148                Ok(Some(())) => {}
149                Ok(None) => break Ok(M::bind(|| ())),
150                Err(()) => break Err(()),
151            }
152        }
153    }
154
155    go_extra!(());
156}
157
158impl<'src, I, O, E, A, F> IterParser<'src, I, O, E> for TryIterConfigure<A, F, O>
159where
160    A: ConfigIterParser<'src, I, O, E>,
161    F: Fn(A::Config, &E::Context, I::Span) -> Result<A::Config, E::Error>,
162    I: Input<'src>,
163    E: ParserExtra<'src, I>,
164{
165    type IterState<M: Mode>
166        = (A::IterState<M>, A::Config)
167    where
168        I: 'src;
169
170    fn make_iter<M: Mode>(
171        &self,
172        inp: &mut InputRef<'src, '_, I, E>,
173    ) -> PResult<Emit, Self::IterState<M>> {
174        let span = inp.span_since(&inp.cursor());
175        let cfg = (self.cfg)(A::Config::default(), inp.ctx(), span)
176            .map_err(|e| inp.add_alt_err(&inp.cursor().inner, e))?;
177
178        Ok((A::make_iter(&self.parser, inp)?, cfg))
179    }
180
181    fn next<M: Mode>(
182        &self,
183        inp: &mut InputRef<'src, '_, I, E>,
184        state: &mut Self::IterState<M>,
185        debug: IterParserDebug,
186    ) -> IPResult<M, O> {
187        self.parser.next_cfg(inp, &mut state.0, &state.1, debug)
188    }
189}
190
191/// See [`Parser::to_slice`]
192pub struct ToSlice<A, O> {
193    pub(crate) parser: A,
194    #[allow(dead_code)]
195    pub(crate) phantom: EmptyPhantom<O>,
196}
197
198impl<A: Copy, O> Copy for ToSlice<A, O> {}
199impl<A: Clone, O> Clone for ToSlice<A, O> {
200    fn clone(&self) -> Self {
201        Self {
202            parser: self.parser.clone(),
203            phantom: EmptyPhantom::new(),
204        }
205    }
206}
207
208impl<'src, A, I, O, E> Parser<'src, I, I::Slice, E> for ToSlice<A, O>
209where
210    A: Parser<'src, I, O, E>,
211    I: SliceInput<'src>,
212    E: ParserExtra<'src, I>,
213{
214    #[doc(hidden)]
215    #[cfg(feature = "debug")]
216    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
217        self.parser.node_info(scope)
218    }
219
220    #[inline(always)]
221    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, I::Slice>
222    where
223        Self: Sized,
224    {
225        let before = inp.cursor();
226        self.parser.go::<Check>(inp)?;
227
228        Ok(M::bind(|| inp.slice_since(&before..)))
229    }
230
231    go_extra!(I::Slice);
232}
233
234/// See [`Parser::filter`].
235pub struct Filter<A, F> {
236    pub(crate) parser: A,
237    pub(crate) filter: F,
238}
239
240impl<A: Copy, F: Copy> Copy for Filter<A, F> {}
241impl<A: Clone, F: Clone> Clone for Filter<A, F> {
242    fn clone(&self) -> Self {
243        Self {
244            parser: self.parser.clone(),
245            filter: self.filter.clone(),
246        }
247    }
248}
249
250impl<'src, A, I, O, E, F> Parser<'src, I, O, E> for Filter<A, F>
251where
252    I: Input<'src>,
253    E: ParserExtra<'src, I>,
254    A: Parser<'src, I, O, E>,
255    F: Fn(&O) -> bool,
256{
257    #[doc(hidden)]
258    #[cfg(feature = "debug")]
259    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
260        debug::NodeInfo::Filter(Box::new(self.parser.node_info(scope)))
261    }
262
263    #[inline(always)]
264    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
265        let found = inp.peek_maybe();
266        let before = inp.cursor();
267        // Remove the pre-inner alt, to be reinserted later so we always preserve it
268        let old_alt = inp.errors.alt.take();
269
270        let res = self.parser.go::<Emit>(inp);
271        let span = inp.span_since(&before);
272        let new_alt = inp.errors.alt.take();
273
274        inp.errors.alt = old_alt;
275        match res {
276            Ok(out) => {
277                if (self.filter)(&out) {
278                    // If successful, reinsert the original alt and then apply the new alt on top of it, since both are valid
279                    if let Some(new_alt) = new_alt {
280                        inp.add_alt_err(&new_alt.pos, new_alt.err);
281                    }
282                    Ok(M::bind(|| out))
283                } else {
284                    // If unsuccessful, reinsert the original alt but replace the new alt with the "something else" error (since it overrides it)
285                    let expected = [DefaultExpected::SomethingElse];
286                    // TODO: Use something more detailed than the next token as the found
287                    let err = E::Error::expected_found(expected, found, span);
288                    inp.add_alt_err(&before.inner, err);
289                    Err(())
290                }
291            }
292
293            Err(_) => {
294                // Can't fail!
295                let new_alt = new_alt.unwrap();
296                inp.add_alt_err(&new_alt.pos, new_alt.err);
297                Err(())
298            }
299        }
300    }
301
302    go_extra!(O);
303}
304
305/// See [`Parser::map`].
306pub struct Map<A, OA, F> {
307    pub(crate) parser: A,
308    pub(crate) mapper: F,
309    #[allow(dead_code)]
310    pub(crate) phantom: EmptyPhantom<OA>,
311}
312
313impl<A: Copy, OA, F: Copy> Copy for Map<A, OA, F> {}
314impl<A: Clone, OA, F: Clone> Clone for Map<A, OA, F> {
315    fn clone(&self) -> Self {
316        Self {
317            parser: self.parser.clone(),
318            mapper: self.mapper.clone(),
319            phantom: EmptyPhantom::new(),
320        }
321    }
322}
323
324impl<'src, I, O, E, A, OA, F> Parser<'src, I, O, E> for Map<A, OA, F>
325where
326    I: Input<'src>,
327    E: ParserExtra<'src, I>,
328    A: Parser<'src, I, OA, E>,
329    F: Fn(OA) -> O,
330{
331    #[doc(hidden)]
332    #[cfg(feature = "debug")]
333    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
334        self.parser.node_info(scope)
335    }
336
337    #[inline(always)]
338    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
339        let out = self.parser.go::<M>(inp)?;
340        Ok(M::map(out, &self.mapper))
341    }
342
343    go_extra!(O);
344}
345
346impl<'src, I, O, E, A, OA, F> IterParser<'src, I, O, E> for Map<A, OA, F>
347where
348    I: Input<'src>,
349    E: ParserExtra<'src, I>,
350    A: IterParser<'src, I, OA, E>,
351    F: Fn(OA) -> O,
352{
353    type IterState<M: Mode>
354        = A::IterState<M>
355    where
356        I: 'src;
357
358    #[inline(always)]
359    fn make_iter<M: Mode>(
360        &self,
361        inp: &mut InputRef<'src, '_, I, E>,
362    ) -> PResult<Emit, Self::IterState<M>> {
363        self.parser.make_iter(inp)
364    }
365
366    #[inline(always)]
367    fn next<M: Mode>(
368        &self,
369        inp: &mut InputRef<'src, '_, I, E>,
370        state: &mut Self::IterState<M>,
371        debug: IterParserDebug,
372    ) -> IPResult<M, O> {
373        match self.parser.next::<M>(inp, state, debug) {
374            Ok(Some(o)) => Ok(Some(M::map(o, &self.mapper))),
375            Ok(None) => Ok(None),
376            Err(()) => Err(()),
377        }
378    }
379}
380
381/// See [`Parser::map_with`].
382pub struct MapWith<A, OA, F> {
383    pub(crate) parser: A,
384    pub(crate) mapper: F,
385    #[allow(dead_code)]
386    pub(crate) phantom: EmptyPhantom<OA>,
387}
388
389impl<A: Copy, OA, F: Copy> Copy for MapWith<A, OA, F> {}
390impl<A: Clone, OA, F: Clone> Clone for MapWith<A, OA, F> {
391    fn clone(&self) -> Self {
392        Self {
393            parser: self.parser.clone(),
394            mapper: self.mapper.clone(),
395            phantom: EmptyPhantom::new(),
396        }
397    }
398}
399
400impl<'src, I, O, E, A, OA, F> Parser<'src, I, O, E> for MapWith<A, OA, F>
401where
402    I: Input<'src>,
403    E: ParserExtra<'src, I>,
404    A: Parser<'src, I, OA, E>,
405    F: Fn(OA, &mut MapExtra<'src, '_, I, E>) -> O,
406{
407    #[doc(hidden)]
408    #[cfg(feature = "debug")]
409    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
410        self.parser.node_info(scope)
411    }
412
413    #[inline(always)]
414    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
415        let before = inp.cursor();
416        let out = self.parser.go::<M>(inp)?;
417        Ok(M::map(out, |out| {
418            (self.mapper)(out, &mut MapExtra::new(&before, inp))
419        }))
420    }
421
422    go_extra!(O);
423}
424
425impl<'src, I, O, E, A, OA, F> IterParser<'src, I, O, E> for MapWith<A, OA, F>
426where
427    I: Input<'src>,
428    E: ParserExtra<'src, I>,
429    A: IterParser<'src, I, OA, E>,
430    F: Fn(OA, &mut MapExtra<'src, '_, I, E>) -> O,
431{
432    type IterState<M: Mode>
433        = A::IterState<M>
434    where
435        I: 'src;
436
437    #[inline(always)]
438    fn make_iter<M: Mode>(
439        &self,
440        inp: &mut InputRef<'src, '_, I, E>,
441    ) -> PResult<Emit, Self::IterState<M>> {
442        self.parser.make_iter(inp)
443    }
444
445    #[inline(always)]
446    fn next<M: Mode>(
447        &self,
448        inp: &mut InputRef<'src, '_, I, E>,
449        state: &mut Self::IterState<M>,
450        debug: IterParserDebug,
451    ) -> IPResult<M, O> {
452        let before = inp.cursor();
453        match self.parser.next::<M>(inp, state, debug) {
454            Ok(Some(o)) => Ok(Some(M::map(o, |o| {
455                (self.mapper)(o, &mut MapExtra::new(&before, inp))
456            }))),
457            Ok(None) => Ok(None),
458            Err(()) => Err(()),
459        }
460    }
461}
462
463/// See [`Parser::map_group`].
464#[cfg(feature = "nightly")]
465pub struct MapGroup<A, OA, F> {
466    pub(crate) parser: A,
467    pub(crate) mapper: F,
468    #[allow(dead_code)]
469    pub(crate) phantom: EmptyPhantom<OA>,
470}
471
472#[cfg(feature = "nightly")]
473impl<A: Copy, OA, F: Copy> Copy for MapGroup<A, OA, F> {}
474#[cfg(feature = "nightly")]
475impl<A: Clone, OA, F: Clone> Clone for MapGroup<A, OA, F> {
476    fn clone(&self) -> Self {
477        Self {
478            parser: self.parser.clone(),
479            mapper: self.mapper.clone(),
480            phantom: EmptyPhantom::new(),
481        }
482    }
483}
484
485#[cfg(feature = "nightly")]
486impl<'src, I, O, E, A, OA, F> Parser<'src, I, O, E> for MapGroup<A, OA, F>
487where
488    I: Input<'src>,
489    E: ParserExtra<'src, I>,
490    A: Parser<'src, I, OA, E>,
491    F: Fn<OA, Output = O>,
492    OA: Tuple,
493{
494    #[inline(always)]
495    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
496        let out = self.parser.go::<M>(inp)?;
497        Ok(M::map(out, |out| self.mapper.call(out)))
498    }
499
500    go_extra!(O);
501}
502
503#[cfg(feature = "nightly")]
504impl<'src, I, O, E, A, OA, F> IterParser<'src, I, O, E> for MapGroup<A, OA, F>
505where
506    I: Input<'src>,
507    E: ParserExtra<'src, I>,
508    A: IterParser<'src, I, OA, E>,
509    F: Fn<OA, Output = O>,
510    OA: Tuple,
511{
512    type IterState<M: Mode>
513        = A::IterState<M>
514    where
515        I: 'src;
516
517    #[inline(always)]
518    fn make_iter<M: Mode>(
519        &self,
520        inp: &mut InputRef<'src, '_, I, E>,
521    ) -> PResult<Emit, Self::IterState<M>> {
522        self.parser.make_iter(inp)
523    }
524
525    #[inline(always)]
526    fn next<M: Mode>(
527        &self,
528        inp: &mut InputRef<'src, '_, I, E>,
529        state: &mut Self::IterState<M>,
530        debug: IterParserDebug,
531    ) -> IPResult<M, O> {
532        match self.parser.next::<M>(inp, state, debug) {
533            Ok(Some(o)) => Ok(Some(M::map(o, |o| self.mapper.call(o)))),
534            Ok(None) => Ok(None),
535            Err(()) => Err(()),
536        }
537    }
538}
539
540/// See [`Parser::to_span`].
541pub struct ToSpan<A, OA> {
542    pub(crate) parser: A,
543    #[allow(dead_code)]
544    pub(crate) phantom: EmptyPhantom<OA>,
545}
546
547impl<A: Copy, OA> Copy for ToSpan<A, OA> {}
548impl<A: Clone, OA> Clone for ToSpan<A, OA> {
549    fn clone(&self) -> Self {
550        Self {
551            parser: self.parser.clone(),
552            phantom: EmptyPhantom::new(),
553        }
554    }
555}
556
557impl<'src, I, OA, E, A> Parser<'src, I, I::Span, E> for ToSpan<A, OA>
558where
559    I: Input<'src>,
560    E: ParserExtra<'src, I>,
561    A: Parser<'src, I, OA, E>,
562{
563    #[inline(always)]
564    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, I::Span> {
565        let before = inp.cursor();
566        self.parser.go::<Check>(inp)?;
567        Ok(M::bind(|| inp.span_since(&before)))
568    }
569
570    go_extra!(I::Span);
571}
572
573/// See [`Parser::spanned`].
574pub struct Spanned<A, OA> {
575    pub(crate) parser: A,
576    #[allow(dead_code)]
577    pub(crate) phantom: EmptyPhantom<OA>,
578}
579
580impl<A: Copy, OA> Copy for Spanned<A, OA> {}
581impl<A: Clone, OA> Clone for Spanned<A, OA> {
582    fn clone(&self) -> Self {
583        Self {
584            parser: self.parser.clone(),
585            phantom: EmptyPhantom::new(),
586        }
587    }
588}
589
590impl<'src, I, OA, E, A> Parser<'src, I, <I::Span as WrappingSpan<OA>>::Spanned, E>
591    for Spanned<A, OA>
592where
593    I: Input<'src>,
594    E: ParserExtra<'src, I>,
595    A: Parser<'src, I, OA, E>,
596    I::Span: WrappingSpan<OA>,
597{
598    #[inline(always)]
599    fn go<M: Mode>(
600        &self,
601        inp: &mut InputRef<'src, '_, I, E>,
602    ) -> PResult<M, <I::Span as WrappingSpan<OA>>::Spanned> {
603        let before = inp.cursor();
604        let out = self.parser.go::<M>(inp)?;
605        Ok(M::map(out, |out| inp.span_since(&before).make_wrapped(out)))
606    }
607
608    go_extra!(<I::Span as WrappingSpan<OA>>::Spanned);
609}
610
611/// See [`Parser::try_foldl`].
612pub struct TryFoldl<F, A, B, OB, E> {
613    pub(crate) parser_a: A,
614    pub(crate) parser_b: B,
615    pub(crate) folder: F,
616    #[allow(dead_code)]
617    pub(crate) phantom: EmptyPhantom<(OB, E)>,
618}
619
620impl<F: Copy, A: Copy, B: Copy, OB, E> Copy for TryFoldl<F, A, B, OB, E> {}
621impl<F: Clone, A: Clone, B: Clone, OB, E> Clone for TryFoldl<F, A, B, OB, E> {
622    fn clone(&self) -> Self {
623        Self {
624            parser_a: self.parser_a.clone(),
625            parser_b: self.parser_b.clone(),
626            folder: self.folder.clone(),
627            phantom: EmptyPhantom::new(),
628        }
629    }
630}
631
632impl<'src, I, F, A, B, OA, OB, E> Parser<'src, I, OA, E> for TryFoldl<F, A, B, OB, E>
633where
634    I: Input<'src>,
635    A: Parser<'src, I, OA, E>,
636    B: IterParser<'src, I, OB, E>,
637    E: ParserExtra<'src, I>,
638    F: Fn(OA, OB, &mut MapExtra<'src, '_, I, E>) -> Result<OA, E::Error>,
639{
640    #[inline(always)]
641    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, OA>
642    where
643        Self: Sized,
644    {
645        let before_all = inp.cursor();
646        let mut out = self.parser_a.go::<Emit>(inp)?;
647        let mut iter_state = self.parser_b.make_iter::<Emit>(inp)?;
648        loop {
649            let before = inp.cursor();
650            match self
651                .parser_b
652                .next::<Emit>(inp, &mut iter_state, IterParserDebug::new(false))
653            {
654                Ok(Some(b_out)) => {
655                    match (self.folder)(out, b_out, &mut MapExtra::new(&before_all, inp)) {
656                        Ok(b_f_out) => {
657                            out = b_f_out;
658                        }
659                        Err(err) => {
660                            inp.add_alt_err(&before.inner, err);
661                            break Err(());
662                        }
663                    }
664                }
665                Ok(None) => break Ok(M::bind(|| out)),
666                Err(()) => break Err(()),
667            }
668        }
669    }
670
671    go_extra!(OA);
672}
673
674/// See [`Parser::try_map`].
675pub struct TryMap<A, OA, F> {
676    pub(crate) parser: A,
677    pub(crate) mapper: F,
678    #[allow(dead_code)]
679    pub(crate) phantom: EmptyPhantom<OA>,
680}
681
682impl<A: Copy, OA, F: Copy> Copy for TryMap<A, OA, F> {}
683impl<A: Clone, OA, F: Clone> Clone for TryMap<A, OA, F> {
684    fn clone(&self) -> Self {
685        Self {
686            parser: self.parser.clone(),
687            mapper: self.mapper.clone(),
688            phantom: EmptyPhantom::new(),
689        }
690    }
691}
692
693impl<'src, I, O, E, A, OA, F> Parser<'src, I, O, E> for TryMap<A, OA, F>
694where
695    I: Input<'src>,
696    E: ParserExtra<'src, I>,
697    A: Parser<'src, I, OA, E>,
698    F: Fn(OA, I::Span) -> Result<O, E::Error>,
699{
700    #[doc(hidden)]
701    #[cfg(feature = "debug")]
702    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
703        debug::NodeInfo::Filter(Box::new(self.parser.node_info(scope)))
704    }
705
706    #[inline(always)]
707    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
708        let before = inp.cursor();
709        // Remove the pre-inner alt, to be reinserted later so we always preserve it
710        let old_alt = inp.errors.alt.take();
711
712        let res = self.parser.go::<Emit>(inp);
713        let span = inp.span_since(&before);
714        let new_alt = inp.errors.alt.take();
715
716        // Reinsert the original alt
717        inp.errors.alt = old_alt;
718        match res {
719            Ok(out) => {
720                match (self.mapper)(out, span) {
721                    Ok(out) => {
722                        // If successful apply the new alt on top of the original alt, since both are valid
723                        if let Some(new_alt) = new_alt {
724                            inp.add_alt_err(&new_alt.pos, new_alt.err);
725                        }
726                        Ok(M::bind(|| out))
727                    }
728
729                    Err(err) => {
730                        // If unsuccessful replace the new alt with the mapper error (since it overrides it)
731                        inp.add_alt_err(&before.inner, err);
732                        Err(())
733                    }
734                }
735            }
736
737            Err(_) => {
738                // Can't fail!
739                let new_alt = new_alt.unwrap();
740                inp.add_alt_err(&new_alt.pos, new_alt.err);
741                Err(())
742            }
743        }
744    }
745
746    go_extra!(O);
747}
748
749/// See [`Parser::try_map_with`].
750pub struct TryMapWith<A, OA, F> {
751    pub(crate) parser: A,
752    pub(crate) mapper: F,
753    #[allow(dead_code)]
754    pub(crate) phantom: EmptyPhantom<OA>,
755}
756
757impl<A: Copy, OA, F: Copy> Copy for TryMapWith<A, OA, F> {}
758impl<A: Clone, OA, F: Clone> Clone for TryMapWith<A, OA, F> {
759    fn clone(&self) -> Self {
760        Self {
761            parser: self.parser.clone(),
762            mapper: self.mapper.clone(),
763            phantom: EmptyPhantom::new(),
764        }
765    }
766}
767
768impl<'src, I, O, E, A, OA, F> Parser<'src, I, O, E> for TryMapWith<A, OA, F>
769where
770    I: Input<'src>,
771    E: ParserExtra<'src, I>,
772    A: Parser<'src, I, OA, E>,
773    F: Fn(OA, &mut MapExtra<'src, '_, I, E>) -> Result<O, E::Error>,
774{
775    #[inline(always)]
776    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
777        let before = inp.cursor();
778        // Remove the pre-inner alt, to be reinserted later so we always preserve it
779        let old_alt = inp.errors.alt.take();
780
781        let res = self.parser.go::<Emit>(inp);
782        let new_alt = inp.errors.alt.take();
783
784        // Reinsert the original alt
785        inp.errors.alt = old_alt;
786        match res {
787            Ok(out) => {
788                match (self.mapper)(out, &mut MapExtra::new(&before, inp)) {
789                    Ok(out) => {
790                        // If successful apply the new alt on top of the original alt, since both are valid
791                        if let Some(new_alt) = new_alt {
792                            inp.add_alt_err(&new_alt.pos, new_alt.err);
793                        }
794                        Ok(M::bind(|| out))
795                    }
796
797                    Err(err) => {
798                        // If unsuccessful replace the new alt with the mapper error (since it overrides it)
799                        inp.add_alt_err(&before.inner, err);
800                        Err(())
801                    }
802                }
803            }
804
805            Err(_) => {
806                // Can't fail!
807                let new_alt = new_alt.unwrap();
808                inp.add_alt_err(&new_alt.pos, new_alt.err);
809                Err(())
810            }
811        }
812    }
813
814    go_extra!(O);
815}
816
817/// See [`Parser::to`].
818pub struct To<A, OA, O> {
819    pub(crate) parser: A,
820    pub(crate) to: O,
821    #[allow(dead_code)]
822    pub(crate) phantom: EmptyPhantom<OA>,
823}
824
825impl<A: Copy, OA, O: Copy> Copy for To<A, OA, O> {}
826impl<A: Clone, OA, O: Clone> Clone for To<A, OA, O> {
827    fn clone(&self) -> Self {
828        Self {
829            parser: self.parser.clone(),
830            to: self.to.clone(),
831            phantom: EmptyPhantom::new(),
832        }
833    }
834}
835
836impl<'src, I, O, E, A, OA> Parser<'src, I, O, E> for To<A, OA, O>
837where
838    I: Input<'src>,
839    E: ParserExtra<'src, I>,
840    A: Parser<'src, I, OA, E>,
841    O: Clone,
842{
843    #[doc(hidden)]
844    #[cfg(feature = "debug")]
845    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
846        self.parser.node_info(scope)
847    }
848
849    #[inline(always)]
850    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
851        self.parser.go::<Check>(inp)?;
852        Ok(M::bind(|| self.to.clone()))
853    }
854
855    go_extra!(O);
856}
857
858/// See [`Parser::into_iter`].
859pub struct IntoIter<A, O> {
860    pub(crate) parser: A,
861    #[allow(dead_code)]
862    pub(crate) phantom: EmptyPhantom<O>,
863}
864
865impl<A: Copy, O> Copy for IntoIter<A, O> {}
866impl<A: Clone, O> Clone for IntoIter<A, O> {
867    fn clone(&self) -> Self {
868        Self {
869            parser: self.parser.clone(),
870            phantom: EmptyPhantom::new(),
871        }
872    }
873}
874
875impl<'src, A, O, I, E> Parser<'src, I, (), E> for IntoIter<A, O>
876where
877    I: Input<'src>,
878    E: ParserExtra<'src, I>,
879    A: Parser<'src, I, O, E>,
880    O: IntoIterator,
881{
882    #[inline(always)]
883    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
884        self.parser.go::<Check>(inp)?;
885        Ok(M::bind(|| ()))
886    }
887
888    go_extra!(());
889}
890
891impl<'src, A, O, I, E> IterParser<'src, I, O::Item, E> for IntoIter<A, O>
892where
893    I: Input<'src>,
894    E: ParserExtra<'src, I>,
895    A: Parser<'src, I, O, E>,
896    O: IntoIterator,
897{
898    // TODO: Don't always produce output for non-emitting modes, but needed due to length. Use some way to 'select'
899    // between iterator and usize at compile time.
900    type IterState<M: Mode> = O::IntoIter; //M::Output<O::IntoIter>;
901
902    #[inline(always)]
903    fn make_iter<M: Mode>(
904        &self,
905        inp: &mut InputRef<'src, '_, I, E>,
906    ) -> PResult<Emit, Self::IterState<M>> {
907        // M::map(self.parser.go::<M>(inp)?, |out| out.into_iter())
908        self.parser.go::<Emit>(inp).map(|out| out.into_iter())
909    }
910
911    #[inline(always)]
912    fn next<M: Mode>(
913        &self,
914        _inp: &mut InputRef<'src, '_, I, E>,
915        iter: &mut Self::IterState<M>,
916        _debug: IterParserDebug,
917    ) -> IPResult<M, O::Item> {
918        Ok(iter.next().map(|out| M::bind(|| out)))
919    }
920}
921
922/// See [`Parser::ignored`].
923pub struct Ignored<A, OA> {
924    pub(crate) parser: A,
925    #[allow(dead_code)]
926    pub(crate) phantom: EmptyPhantom<OA>,
927}
928
929impl<A: Copy, OA> Copy for Ignored<A, OA> {}
930impl<A: Clone, OA> Clone for Ignored<A, OA> {
931    fn clone(&self) -> Self {
932        Self {
933            parser: self.parser.clone(),
934            phantom: EmptyPhantom::new(),
935        }
936    }
937}
938
939impl<'src, I, E, A, OA> Parser<'src, I, (), E> for Ignored<A, OA>
940where
941    I: Input<'src>,
942    E: ParserExtra<'src, I>,
943    A: Parser<'src, I, OA, E>,
944{
945    #[doc(hidden)]
946    #[cfg(feature = "debug")]
947    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
948        self.parser.node_info(scope)
949    }
950
951    #[inline(always)]
952    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
953        self.parser.go::<Check>(inp)?;
954        Ok(M::bind(|| ()))
955    }
956
957    go_extra!(());
958}
959
960/// See [`Parser::unwrapped`].
961pub struct Unwrapped<A, O> {
962    pub(crate) parser: A,
963    #[cfg(debug_assertions)]
964    pub(crate) location: Location<'static>,
965    #[allow(dead_code)]
966    pub(crate) phantom: EmptyPhantom<O>,
967}
968
969impl<A: Copy, O> Copy for Unwrapped<A, O> {}
970impl<A: Clone, O> Clone for Unwrapped<A, O> {
971    fn clone(&self) -> Self {
972        Self {
973            parser: self.parser.clone(),
974            #[cfg(debug_assertions)]
975            location: self.location,
976            phantom: EmptyPhantom::new(),
977        }
978    }
979}
980
981impl<'src, I, E, A, O, U> Parser<'src, I, O, E> for Unwrapped<A, Result<O, U>>
982where
983    I: Input<'src>,
984    E: ParserExtra<'src, I>,
985    A: Parser<'src, I, Result<O, U>, E>,
986    U: fmt::Debug,
987{
988    #[inline(always)]
989    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
990        let out = self.parser.go::<M>(inp)?;
991        Ok(M::map(out, |out| match out {
992            Ok(out) => out,
993
994            Err(err) => {
995                #[cfg(debug_assertions)]
996                panic!(
997                    "called `Result::unwrap` on a `Err(_)` value at {}: {:?}",
998                    self.location, err
999                );
1000                #[cfg(not(debug_assertions))]
1001                panic!("called `Result::unwrap` on a `Err(_)` value: {:?}", err);
1002            }
1003        }))
1004    }
1005
1006    go_extra!(O);
1007}
1008
1009impl<'src, I, E, A, O> Parser<'src, I, O, E> for Unwrapped<A, Option<O>>
1010where
1011    I: Input<'src>,
1012    E: ParserExtra<'src, I>,
1013    A: Parser<'src, I, Option<O>, E>,
1014{
1015    #[inline(always)]
1016    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
1017        let out = self.parser.go::<M>(inp)?;
1018        Ok(M::map(out, |out| match out {
1019            Some(out) => out,
1020            None => {
1021                #[cfg(debug_assertions)]
1022                panic!(
1023                    "called `Option::unwrap` on a `None` value at {}",
1024                    self.location
1025                );
1026                #[cfg(not(debug_assertions))]
1027                panic!("called `Option::unwrap` on a `None` value");
1028            }
1029        }))
1030    }
1031
1032    go_extra!(O);
1033}
1034
1035/// See [`Parser::memoized`].
1036#[cfg(feature = "memoization")]
1037#[derive(Copy, Clone)]
1038pub struct Memoized<A> {
1039    pub(crate) parser: A,
1040}
1041
1042#[cfg(feature = "memoization")]
1043impl<'src, I, E, A, O> Parser<'src, I, O, E> for Memoized<A>
1044where
1045    I: Input<'src>,
1046    E: ParserExtra<'src, I>,
1047    E::Error: Clone,
1048    A: Parser<'src, I, O, E>,
1049{
1050    #[inline(always)]
1051    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
1052        let before = inp.cursor();
1053        // TODO: Don't use address, since this might not be constant?
1054        let key = (
1055            I::cursor_location(&before.inner),
1056            &self.parser as *const _ as *const () as usize,
1057        );
1058
1059        match inp.memos.entry(key) {
1060            hashbrown::hash_map::Entry::Occupied(o) => {
1061                if let Some(err) = o.get() {
1062                    let err = err.clone();
1063                    inp.add_alt_err(&before.inner /*&err.pos*/, err.err);
1064                } else {
1065                    let err_span = inp.span_since(&before);
1066                    // TODO: Is this an appropriate way to handle infinite recursion?
1067                    inp.add_alt([], None, err_span);
1068                }
1069                return Err(());
1070            }
1071            hashbrown::hash_map::Entry::Vacant(v) => {
1072                v.insert(None);
1073            }
1074        }
1075
1076        let res = self.parser.go::<M>(inp);
1077
1078        if res.is_err() {
1079            let alt = inp.take_alt();
1080            inp.memos.insert(key, alt);
1081        } else {
1082            inp.memos.remove(&key);
1083        }
1084
1085        res
1086    }
1087
1088    go_extra!(O);
1089}
1090
1091/// See [`Parser::then`].
1092pub struct Then<A, B, OA, OB, E> {
1093    pub(crate) parser_a: A,
1094    pub(crate) parser_b: B,
1095    #[allow(dead_code)]
1096    pub(crate) phantom: EmptyPhantom<(OA, OB, E)>,
1097}
1098
1099impl<A: Copy, B: Copy, OA, OB, E> Copy for Then<A, B, OA, OB, E> {}
1100impl<A: Clone, B: Clone, OA, OB, E> Clone for Then<A, B, OA, OB, E> {
1101    fn clone(&self) -> Self {
1102        Self {
1103            parser_a: self.parser_a.clone(),
1104            parser_b: self.parser_b.clone(),
1105            phantom: EmptyPhantom::new(),
1106        }
1107    }
1108}
1109
1110impl<'src, I, E, A, B, OA, OB> Parser<'src, I, (OA, OB), E> for Then<A, B, OA, OB, E>
1111where
1112    I: Input<'src>,
1113    E: ParserExtra<'src, I>,
1114    A: Parser<'src, I, OA, E>,
1115    B: Parser<'src, I, OB, E>,
1116{
1117    #[doc(hidden)]
1118    #[cfg(feature = "debug")]
1119    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1120        debug::NodeInfo::Then(
1121            Box::new(self.parser_a.node_info(scope)),
1122            Box::new(self.parser_b.node_info(scope)),
1123        )
1124    }
1125
1126    #[inline(always)]
1127    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, (OA, OB)> {
1128        let a = self.parser_a.go::<M>(inp)?;
1129        let b = self.parser_b.go::<M>(inp)?;
1130        Ok(M::combine(a, b, |a: OA, b: OB| (a, b)))
1131    }
1132
1133    go_extra!((OA, OB));
1134}
1135
1136impl<'src, I, E, A, B, O, U, V> IterParser<'src, I, O, E> for Then<A, B, U, V, E>
1137where
1138    I: Input<'src>,
1139    E: ParserExtra<'src, I>,
1140    A: IterParser<'src, I, O, E>,
1141    B: IterParser<'src, I, O, E>,
1142{
1143    type IterState<M: Mode>
1144        = (A::IterState<M>, Option<B::IterState<M>>)
1145    where
1146        I: 'src;
1147
1148    #[inline(always)]
1149    fn make_iter<M: Mode>(
1150        &self,
1151        inp: &mut InputRef<'src, '_, I, E>,
1152    ) -> PResult<Emit, Self::IterState<M>> {
1153        Ok((self.parser_a.make_iter::<M>(inp)?, None))
1154    }
1155
1156    #[inline(always)]
1157    fn next<M: Mode>(
1158        &self,
1159        inp: &mut InputRef<'src, '_, I, E>,
1160        state: &mut Self::IterState<M>,
1161        debug: IterParserDebug,
1162    ) -> IPResult<M, O> {
1163        match state {
1164            (_, Some(b)) => self.parser_b.next(inp, b, debug),
1165            (a, b) => match self.parser_a.next(inp, a, debug)? {
1166                Some(a_out) => Ok(Some(a_out)),
1167                None => {
1168                    let b = b.insert(self.parser_b.make_iter(inp)?);
1169                    self.parser_b.next(inp, b, debug)
1170                }
1171            },
1172        }
1173    }
1174}
1175
1176/// See [`Parser::ignore_then`].
1177pub struct IgnoreThen<A, B, OA, E> {
1178    pub(crate) parser_a: A,
1179    pub(crate) parser_b: B,
1180    #[allow(dead_code)]
1181    pub(crate) phantom: EmptyPhantom<(OA, E)>,
1182}
1183
1184impl<A: Copy, B: Copy, OA, E> Copy for IgnoreThen<A, B, OA, E> {}
1185impl<A: Clone, B: Clone, OA, E> Clone for IgnoreThen<A, B, OA, E> {
1186    fn clone(&self) -> Self {
1187        Self {
1188            parser_a: self.parser_a.clone(),
1189            parser_b: self.parser_b.clone(),
1190            phantom: EmptyPhantom::new(),
1191        }
1192    }
1193}
1194
1195impl<'src, I, E, A, B, OA, OB> Parser<'src, I, OB, E> for IgnoreThen<A, B, OA, E>
1196where
1197    I: Input<'src>,
1198    E: ParserExtra<'src, I>,
1199    A: Parser<'src, I, OA, E>,
1200    B: Parser<'src, I, OB, E>,
1201{
1202    #[doc(hidden)]
1203    #[cfg(feature = "debug")]
1204    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1205        debug::NodeInfo::Then(
1206            Box::new(self.parser_a.node_info(scope)),
1207            Box::new(self.parser_b.node_info(scope)),
1208        )
1209    }
1210
1211    #[inline(always)]
1212    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, OB> {
1213        self.parser_a.go::<Check>(inp)?;
1214        let b = self.parser_b.go::<M>(inp)?;
1215        Ok(M::map(b, |b: OB| b))
1216    }
1217
1218    go_extra!(OB);
1219}
1220
1221/// See [`Parser::then_ignore`].
1222pub struct ThenIgnore<A, B, OB, E> {
1223    pub(crate) parser_a: A,
1224    pub(crate) parser_b: B,
1225    #[allow(dead_code)]
1226    pub(crate) phantom: EmptyPhantom<(OB, E)>,
1227}
1228
1229impl<A: Copy, B: Copy, OB, E> Copy for ThenIgnore<A, B, OB, E> {}
1230impl<A: Clone, B: Clone, OB, E> Clone for ThenIgnore<A, B, OB, E> {
1231    fn clone(&self) -> Self {
1232        Self {
1233            parser_a: self.parser_a.clone(),
1234            parser_b: self.parser_b.clone(),
1235            phantom: EmptyPhantom::new(),
1236        }
1237    }
1238}
1239
1240impl<'src, I, E, A, B, OA, OB> Parser<'src, I, OA, E> for ThenIgnore<A, B, OB, E>
1241where
1242    I: Input<'src>,
1243    E: ParserExtra<'src, I>,
1244    A: Parser<'src, I, OA, E>,
1245    B: Parser<'src, I, OB, E>,
1246{
1247    #[doc(hidden)]
1248    #[cfg(feature = "debug")]
1249    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1250        debug::NodeInfo::Then(
1251            Box::new(self.parser_a.node_info(scope)),
1252            Box::new(self.parser_b.node_info(scope)),
1253        )
1254    }
1255
1256    #[inline(always)]
1257    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, OA> {
1258        let a = self.parser_a.go::<M>(inp)?;
1259        self.parser_b.go::<Check>(inp)?;
1260        Ok(M::map(a, |a: OA| a))
1261    }
1262
1263    go_extra!(OA);
1264}
1265
1266/// See [`Parser::nested_in`].
1267pub struct NestedIn<A, B, J, O, E> {
1268    pub(crate) parser_a: A,
1269    pub(crate) parser_b: B,
1270    #[allow(dead_code)]
1271    pub(crate) phantom: EmptyPhantom<(J, O, E)>,
1272}
1273
1274impl<A: Copy, B: Copy, J, O, E> Copy for NestedIn<A, B, J, O, E> {}
1275impl<A: Clone, B: Clone, J, O, E> Clone for NestedIn<A, B, J, O, E> {
1276    fn clone(&self) -> Self {
1277        Self {
1278            parser_a: self.parser_a.clone(),
1279            parser_b: self.parser_b.clone(),
1280            phantom: EmptyPhantom::new(),
1281        }
1282    }
1283}
1284
1285impl<'src, I, J, E, A, B, O> Parser<'src, I, O, E> for NestedIn<A, B, J, O, E>
1286where
1287    I: Input<'src>,
1288    E: ParserExtra<'src, I>,
1289    // These bounds looks silly, but they basically just ensure that the extra type of the inner parser is compatible with the extra of the outer parser
1290    E: ParserExtra<
1291        'src,
1292        J,
1293        Error = <E as ParserExtra<'src, I>>::Error,
1294        State = <E as ParserExtra<'src, I>>::State,
1295        Context = <E as ParserExtra<'src, I>>::Context,
1296    >,
1297    <E as ParserExtra<'src, I>>::Error: Error<'src, J>,
1298    <E as ParserExtra<'src, I>>::State: Inspector<'src, J>,
1299    B: Parser<'src, I, J, E>,
1300    J: Input<'src>,
1301    A: Parser<
1302        'src,
1303        J,
1304        O,
1305        extra::Full<
1306            <E as ParserExtra<'src, I>>::Error,
1307            <E as ParserExtra<'src, I>>::State,
1308            <E as ParserExtra<'src, I>>::Context,
1309        >,
1310    >,
1311{
1312    #[doc(hidden)]
1313    #[cfg(feature = "debug")]
1314    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1315        debug::NodeInfo::NestedIn(
1316            Box::new(self.parser_a.node_info(scope)),
1317            Box::new(self.parser_b.node_info(scope)),
1318        )
1319    }
1320
1321    #[inline(always)]
1322    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
1323        let before = inp.save();
1324
1325        let inp2 = self.parser_b.go::<Emit>(inp)?;
1326
1327        let alt = inp.errors.alt.take();
1328
1329        #[cfg(feature = "memoization")]
1330        let mut memos = HashMap::default();
1331        let (start, mut cache) = inp2.begin();
1332        let res = inp.with_input(
1333            start,
1334            &mut cache,
1335            &mut Default::default(),
1336            |inp| (&self.parser_a).then_ignore(end()).go::<M>(inp),
1337            #[cfg(feature = "memoization")]
1338            &mut memos,
1339        );
1340
1341        // Translate error offsets to the start of the outer pattern
1342        // This is not idea, but it mostly prevents error prioritisation issues
1343        let new_alt = inp.errors.alt.take();
1344        inp.errors.alt = alt;
1345        if let Some(new_alt) = new_alt {
1346            inp.add_alt_err(&before.cursor().inner, new_alt.err);
1347        }
1348        for err in inp
1349            .errors
1350            .secondary
1351            .get_mut(before.err_count..)
1352            .into_iter()
1353            .flatten()
1354        {
1355            err.pos = before.cursor().inner.clone();
1356        }
1357
1358        res
1359    }
1360
1361    go_extra!(O);
1362}
1363
1364/// See [`Parser::ignore_with_ctx`].
1365pub struct IgnoreWithCtx<A, B, OA, I, E> {
1366    pub(crate) parser: A,
1367    pub(crate) then: B,
1368    #[allow(dead_code)]
1369    pub(crate) phantom: EmptyPhantom<(B, OA, E, I)>,
1370}
1371
1372impl<A: Copy, B: Copy, OA, I, E> Copy for IgnoreWithCtx<A, B, OA, I, E> {}
1373impl<A: Clone, B: Clone, OA, I, E> Clone for IgnoreWithCtx<A, B, OA, I, E> {
1374    fn clone(&self) -> Self {
1375        Self {
1376            parser: self.parser.clone(),
1377            then: self.then.clone(),
1378            phantom: EmptyPhantom::new(),
1379        }
1380    }
1381}
1382
1383impl<'src, I, E, A, B, OA, OB> Parser<'src, I, OB, E>
1384    for IgnoreWithCtx<A, B, OA, I, extra::Full<E::Error, E::State, OA>>
1385where
1386    I: Input<'src>,
1387    E: ParserExtra<'src, I>,
1388    A: Parser<'src, I, OA, E>,
1389    B: Parser<'src, I, OB, extra::Full<E::Error, E::State, OA>>,
1390    OA: 'src,
1391{
1392    #[inline(always)]
1393    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, OB> {
1394        let p1 = self.parser.go::<Emit>(inp)?;
1395        inp.with_ctx(&p1, |inp| self.then.go::<M>(inp))
1396    }
1397
1398    go_extra!(OB);
1399}
1400
1401impl<'src, I, E, A, B, OA, OB> IterParser<'src, I, OB, E>
1402    for IgnoreWithCtx<A, B, OA, I, extra::Full<E::Error, E::State, OA>>
1403where
1404    I: Input<'src>,
1405    E: ParserExtra<'src, I>,
1406    A: Parser<'src, I, OA, E>,
1407    B: IterParser<'src, I, OB, extra::Full<E::Error, E::State, OA>>,
1408    OA: 'src,
1409{
1410    type IterState<M: Mode>
1411        = (OA, B::IterState<M>)
1412    where
1413        I: 'src;
1414
1415    #[inline(always)]
1416    fn make_iter<M: Mode>(
1417        &self,
1418        inp: &mut InputRef<'src, '_, I, E>,
1419    ) -> PResult<Emit, Self::IterState<M>> {
1420        let out = self.parser.go::<Emit>(inp)?;
1421        let then = inp.with_ctx(&out, |inp| self.then.make_iter::<M>(inp))?;
1422        Ok((out, then))
1423    }
1424
1425    #[inline(always)]
1426    fn next<M: Mode>(
1427        &self,
1428        inp: &mut InputRef<'src, '_, I, E>,
1429        state: &mut Self::IterState<M>,
1430        debug: IterParserDebug,
1431    ) -> IPResult<M, OB> {
1432        let (ctx, inner_state) = state;
1433
1434        inp.with_ctx(ctx, |inp| self.then.next(inp, inner_state, debug))
1435    }
1436}
1437
1438/// See [`Parser::then_with_ctx`].
1439pub struct ThenWithCtx<A, B, OA, I, E> {
1440    pub(crate) parser: A,
1441    pub(crate) then: B,
1442    #[allow(dead_code)]
1443    pub(crate) phantom: EmptyPhantom<(B, OA, E, I)>,
1444}
1445
1446impl<A: Copy, B: Copy, OA, I, E> Copy for ThenWithCtx<A, B, OA, I, E> {}
1447impl<A: Clone, B: Clone, OA, I, E> Clone for ThenWithCtx<A, B, OA, I, E> {
1448    fn clone(&self) -> Self {
1449        Self {
1450            parser: self.parser.clone(),
1451            then: self.then.clone(),
1452            phantom: EmptyPhantom::new(),
1453        }
1454    }
1455}
1456
1457impl<'src, I, E, A, B, OA, OB> Parser<'src, I, (OA, OB), E>
1458    for ThenWithCtx<A, B, OA, I, extra::Full<E::Error, E::State, OA>>
1459where
1460    I: Input<'src>,
1461    E: ParserExtra<'src, I>,
1462    A: Parser<'src, I, OA, E>,
1463    B: Parser<'src, I, OB, extra::Full<E::Error, E::State, OA>>,
1464    OA: 'src,
1465{
1466    #[inline(always)]
1467    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, (OA, OB)> {
1468        let p1 = self.parser.go::<Emit>(inp)?;
1469        let p2 = inp.with_ctx(&p1, |inp| self.then.go::<M>(inp))?;
1470        Ok(M::map(p2, |p2| (p1, p2)))
1471    }
1472
1473    go_extra!((OA, OB));
1474}
1475
1476impl<'src, I, E, A, B, OA, OB> IterParser<'src, I, OB, E>
1477    for ThenWithCtx<A, B, OA, I, extra::Full<E::Error, E::State, OA>>
1478where
1479    I: Input<'src>,
1480    E: ParserExtra<'src, I>,
1481    A: Parser<'src, I, OA, E>,
1482    B: IterParser<'src, I, OB, extra::Full<E::Error, E::State, OA>>,
1483    OA: 'src,
1484{
1485    type IterState<M: Mode>
1486        = (OA, B::IterState<M>)
1487    where
1488        I: 'src;
1489
1490    #[inline(always)]
1491    fn make_iter<M: Mode>(
1492        &self,
1493        inp: &mut InputRef<'src, '_, I, E>,
1494    ) -> PResult<Emit, Self::IterState<M>> {
1495        let out = self.parser.go::<Emit>(inp)?;
1496        let then = inp.with_ctx(&out, |inp| self.then.make_iter::<M>(inp))?;
1497        Ok((out, then))
1498    }
1499
1500    #[inline(always)]
1501    fn next<M: Mode>(
1502        &self,
1503        inp: &mut InputRef<'src, '_, I, E>,
1504        state: &mut Self::IterState<M>,
1505        debug: IterParserDebug,
1506    ) -> IPResult<M, OB> {
1507        let (ctx, inner_state) = state;
1508
1509        inp.with_ctx(ctx, |inp| self.then.next(inp, inner_state, debug))
1510    }
1511}
1512
1513/// See [`Parser::with_ctx`].
1514pub struct WithCtx<A, Ctx> {
1515    pub(crate) parser: A,
1516    pub(crate) ctx: Ctx,
1517}
1518
1519impl<A: Copy, Ctx: Copy> Copy for WithCtx<A, Ctx> {}
1520impl<A: Clone, Ctx: Clone> Clone for WithCtx<A, Ctx> {
1521    fn clone(&self) -> Self {
1522        WithCtx {
1523            parser: self.parser.clone(),
1524            ctx: self.ctx.clone(),
1525        }
1526    }
1527}
1528
1529impl<'src, I, O, E, A, Ctx> Parser<'src, I, O, E> for WithCtx<A, Ctx>
1530where
1531    I: Input<'src>,
1532    E: ParserExtra<'src, I>,
1533    A: Parser<'src, I, O, extra::Full<E::Error, E::State, Ctx>>,
1534    Ctx: 'src,
1535{
1536    #[inline(always)]
1537    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
1538        inp.with_ctx(&self.ctx, |inp| self.parser.go::<M>(inp))
1539    }
1540
1541    go_extra!(O);
1542}
1543
1544/// See [`Parser::with_state`].
1545pub struct WithState<A, State> {
1546    pub(crate) parser: A,
1547    pub(crate) state: State,
1548}
1549
1550impl<A: Copy, Ctx: Copy> Copy for WithState<A, Ctx> {}
1551impl<A: Clone, Ctx: Clone> Clone for WithState<A, Ctx> {
1552    fn clone(&self) -> Self {
1553        WithState {
1554            parser: self.parser.clone(),
1555            state: self.state.clone(),
1556        }
1557    }
1558}
1559
1560impl<'src, I, O, E, A, State> Parser<'src, I, O, E> for WithState<A, State>
1561where
1562    I: Input<'src>,
1563    E: ParserExtra<'src, I>,
1564    A: Parser<'src, I, O, extra::Full<E::Error, State, E::Context>>,
1565    State: 'src + Clone + Inspector<'src, I>,
1566{
1567    #[inline(always)]
1568    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
1569        inp.with_state(&mut self.state.clone(), |inp| self.parser.go::<M>(inp))
1570    }
1571
1572    go_extra!(O);
1573}
1574
1575/// See [`Parser::delimited_by`].
1576pub struct DelimitedBy<A, B, C, OB, OC> {
1577    pub(crate) parser: A,
1578    pub(crate) start: B,
1579    pub(crate) end: C,
1580    #[allow(dead_code)]
1581    pub(crate) phantom: EmptyPhantom<(OB, OC)>,
1582}
1583
1584impl<A: Copy, B: Copy, C: Copy, OB, OC> Copy for DelimitedBy<A, B, C, OB, OC> {}
1585impl<A: Clone, B: Clone, C: Clone, OB, OC> Clone for DelimitedBy<A, B, C, OB, OC> {
1586    fn clone(&self) -> Self {
1587        Self {
1588            parser: self.parser.clone(),
1589            start: self.start.clone(),
1590            end: self.end.clone(),
1591            phantom: EmptyPhantom::new(),
1592        }
1593    }
1594}
1595
1596impl<'src, I, E, A, B, C, OA, OB, OC> Parser<'src, I, OA, E> for DelimitedBy<A, B, C, OB, OC>
1597where
1598    I: Input<'src>,
1599    E: ParserExtra<'src, I>,
1600    A: Parser<'src, I, OA, E>,
1601    B: Parser<'src, I, OB, E>,
1602    C: Parser<'src, I, OC, E>,
1603{
1604    #[doc(hidden)]
1605    #[cfg(feature = "debug")]
1606    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1607        debug::NodeInfo::Then(
1608            Box::new(debug::NodeInfo::Then(
1609                Box::new(self.start.node_info(scope)),
1610                Box::new(self.parser.node_info(scope)),
1611            )),
1612            Box::new(self.end.node_info(scope)),
1613        )
1614    }
1615
1616    #[inline(always)]
1617    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, OA> {
1618        self.start.go::<Check>(inp)?;
1619        let a = self.parser.go::<M>(inp)?;
1620        self.end.go::<Check>(inp)?;
1621        Ok(a)
1622    }
1623
1624    go_extra!(OA);
1625}
1626
1627/// See [`Parser::padded_by`].
1628pub struct PaddedBy<A, B, OB> {
1629    pub(crate) parser: A,
1630    pub(crate) padding: B,
1631    #[allow(dead_code)]
1632    pub(crate) phantom: EmptyPhantom<OB>,
1633}
1634
1635impl<A: Copy, B: Copy, OB> Copy for PaddedBy<A, B, OB> {}
1636impl<A: Clone, B: Clone, OB> Clone for PaddedBy<A, B, OB> {
1637    fn clone(&self) -> Self {
1638        Self {
1639            parser: self.parser.clone(),
1640            padding: self.padding.clone(),
1641            phantom: EmptyPhantom::new(),
1642        }
1643    }
1644}
1645
1646impl<'src, I, E, A, B, OA, OB> Parser<'src, I, OA, E> for PaddedBy<A, B, OB>
1647where
1648    I: Input<'src>,
1649    E: ParserExtra<'src, I>,
1650    A: Parser<'src, I, OA, E>,
1651    B: Parser<'src, I, OB, E>,
1652{
1653    #[inline(always)]
1654    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, OA> {
1655        self.padding.go::<Check>(inp)?;
1656        let a = self.parser.go::<M>(inp)?;
1657        self.padding.go::<Check>(inp)?;
1658        Ok(a)
1659    }
1660
1661    go_extra!(OA);
1662}
1663
1664/// See [`Parser::or`].
1665#[derive(Copy, Clone)]
1666pub struct Or<A, B> {
1667    pub(crate) choice: crate::primitive::Choice<(A, B)>,
1668}
1669
1670impl<'src, I, O, E, A, B> Parser<'src, I, O, E> for Or<A, B>
1671where
1672    I: Input<'src>,
1673    E: ParserExtra<'src, I>,
1674    A: Parser<'src, I, O, E>,
1675    B: Parser<'src, I, O, E>,
1676{
1677    #[doc(hidden)]
1678    #[cfg(feature = "debug")]
1679    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1680        self.choice.node_info(scope)
1681    }
1682
1683    #[inline(always)]
1684    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
1685        self.choice.go::<M>(inp)
1686    }
1687
1688    go_extra!(O);
1689}
1690
1691/// Configuration for [`Parser::repeated`], used in [`ConfigParser::configure`].
1692#[derive(Default)]
1693pub struct RepeatedCfg {
1694    at_least: Option<usize>,
1695    at_most: Option<usize>,
1696}
1697
1698impl RepeatedCfg {
1699    /// Set the minimum number of repetitions accepted
1700    pub fn at_least(mut self, n: usize) -> Self {
1701        self.at_least = Some(n);
1702        self
1703    }
1704
1705    /// Set the maximum number of repetitions accepted
1706    pub fn at_most(mut self, n: usize) -> Self {
1707        self.at_most = Some(n);
1708        self
1709    }
1710
1711    /// Set an exact number of repetitions to accept
1712    pub fn exactly(mut self, n: usize) -> Self {
1713        self.at_least = Some(n);
1714        self.at_most = Some(n);
1715        self
1716    }
1717}
1718
1719/// See [`Parser::repeated`].
1720pub struct Repeated<A, OA, I, E> {
1721    pub(crate) parser: A,
1722    pub(crate) at_least: usize,
1723    // Slightly evil: Should be `Option<usize>`, but we encode `!0` as 'no cap' because it's so large
1724    pub(crate) at_most: u64,
1725    #[cfg(debug_assertions)]
1726    pub(crate) location: Location<'static>,
1727    #[allow(dead_code)]
1728    pub(crate) phantom: EmptyPhantom<(OA, E, I)>,
1729}
1730
1731impl<A: Copy, OA, I, E> Copy for Repeated<A, OA, I, E> {}
1732impl<A: Clone, OA, I, E> Clone for Repeated<A, OA, I, E> {
1733    fn clone(&self) -> Self {
1734        Self {
1735            parser: self.parser.clone(),
1736            at_least: self.at_least,
1737            at_most: self.at_most,
1738            #[cfg(debug_assertions)]
1739            location: self.location,
1740            phantom: EmptyPhantom::new(),
1741        }
1742    }
1743}
1744
1745impl<'src, A, OA, I, E> Repeated<A, OA, I, E>
1746where
1747    A: Parser<'src, I, OA, E>,
1748    I: Input<'src>,
1749    E: ParserExtra<'src, I>,
1750{
1751    /// Require that the pattern appear at least a minimum number of times.
1752    pub fn at_least(self, at_least: usize) -> Self {
1753        Self { at_least, ..self }
1754    }
1755
1756    /// Require that the pattern appear at most a maximum number of times.
1757    pub fn at_most(self, at_most: usize) -> Self {
1758        Self {
1759            at_most: at_most as u64,
1760            ..self
1761        }
1762    }
1763
1764    /// Require that the pattern appear exactly the given number of times.
1765    ///
1766    /// ```
1767    /// # use chumsky::prelude::*;
1768    /// let ring = just::<_, _, extra::Err<Simple<char>>>('O');
1769    ///
1770    /// let for_the_elves = ring
1771    ///     .repeated()
1772    ///     .exactly(3)
1773    ///     .collect::<Vec<_>>();
1774    ///
1775    /// let for_the_dwarves = ring
1776    ///     .repeated()
1777    ///     .exactly(7)
1778    ///     .collect::<Vec<_>>();
1779    ///
1780    /// let for_the_humans = ring
1781    ///     .repeated()
1782    ///     .exactly(9)
1783    ///     .collect::<Vec<_>>();
1784    ///
1785    /// let for_sauron = ring
1786    ///     .repeated()
1787    ///     .exactly(1)
1788    ///     .collect::<Vec<_>>();
1789    ///
1790    /// let rings = for_the_elves
1791    ///     .then(for_the_dwarves)
1792    ///     .then(for_the_humans)
1793    ///     .then(for_sauron);
1794    ///
1795    /// assert!(rings.parse("OOOOOOOOOOOOOOOOOOO").has_errors()); // Too few rings!
1796    /// assert!(rings.parse("OOOOOOOOOOOOOOOOOOOOO").has_errors()); // Too many rings!
1797    /// // The perfect number of rings
1798    /// assert_eq!(
1799    ///     rings.parse("OOOOOOOOOOOOOOOOOOOO").into_result(),
1800    ///     Ok(((((vec!['O'; 3]), vec!['O'; 7]), vec!['O'; 9]), vec!['O'; 1])),
1801    /// );
1802    /// ````
1803    pub fn exactly(self, exactly: usize) -> Self {
1804        Self {
1805            at_least: exactly,
1806            at_most: exactly as u64,
1807            ..self
1808        }
1809    }
1810}
1811
1812impl<'src, I, E, A, OA> Parser<'src, I, (), E> for Repeated<A, OA, I, E>
1813where
1814    I: Input<'src>,
1815    E: ParserExtra<'src, I>,
1816    A: Parser<'src, I, OA, E>,
1817{
1818    #[doc(hidden)]
1819    #[cfg(feature = "debug")]
1820    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1821        debug::NodeInfo::Repeated(
1822            self.at_least as u64..self.at_most,
1823            Box::new(self.parser.node_info(scope)),
1824        )
1825    }
1826
1827    #[inline(always)]
1828    #[allow(clippy::nonminimal_bool)] // TODO: Remove this, lint is currently buggy
1829    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
1830        if self.at_most == !0 && self.at_least == 0 {
1831            loop {
1832                let before = inp.save();
1833                match self.parser.go::<Check>(inp) {
1834                    Ok(()) => {
1835                        #[cfg(debug_assertions)]
1836                        debug_assert!(
1837                            *before.cursor() != inp.cursor(),
1838                            "found Repeated combinator making no progress at {}",
1839                            self.location,
1840                        );
1841                    }
1842                    Err(()) => {
1843                        inp.rewind(before);
1844                        break Ok(M::bind(|| ()));
1845                    }
1846                }
1847            }
1848        } else {
1849            let mut state = self.make_iter::<Check>(inp)?;
1850            loop {
1851                match self.next::<Check>(inp, &mut state, IterParserDebug::new(false)) {
1852                    Ok(Some(())) => {}
1853                    Ok(None) => break Ok(M::bind(|| ())),
1854                    // TODO: Technically we should be rewinding here: as-is, this is invalid since errorring parsers
1855                    // are permitted to leave input state unspecified. Really, unwinding should occur *here* and not in
1856                    // `next`.
1857                    Err(()) => break Err(()),
1858                }
1859            }
1860        }
1861    }
1862
1863    go_extra!(());
1864}
1865
1866impl<'src, A, O, I, E> IterParser<'src, I, O, E> for Repeated<A, O, I, E>
1867where
1868    I: Input<'src>,
1869    E: ParserExtra<'src, I>,
1870    A: Parser<'src, I, O, E>,
1871{
1872    type IterState<M: Mode> = usize;
1873
1874    #[doc(hidden)]
1875    #[cfg(feature = "debug")]
1876    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
1877        debug::NodeInfo::Repeated(
1878            self.at_least as u64..self.at_most,
1879            Box::new(self.parser.node_info(scope)),
1880        )
1881    }
1882
1883    #[inline(always)]
1884    fn make_iter<M: Mode>(
1885        &self,
1886        _inp: &mut InputRef<'src, '_, I, E>,
1887    ) -> PResult<Emit, Self::IterState<M>> {
1888        Ok(0)
1889    }
1890
1891    #[inline(always)]
1892    fn next<M: Mode>(
1893        &self,
1894        inp: &mut InputRef<'src, '_, I, E>,
1895        count: &mut Self::IterState<M>,
1896        debug: IterParserDebug,
1897    ) -> IPResult<M, O> {
1898        if *count as u64 >= self.at_most {
1899            return Ok(None);
1900        }
1901
1902        let before = inp.save();
1903        match self.parser.go::<M>(inp) {
1904            Ok(item) => {
1905                #[cfg(debug_assertions)]
1906                if !debug.nonconsumption_is_ok && self.at_most == !0 {
1907                    debug_assert!(
1908                        *before.cursor() != inp.cursor(),
1909                        "found Repeated combinator making no progress at {}",
1910                        self.location,
1911                    );
1912                }
1913                *count += 1;
1914                Ok(Some(item))
1915            }
1916            Err(()) => {
1917                inp.rewind(before);
1918                if *count >= self.at_least {
1919                    Ok(None)
1920                } else {
1921                    Err(())
1922                }
1923            }
1924        }
1925    }
1926}
1927
1928impl<'src, A, O, I, E> ConfigIterParser<'src, I, O, E> for Repeated<A, O, I, E>
1929where
1930    I: Input<'src>,
1931    E: ParserExtra<'src, I>,
1932    A: Parser<'src, I, O, E>,
1933{
1934    type Config = RepeatedCfg;
1935
1936    #[inline(always)]
1937    fn next_cfg<M: Mode>(
1938        &self,
1939        inp: &mut InputRef<'src, '_, I, E>,
1940        count: &mut Self::IterState<M>,
1941        cfg: &Self::Config,
1942        debug: IterParserDebug,
1943    ) -> IPResult<M, O> {
1944        let at_most = cfg.at_most.map(|x| x as u64).unwrap_or(self.at_most);
1945        let at_least = cfg.at_least.unwrap_or(self.at_least);
1946
1947        if *count as u64 >= at_most {
1948            return Ok(None);
1949        }
1950
1951        let before = inp.save();
1952        match self.parser.go::<M>(inp) {
1953            Ok(item) => {
1954                #[cfg(debug_assertions)]
1955                if !debug.nonconsumption_is_ok {
1956                    debug_assert!(
1957                        *before.cursor() != inp.cursor(),
1958                        "found Repeated combinator making no progress at {}",
1959                        self.location,
1960                    );
1961                }
1962                *count += 1;
1963                Ok(Some(item))
1964            }
1965            Err(()) => {
1966                inp.rewind(before);
1967                if *count >= at_least {
1968                    Ok(None)
1969                } else {
1970                    Err(())
1971                }
1972            }
1973        }
1974    }
1975}
1976
1977/// See [`Parser::separated_by`].
1978pub struct SeparatedBy<A, B, OA, OB, I, E> {
1979    pub(crate) parser: A,
1980    pub(crate) separator: B,
1981    pub(crate) at_least: usize,
1982    // Slightly evil: Should be `Option<usize>`, but we encode `!0` as 'no cap' because it's so large
1983    pub(crate) at_most: u64,
1984    pub(crate) allow_leading: bool,
1985    pub(crate) allow_trailing: bool,
1986    #[cfg(debug_assertions)]
1987    pub(crate) location: Location<'static>,
1988    #[allow(dead_code)]
1989    pub(crate) phantom: EmptyPhantom<(OA, OB, E, I)>,
1990}
1991
1992impl<A: Copy, B: Copy, OA, OB, I, E> Copy for SeparatedBy<A, B, OA, OB, I, E> {}
1993impl<A: Clone, B: Clone, OA, OB, I, E> Clone for SeparatedBy<A, B, OA, OB, I, E> {
1994    fn clone(&self) -> Self {
1995        Self {
1996            parser: self.parser.clone(),
1997            separator: self.separator.clone(),
1998            at_least: self.at_least,
1999            at_most: self.at_most,
2000            allow_leading: self.allow_leading,
2001            allow_trailing: self.allow_trailing,
2002            #[cfg(debug_assertions)]
2003            location: self.location,
2004            phantom: EmptyPhantom::new(),
2005        }
2006    }
2007}
2008
2009impl<'src, A, B, OA, OB, I, E> SeparatedBy<A, B, OA, OB, I, E>
2010where
2011    A: Parser<'src, I, OA, E>,
2012    B: Parser<'src, I, OB, E>,
2013    I: Input<'src>,
2014    E: ParserExtra<'src, I>,
2015{
2016    /// Require that the pattern appear at least a minimum number of times.
2017    ///
2018    /// ```
2019    /// # use chumsky::prelude::*;
2020    /// let numbers = just::<_, _, extra::Err<Simple<char>>>('-')
2021    ///     .separated_by(just('.'))
2022    ///     .at_least(2)
2023    ///     .collect::<Vec<_>>();
2024    ///
2025    /// assert!(numbers.parse("").has_errors());
2026    /// assert!(numbers.parse("-").has_errors());
2027    /// assert_eq!(numbers.parse("-.-").into_result(), Ok(vec!['-', '-']));
2028    /// ````
2029    pub fn at_least(self, at_least: usize) -> Self {
2030        Self { at_least, ..self }
2031    }
2032
2033    /// Require that the pattern appear at most a maximum number of times.
2034    ///
2035    /// ```
2036    /// # use chumsky::prelude::*;
2037    /// let row_4 = text::int::<_, extra::Err<Simple<char>>>(10)
2038    ///     .padded()
2039    ///     .separated_by(just(','))
2040    ///     .at_most(4)
2041    ///     .collect::<Vec<_>>();
2042    ///
2043    /// let matrix_4x4 = row_4
2044    ///     .separated_by(just(','))
2045    ///     .at_most(4)
2046    ///     .collect::<Vec<_>>();
2047    ///
2048    /// assert_eq!(
2049    ///     matrix_4x4.parse("0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15").into_result(),
2050    ///     Ok(vec![
2051    ///         vec!["0", "1", "2", "3"],
2052    ///         vec!["4", "5", "6", "7"],
2053    ///         vec!["8", "9", "10", "11"],
2054    ///         vec!["12", "13", "14", "15"],
2055    ///     ]),
2056    /// );
2057    /// ````
2058    pub fn at_most(self, at_most: usize) -> Self {
2059        Self {
2060            at_most: at_most as u64,
2061            ..self
2062        }
2063    }
2064
2065    /// Require that the pattern appear exactly the given number of times.
2066    ///
2067    /// ```
2068    /// # use chumsky::prelude::*;
2069    /// let coordinate_3d = text::int::<_, extra::Err<Simple<char>>>(10)
2070    ///     .padded()
2071    ///     .separated_by(just(','))
2072    ///     .exactly(3)
2073    ///     .collect::<Vec<_>>();
2074    ///
2075    /// // Not enough elements
2076    /// assert!(coordinate_3d.parse("4, 3").has_errors());
2077    /// // Too many elements
2078    /// assert!(coordinate_3d.parse("7, 2, 13, 4").has_errors());
2079    /// // Just the right number of elements
2080    /// assert_eq!(coordinate_3d.parse("5, 0, 12").into_result(), Ok(vec!["5", "0", "12"]));
2081    /// ````
2082    pub fn exactly(self, exactly: usize) -> Self {
2083        Self {
2084            at_least: exactly,
2085            at_most: exactly as u64,
2086            ..self
2087        }
2088    }
2089
2090    /// Allow a leading separator to appear before the first item.
2091    ///
2092    /// Note that even if no items are parsed, a leading separator *is* permitted.
2093    ///
2094    /// # Examples
2095    ///
2096    /// ```
2097    /// # use chumsky::prelude::*;
2098    /// let r#enum = text::ascii::keyword::<_, _, extra::Err<Simple<char>>>("enum")
2099    ///     .padded()
2100    ///     .ignore_then(text::ascii::ident()
2101    ///         .padded()
2102    ///         .separated_by(just('|'))
2103    ///         .allow_leading()
2104    ///         .collect::<Vec<_>>());
2105    ///
2106    /// assert_eq!(r#enum.parse("enum True | False").into_result(), Ok(vec!["True", "False"]));
2107    /// assert_eq!(r#enum.parse("
2108    ///     enum
2109    ///     | True
2110    ///     | False
2111    /// ").into_result(), Ok(vec!["True", "False"]));
2112    /// ```
2113    pub fn allow_leading(self) -> Self {
2114        Self {
2115            allow_leading: true,
2116            ..self
2117        }
2118    }
2119
2120    /// Allow a trailing separator to appear after the last item.
2121    ///
2122    /// Note that if no items are parsed, no leading separator is permitted.
2123    ///
2124    /// # Examples
2125    ///
2126    /// ```
2127    /// # use chumsky::prelude::*;
2128    /// let numbers = text::int::<_, extra::Err<Simple<char>>>(10)
2129    ///     .padded()
2130    ///     .separated_by(just(','))
2131    ///     .allow_trailing()
2132    ///     .collect::<Vec<_>>()
2133    ///     .delimited_by(just('('), just(')'));
2134    ///
2135    /// assert_eq!(numbers.parse("(1, 2)").into_result(), Ok(vec!["1", "2"]));
2136    /// assert_eq!(numbers.parse("(1, 2,)").into_result(), Ok(vec!["1", "2"]));
2137    /// ```
2138    pub fn allow_trailing(self) -> Self {
2139        Self {
2140            allow_trailing: true,
2141            ..self
2142        }
2143    }
2144}
2145
2146impl<'src, I, E, A, B, OA, OB> IterParser<'src, I, OA, E> for SeparatedBy<A, B, OA, OB, I, E>
2147where
2148    I: Input<'src>,
2149    E: ParserExtra<'src, I>,
2150    A: Parser<'src, I, OA, E>,
2151    B: Parser<'src, I, OB, E>,
2152{
2153    type IterState<M: Mode>
2154        = usize
2155    where
2156        I: 'src;
2157
2158    #[doc(hidden)]
2159    #[cfg(feature = "debug")]
2160    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
2161        debug::NodeInfo::SeparatedBy(
2162            Box::new(self.parser.node_info(scope)),
2163            Box::new(self.separator.node_info(scope)),
2164        )
2165    }
2166
2167    #[inline(always)]
2168    fn make_iter<M: Mode>(
2169        &self,
2170        _inp: &mut InputRef<'src, '_, I, E>,
2171    ) -> PResult<Emit, Self::IterState<M>> {
2172        Ok(0)
2173    }
2174
2175    #[inline(always)]
2176    fn next<M: Mode>(
2177        &self,
2178        inp: &mut InputRef<'src, '_, I, E>,
2179        state: &mut Self::IterState<M>,
2180        debug: IterParserDebug,
2181    ) -> IPResult<M, OA> {
2182        #[cfg(debug_assertions)]
2183        let before = inp.cursor();
2184
2185        if *state as u64 >= self.at_most {
2186            return Ok(None);
2187        }
2188
2189        let before_separator = inp.save();
2190        if *state == 0 && self.allow_leading {
2191            if self.separator.go::<Check>(inp).is_err() {
2192                inp.rewind(before_separator.clone());
2193            }
2194        } else if *state > 0 {
2195            match self.separator.go::<Check>(inp) {
2196                Ok(()) => {
2197                    // Do nothing
2198                }
2199                Err(()) if *state < self.at_least => {
2200                    inp.rewind(before_separator);
2201                    return Err(());
2202                }
2203                Err(()) => {
2204                    inp.rewind(before_separator);
2205                    return Ok(None);
2206                }
2207            }
2208        }
2209
2210        let before_item = inp.save();
2211        match self.parser.go::<M>(inp) {
2212            Ok(item) => {
2213                #[cfg(debug_assertions)]
2214                if !debug.nonconsumption_is_ok && self.at_most == !0 && *state > 0 {
2215                    debug_assert!(
2216                        before != inp.cursor(),
2217                        "found SeparatedBy combinator making no progress at {}",
2218                        self.location,
2219                    );
2220                }
2221                *state += 1;
2222                Ok(Some(item))
2223            }
2224            Err(()) if *state < self.at_least => {
2225                // We have errored before we have reached the count,
2226                // and therefore should return this error, as we are
2227                // still expecting items
2228                inp.rewind(before_separator);
2229                Err(())
2230            }
2231            Err(()) => {
2232                // We are not expecting any more items, so it is okay
2233                // for it to fail.
2234
2235                // though if we don't allow trailing, we shouldn't have
2236                // consumed the separator, so we need to rewind it.
2237                if self.allow_trailing {
2238                    inp.rewind(before_item);
2239                } else {
2240                    inp.rewind(before_separator);
2241                }
2242                Ok(None)
2243            }
2244        }
2245    }
2246}
2247
2248impl<'src, I, E, A, B, OA, OB> Parser<'src, I, (), E> for SeparatedBy<A, B, OA, OB, I, E>
2249where
2250    I: Input<'src>,
2251    E: ParserExtra<'src, I>,
2252    A: Parser<'src, I, OA, E>,
2253    B: Parser<'src, I, OB, E>,
2254{
2255    #[doc(hidden)]
2256    #[cfg(feature = "debug")]
2257    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
2258        debug::NodeInfo::SeparatedBy(
2259            Box::new(self.parser.node_info(scope)),
2260            Box::new(self.separator.node_info(scope)),
2261        )
2262    }
2263
2264    #[inline(always)]
2265    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
2266        let mut state = self.make_iter::<Check>(inp)?;
2267        loop {
2268            match self.next::<Check>(inp, &mut state, IterParserDebug::new(false)) {
2269                Ok(Some(())) => {}
2270                Ok(None) => break Ok(M::bind(|| ())),
2271                // TODO: Technically we should be rewinding here: as-is, this is invalid since errorring parsers
2272                // are permitted to leave input state unspecified. Really, unwinding should occur *here* and not in
2273                // `next`.
2274                Err(()) => break Err(()),
2275            }
2276        }
2277    }
2278
2279    go_extra!(());
2280}
2281
2282/// See [`IterParser::enumerate`].
2283pub struct Enumerate<A, O> {
2284    pub(crate) parser: A,
2285    #[allow(dead_code)]
2286    pub(crate) phantom: EmptyPhantom<O>,
2287}
2288
2289impl<A: Copy, O> Copy for Enumerate<A, O> {}
2290impl<A: Clone, O> Clone for Enumerate<A, O> {
2291    fn clone(&self) -> Self {
2292        Self {
2293            parser: self.parser.clone(),
2294            phantom: EmptyPhantom::new(),
2295        }
2296    }
2297}
2298
2299impl<'src, I, O, E, A> IterParser<'src, I, (usize, O), E> for Enumerate<A, O>
2300where
2301    A: IterParser<'src, I, O, E>,
2302    I: Input<'src>,
2303    E: ParserExtra<'src, I>,
2304{
2305    type IterState<M: Mode>
2306        = (usize, A::IterState<M>)
2307    where
2308        I: 'src;
2309
2310    #[inline(always)]
2311    fn make_iter<M: Mode>(
2312        &self,
2313        inp: &mut InputRef<'src, '_, I, E>,
2314    ) -> PResult<Emit, Self::IterState<M>> {
2315        Ok((0, A::make_iter(&self.parser, inp)?))
2316    }
2317
2318    #[inline(always)]
2319    fn next<M: Mode>(
2320        &self,
2321        inp: &mut InputRef<'src, '_, I, E>,
2322        state: &mut Self::IterState<M>,
2323        debug: IterParserDebug,
2324    ) -> IPResult<M, (usize, O)> {
2325        let out = self
2326            .parser
2327            .next(inp, &mut state.1, debug)?
2328            .map(|out| M::map(out, |out| (state.0, out)));
2329        state.0 += 1;
2330        Ok(out)
2331    }
2332}
2333
2334/// See [`IterParser::collect`].
2335pub struct Collect<A, O, C> {
2336    pub(crate) parser: A,
2337    #[allow(dead_code)]
2338    pub(crate) phantom: EmptyPhantom<(O, C)>,
2339}
2340
2341impl<A: Copy, O, C> Copy for Collect<A, O, C> {}
2342impl<A: Clone, O, C> Clone for Collect<A, O, C> {
2343    fn clone(&self) -> Self {
2344        Self {
2345            parser: self.parser.clone(),
2346            phantom: EmptyPhantom::new(),
2347        }
2348    }
2349}
2350
2351impl<'src, I, O, E, A, C> Parser<'src, I, C, E> for Collect<A, O, C>
2352where
2353    I: Input<'src>,
2354    E: ParserExtra<'src, I>,
2355    A: IterParser<'src, I, O, E>,
2356    C: Container<O>,
2357{
2358    #[doc(hidden)]
2359    #[cfg(feature = "debug")]
2360    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
2361        self.parser.node_info(scope)
2362    }
2363
2364    #[inline(always)]
2365    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, C> {
2366        let mut output = M::bind::<C, _>(|| C::default());
2367        let mut iter_state = self.parser.make_iter::<M>(inp)?;
2368        loop {
2369            match self
2370                .parser
2371                .next::<M>(inp, &mut iter_state, IterParserDebug::new(false))
2372            {
2373                Ok(Some(out)) => {
2374                    M::combine_mut(&mut output, out, |output: &mut C, item| output.push(item));
2375                }
2376
2377                Ok(None) => break Ok(output),
2378
2379                Err(()) => break Err(()),
2380            }
2381        }
2382    }
2383
2384    go_extra!(C);
2385}
2386
2387/// See [`IterParser::collect_exactly`]
2388pub struct CollectExactly<A, O, C> {
2389    pub(crate) parser: A,
2390    #[allow(dead_code)]
2391    pub(crate) phantom: EmptyPhantom<(O, C)>,
2392}
2393
2394impl<A: Copy, O, C> Copy for CollectExactly<A, O, C> {}
2395impl<A: Clone, O, C> Clone for CollectExactly<A, O, C> {
2396    fn clone(&self) -> Self {
2397        Self {
2398            parser: self.parser.clone(),
2399            phantom: EmptyPhantom::new(),
2400        }
2401    }
2402}
2403
2404impl<'src, I, O, E, A, C> Parser<'src, I, C, E> for CollectExactly<A, O, C>
2405where
2406    I: Input<'src>,
2407    E: ParserExtra<'src, I>,
2408    A: IterParser<'src, I, O, E>,
2409    C: ContainerExactly<O>,
2410{
2411    #[inline]
2412    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, C> {
2413        // let before = inp.cursor();
2414        let mut output = M::bind(|| C::uninit());
2415        let mut iter_state = self.parser.make_iter::<M>(inp)?;
2416        for idx in 0..C::LEN {
2417            match self
2418                .parser
2419                .next::<M>(inp, &mut iter_state, IterParserDebug::new(true))
2420            {
2421                Ok(Some(out)) => {
2422                    M::combine_mut(&mut output, out, |c, out| C::write(c, idx, out));
2423                }
2424                Ok(None) => {
2425                    // let span = inp.span_since(&before);
2426                    // We don't add an alt here because we assume the inner parser will. Is this safe to assume?
2427                    // inp.add_alt([ExpectedMoreElements(Some(C::LEN - idx))], None, span);
2428                    // SAFETY: We're guaranteed to have initialized up to `idx` values
2429                    M::map(output, |mut output| unsafe {
2430                        C::drop_before(&mut output, idx)
2431                    });
2432                    return Err(());
2433                }
2434                Err(()) => {
2435                    // SAFETY: We're guaranteed to have initialized up to `idx` values
2436                    M::map(output, |mut output| unsafe {
2437                        C::drop_before(&mut output, idx)
2438                    });
2439                    return Err(());
2440                }
2441            }
2442        }
2443        // SAFETY: If we reach this point, we guarantee to have initialized C::LEN values
2444        Ok(M::map(output, |output| unsafe { C::take(output) }))
2445    }
2446
2447    go_extra!(C);
2448}
2449
2450/// See [`Parser::or_not`].
2451#[derive(Copy, Clone)]
2452pub struct OrNot<A> {
2453    pub(crate) parser: A,
2454}
2455
2456impl<'src, I, O, E, A> Parser<'src, I, Option<O>, E> for OrNot<A>
2457where
2458    I: Input<'src>,
2459    E: ParserExtra<'src, I>,
2460    A: Parser<'src, I, O, E>,
2461{
2462    #[doc(hidden)]
2463    #[cfg(feature = "debug")]
2464    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
2465        debug::NodeInfo::OrNot(Box::new(self.parser.node_info(scope)))
2466    }
2467
2468    #[inline(always)]
2469    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, Option<O>> {
2470        let before = inp.save();
2471        Ok(match self.parser.go::<M>(inp) {
2472            Ok(out) => M::map::<O, _, _>(out, Some),
2473            Err(()) => {
2474                inp.rewind(before);
2475                M::bind::<Option<O>, _>(|| None)
2476            }
2477        })
2478    }
2479
2480    go_extra!(Option<O>);
2481}
2482
2483impl<'src, A, O, I, E> IterParser<'src, I, O, E> for OrNot<A>
2484where
2485    I: Input<'src>,
2486    E: ParserExtra<'src, I>,
2487    A: Parser<'src, I, O, E>,
2488{
2489    type IterState<M: Mode> = bool;
2490
2491    #[inline(always)]
2492    fn make_iter<M: Mode>(
2493        &self,
2494        _inp: &mut InputRef<'src, '_, I, E>,
2495    ) -> PResult<Emit, Self::IterState<M>> {
2496        Ok(false)
2497    }
2498
2499    #[inline(always)]
2500    fn next<M: Mode>(
2501        &self,
2502        inp: &mut InputRef<'src, '_, I, E>,
2503        finished: &mut Self::IterState<M>,
2504        _debug: IterParserDebug,
2505    ) -> IPResult<M, O> {
2506        if *finished {
2507            return Ok(None);
2508        }
2509
2510        let before = inp.save();
2511        match self.parser.go::<M>(inp) {
2512            Ok(item) => {
2513                *finished = true;
2514                Ok(Some(item))
2515            }
2516            Err(()) => {
2517                inp.rewind(before);
2518                *finished = true;
2519                Ok(None)
2520            }
2521        }
2522    }
2523}
2524
2525/// See [`Parser::not`].
2526pub struct Not<A, OA> {
2527    pub(crate) parser: A,
2528    #[allow(dead_code)]
2529    pub(crate) phantom: EmptyPhantom<OA>,
2530}
2531
2532impl<A: Copy, OA> Copy for Not<A, OA> {}
2533impl<A: Clone, OA> Clone for Not<A, OA> {
2534    fn clone(&self) -> Self {
2535        Self {
2536            parser: self.parser.clone(),
2537            phantom: EmptyPhantom::new(),
2538        }
2539    }
2540}
2541
2542impl<'src, I, E, A, OA> Parser<'src, I, (), E> for Not<A, OA>
2543where
2544    I: Input<'src>,
2545    E: ParserExtra<'src, I>,
2546    A: Parser<'src, I, OA, E>,
2547{
2548    #[inline(always)]
2549    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
2550        let before = inp.save();
2551
2552        let alt = inp.errors.alt.take();
2553
2554        let result = self.parser.go::<Check>(inp);
2555        let result_span = inp.span_since(before.cursor());
2556        inp.rewind(before);
2557
2558        inp.errors.alt = alt;
2559
2560        match result {
2561            Ok(()) => {
2562                let found = inp.peek_maybe();
2563                inp.add_alt([DefaultExpected::SomethingElse], found, result_span);
2564                Err(())
2565            }
2566            Err(()) => Ok(M::bind(|| ())),
2567        }
2568    }
2569
2570    go_extra!(());
2571}
2572
2573/// See [`IterParser::flatten`].
2574#[cfg(feature = "nightly")]
2575pub struct Flatten<A, O> {
2576    pub(crate) parser: A,
2577    #[allow(dead_code)]
2578    pub(crate) phantom: EmptyPhantom<O>,
2579}
2580
2581#[cfg(feature = "nightly")]
2582impl<A: Copy, O> Copy for Flatten<A, O> {}
2583#[cfg(feature = "nightly")]
2584impl<A: Clone, O> Clone for Flatten<A, O> {
2585    fn clone(&self) -> Self {
2586        Self {
2587            parser: self.parser.clone(),
2588            phantom: EmptyPhantom::new(),
2589        }
2590    }
2591}
2592
2593#[cfg(feature = "nightly")]
2594impl<'src, A, O, I, E> IterParser<'src, I, O::Item, E> for Flatten<A, O>
2595where
2596    I: Input<'src>,
2597    E: ParserExtra<'src, I>,
2598    A: IterParser<'src, I, O, E>,
2599    O: IntoIterator,
2600{
2601    type IterState<M: Mode> = (A::IterState<M>, Option<M::Output<O::IntoIter>>);
2602
2603    #[inline(always)]
2604    fn make_iter<M: Mode>(
2605        &self,
2606        inp: &mut InputRef<'src, '_, I, E>,
2607    ) -> PResult<Emit, Self::IterState<M>> {
2608        Ok((self.parser.make_iter(inp)?, None))
2609    }
2610
2611    #[inline(always)]
2612    fn next<M: Mode>(
2613        &self,
2614        inp: &mut InputRef<'src, '_, I, E>,
2615        (st, iter): &mut Self::IterState<M>,
2616        debug: IterParserDebug,
2617    ) -> IPResult<M, O::Item> {
2618        if let Some(item) = iter
2619            .as_mut()
2620            .and_then(|i| M::get_or(M::map(M::from_mut(i), |i| i.next()), || None))
2621        {
2622            return Ok(Some(M::bind(move || item)));
2623        }
2624
2625        // TODO: Debug looping check
2626        loop {
2627            let before = inp.save();
2628            match self.parser.next::<M>(inp, st, debug) {
2629                Ok(Some(item)) => match M::get_or(
2630                    M::map(
2631                        M::from_mut(iter.insert(M::map(item, |i| i.into_iter()))),
2632                        |i| i.next().map(Some),
2633                    ),
2634                    || Some(None),
2635                ) {
2636                    Some(Some(item)) => break Ok(Some(M::bind(move || item))),
2637                    Some(None) => break Ok(Some(M::bind(|| unreachable!()))),
2638                    None => continue,
2639                },
2640
2641                Ok(None) => break Ok(None),
2642
2643                Err(()) => {
2644                    inp.rewind(before);
2645                    break Err(());
2646                }
2647            }
2648        }
2649    }
2650}
2651
2652/// See [`Parser::and_is`].
2653pub struct AndIs<A, B, OB> {
2654    pub(crate) parser_a: A,
2655    pub(crate) parser_b: B,
2656    #[allow(dead_code)]
2657    pub(crate) phantom: EmptyPhantom<OB>,
2658}
2659
2660impl<A: Copy, B: Copy, OB> Copy for AndIs<A, B, OB> {}
2661impl<A: Clone, B: Clone, OB> Clone for AndIs<A, B, OB> {
2662    fn clone(&self) -> Self {
2663        Self {
2664            parser_a: self.parser_a.clone(),
2665            parser_b: self.parser_b.clone(),
2666            phantom: EmptyPhantom::new(),
2667        }
2668    }
2669}
2670
2671impl<'src, I, E, A, B, OA, OB> Parser<'src, I, OA, E> for AndIs<A, B, OB>
2672where
2673    I: Input<'src>,
2674    E: ParserExtra<'src, I>,
2675    A: Parser<'src, I, OA, E>,
2676    B: Parser<'src, I, OB, E>,
2677{
2678    #[inline(always)]
2679    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, OA> {
2680        let before = inp.save().clone();
2681        match self.parser_a.go::<M>(inp) {
2682            Ok(out) => {
2683                // A succeeded -- go back to the beginning and try B
2684                let after = inp.save();
2685                inp.rewind_input(before);
2686
2687                match self.parser_b.go::<Check>(inp) {
2688                    Ok(()) => {
2689                        // B succeeded -- go to the end of A and return its output
2690                        inp.rewind_input(after);
2691                        Ok(out)
2692                    }
2693                    Err(()) => {
2694                        // B failed -- go back to the beginning and fail
2695                        Err(())
2696                    }
2697                }
2698            }
2699            Err(()) => {
2700                // A failed -- go back to the beginning and fail
2701                inp.rewind(before);
2702                Err(())
2703            }
2704        }
2705    }
2706
2707    go_extra!(OA);
2708}
2709
2710/// See [`IterParser::fold`].
2711pub struct Fold<F, A, B, O, E> {
2712    pub(crate) parser: A,
2713    pub(crate) init: B,
2714    pub(crate) folder: F,
2715    #[allow(dead_code)]
2716    pub(crate) phantom: EmptyPhantom<(O, E)>,
2717}
2718
2719impl<F: Copy, A: Copy, B: Copy, O, E> Copy for Fold<F, A, B, O, E> {}
2720impl<F: Clone, A: Clone, B: Clone, O, E> Clone for Fold<F, A, B, O, E> {
2721    fn clone(&self) -> Self {
2722        Self {
2723            parser: self.parser.clone(),
2724            init: self.init.clone(),
2725            folder: self.folder.clone(),
2726            phantom: EmptyPhantom::new(),
2727        }
2728    }
2729}
2730
2731impl<'src, I, F, A, B, O, E> Parser<'src, I, B, E> for Fold<F, A, B, O, E>
2732where
2733    I: Input<'src>,
2734    A: IterParser<'src, I, O, E>,
2735    E: ParserExtra<'src, I>,
2736    B: Clone,
2737    F: Fn(B, O) -> B,
2738{
2739    #[inline(always)]
2740    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, B>
2741    where
2742        Self: Sized,
2743    {
2744        let mut acc = M::bind(|| self.init.clone());
2745        let mut iter_state = self.parser.make_iter::<M>(inp)?;
2746        loop {
2747            match self
2748                .parser
2749                .next::<M>(inp, &mut iter_state, IterParserDebug::new(false))
2750            {
2751                Ok(Some(out)) => {
2752                    acc = M::combine(acc, out, |acc, item| (self.folder)(acc, item));
2753                }
2754                Ok(None) => break,
2755                Err(()) => return Err(()),
2756            }
2757        }
2758
2759        Ok(acc)
2760    }
2761
2762    go_extra!(B);
2763}
2764
2765/// See [`IterParser::foldr`].
2766pub struct Foldr<F, A, B, OA, E> {
2767    pub(crate) parser_a: A,
2768    pub(crate) parser_b: B,
2769    pub(crate) folder: F,
2770    #[allow(dead_code)]
2771    pub(crate) phantom: EmptyPhantom<(OA, E)>,
2772}
2773
2774impl<F: Copy, A: Copy, B: Copy, OA, E> Copy for Foldr<F, A, B, OA, E> {}
2775impl<F: Clone, A: Clone, B: Clone, OA, E> Clone for Foldr<F, A, B, OA, E> {
2776    fn clone(&self) -> Self {
2777        Self {
2778            parser_a: self.parser_a.clone(),
2779            parser_b: self.parser_b.clone(),
2780            folder: self.folder.clone(),
2781            phantom: EmptyPhantom::new(),
2782        }
2783    }
2784}
2785
2786impl<'src, I, F, A, B, O, OA, E> Parser<'src, I, O, E> for Foldr<F, A, B, OA, E>
2787where
2788    I: Input<'src>,
2789    A: IterParser<'src, I, OA, E>,
2790    B: Parser<'src, I, O, E>,
2791    E: ParserExtra<'src, I>,
2792    F: Fn(OA, O) -> O,
2793{
2794    #[doc(hidden)]
2795    #[cfg(feature = "debug")]
2796    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
2797        debug::NodeInfo::Then(
2798            Box::new(debug::NodeInfo::Repeated(
2799                0..!0,
2800                Box::new(self.parser_a.node_info(scope)),
2801            )),
2802            Box::new(self.parser_b.node_info(scope)),
2803        )
2804    }
2805
2806    #[inline(always)]
2807    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
2808    where
2809        Self: Sized,
2810    {
2811        let mut a_out = M::bind(|| Vec::new());
2812        let mut iter_state = self.parser_a.make_iter::<M>(inp)?;
2813        loop {
2814            match self
2815                .parser_a
2816                .next::<M>(inp, &mut iter_state, IterParserDebug::new(false))
2817            {
2818                Ok(Some(out)) => {
2819                    M::combine_mut(&mut a_out, out, |a_out, item| a_out.push(item));
2820                }
2821
2822                Ok(None) => break,
2823
2824                Err(()) => return Err(()),
2825            }
2826        }
2827
2828        let b_out = self.parser_b.go::<M>(inp)?;
2829
2830        Ok(M::combine(a_out, b_out, |a_out, b_out| {
2831            a_out.into_iter().rfold(b_out, |b, a| (self.folder)(a, b))
2832        }))
2833    }
2834
2835    go_extra!(O);
2836}
2837
2838/// See [`IterParser::foldr_with`].
2839pub struct FoldrWith<F, A, B, OA, E> {
2840    pub(crate) parser_a: A,
2841    pub(crate) parser_b: B,
2842    pub(crate) folder: F,
2843    #[allow(dead_code)]
2844    pub(crate) phantom: EmptyPhantom<(OA, E)>,
2845}
2846
2847impl<F: Copy, A: Copy, B: Copy, OA, E> Copy for FoldrWith<F, A, B, OA, E> {}
2848impl<F: Clone, A: Clone, B: Clone, OA, E> Clone for FoldrWith<F, A, B, OA, E> {
2849    fn clone(&self) -> Self {
2850        Self {
2851            parser_a: self.parser_a.clone(),
2852            parser_b: self.parser_b.clone(),
2853            folder: self.folder.clone(),
2854            phantom: EmptyPhantom::new(),
2855        }
2856    }
2857}
2858
2859impl<'src, I, F, A, B, O, OA, E> Parser<'src, I, O, E> for FoldrWith<F, A, B, OA, E>
2860where
2861    I: Input<'src>,
2862    A: IterParser<'src, I, OA, E>,
2863    B: Parser<'src, I, O, E>,
2864    E: ParserExtra<'src, I>,
2865    F: Fn(OA, O, &mut MapExtra<'src, '_, I, E>) -> O,
2866{
2867    #[inline(always)]
2868    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
2869    where
2870        Self: Sized,
2871    {
2872        let mut a_out = M::bind(Vec::new);
2873        let mut iter_state = self.parser_a.make_iter::<M>(inp)?;
2874        loop {
2875            let before = inp.cursor();
2876            match self
2877                .parser_a
2878                .next::<M>(inp, &mut iter_state, IterParserDebug::new(false))
2879            {
2880                Ok(Some(out)) => {
2881                    M::combine_mut(&mut a_out, out, |a_out, item| {
2882                        a_out.push((item, before.clone()))
2883                    });
2884                }
2885
2886                Ok(None) => break,
2887
2888                Err(()) => return Err(()),
2889            }
2890        }
2891
2892        let b_out = self.parser_b.go::<M>(inp)?;
2893
2894        Ok(M::combine(a_out, b_out, |a_out, b_out| {
2895            a_out.into_iter().rfold(b_out, |b, (a, before)| {
2896                (self.folder)(a, b, &mut MapExtra::new(&before, inp))
2897            })
2898        }))
2899    }
2900
2901    go_extra!(O);
2902}
2903
2904/// See [`Parser::foldl`].
2905pub struct Foldl<F, A, B, OB, E> {
2906    pub(crate) parser_a: A,
2907    pub(crate) parser_b: B,
2908    pub(crate) folder: F,
2909    #[allow(dead_code)]
2910    pub(crate) phantom: EmptyPhantom<(OB, E)>,
2911}
2912
2913impl<F: Copy, A: Copy, B: Copy, OB, E> Copy for Foldl<F, A, B, OB, E> {}
2914impl<F: Clone, A: Clone, B: Clone, OB, E> Clone for Foldl<F, A, B, OB, E> {
2915    fn clone(&self) -> Self {
2916        Self {
2917            parser_a: self.parser_a.clone(),
2918            parser_b: self.parser_b.clone(),
2919            folder: self.folder.clone(),
2920            phantom: EmptyPhantom::new(),
2921        }
2922    }
2923}
2924
2925impl<'src, I, F, A, B, O, OB, E> Parser<'src, I, O, E> for Foldl<F, A, B, OB, E>
2926where
2927    I: Input<'src>,
2928    A: Parser<'src, I, O, E>,
2929    B: IterParser<'src, I, OB, E>,
2930    E: ParserExtra<'src, I>,
2931    F: Fn(O, OB) -> O,
2932{
2933    #[doc(hidden)]
2934    #[cfg(feature = "debug")]
2935    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
2936        debug::NodeInfo::Then(
2937            Box::new(self.parser_a.node_info(scope)),
2938            Box::new(debug::NodeInfo::Repeated(
2939                0..!0,
2940                Box::new(self.parser_b.node_info(scope)),
2941            )),
2942        )
2943    }
2944
2945    #[inline(always)]
2946    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
2947    where
2948        Self: Sized,
2949    {
2950        let mut out = self.parser_a.go::<M>(inp)?;
2951        let mut iter_state = self.parser_b.make_iter::<M>(inp)?;
2952        loop {
2953            match self
2954                .parser_b
2955                .next::<M>(inp, &mut iter_state, IterParserDebug::new(false))
2956            {
2957                Ok(Some(b_out)) => {
2958                    out = M::combine(out, b_out, |out, b_out| (self.folder)(out, b_out));
2959                }
2960
2961                Ok(None) => break Ok(out),
2962
2963                Err(()) => break Err(()),
2964            }
2965        }
2966    }
2967
2968    go_extra!(O);
2969}
2970
2971/// See [`Parser::foldl_with`].
2972pub struct FoldlWith<F, A, B, OB, E> {
2973    pub(crate) parser_a: A,
2974    pub(crate) parser_b: B,
2975    pub(crate) folder: F,
2976    #[allow(dead_code)]
2977    pub(crate) phantom: EmptyPhantom<(OB, E)>,
2978}
2979
2980impl<F: Copy, A: Copy, B: Copy, OB, E> Copy for FoldlWith<F, A, B, OB, E> {}
2981impl<F: Clone, A: Clone, B: Clone, OB, E> Clone for FoldlWith<F, A, B, OB, E> {
2982    fn clone(&self) -> Self {
2983        Self {
2984            parser_a: self.parser_a.clone(),
2985            parser_b: self.parser_b.clone(),
2986            folder: self.folder.clone(),
2987            phantom: EmptyPhantom::new(),
2988        }
2989    }
2990}
2991
2992impl<'src, I, F, A, B, O, OB, E> Parser<'src, I, O, E> for FoldlWith<F, A, B, OB, E>
2993where
2994    I: Input<'src>,
2995    A: Parser<'src, I, O, E>,
2996    B: IterParser<'src, I, OB, E>,
2997    E: ParserExtra<'src, I>,
2998    F: Fn(O, OB, &mut MapExtra<'src, '_, I, E>) -> O,
2999{
3000    #[doc(hidden)]
3001    #[cfg(feature = "debug")]
3002    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
3003        debug::NodeInfo::Then(
3004            Box::new(self.parser_a.node_info(scope)),
3005            Box::new(debug::NodeInfo::Repeated(
3006                0..!0,
3007                Box::new(self.parser_b.node_info(scope)),
3008            )),
3009        )
3010    }
3011
3012    #[inline(always)]
3013    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
3014    where
3015        Self: Sized,
3016    {
3017        let before_all = inp.cursor();
3018        let mut out = self.parser_a.go::<M>(inp)?;
3019        let mut iter_state = self.parser_b.make_iter::<M>(inp)?;
3020        loop {
3021            match self
3022                .parser_b
3023                .next::<M>(inp, &mut iter_state, IterParserDebug::new(false))
3024            {
3025                Ok(Some(b_out)) => {
3026                    out = M::combine(out, b_out, |out, b_out| {
3027                        (self.folder)(out, b_out, &mut MapExtra::new(&before_all, inp))
3028                    })
3029                }
3030
3031                Ok(None) => break Ok(out),
3032
3033                Err(()) => break Err(()),
3034            }
3035        }
3036    }
3037
3038    go_extra!(O);
3039}
3040
3041/// See [`Parser::rewind`].
3042#[must_use]
3043#[derive(Copy, Clone)]
3044pub struct Rewind<A> {
3045    pub(crate) parser: A,
3046}
3047
3048impl<'src, I, O, E, A> Parser<'src, I, O, E> for Rewind<A>
3049where
3050    I: Input<'src>,
3051    E: ParserExtra<'src, I>,
3052    A: Parser<'src, I, O, E>,
3053{
3054    #[inline(always)]
3055    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
3056        let before = inp.save();
3057        let old_alt = inp.take_alt();
3058        let res = self.parser.go::<M>(inp);
3059        let new_alt = inp.take_alt();
3060
3061        inp.errors.alt = old_alt;
3062        if res.is_ok() {
3063            if let Some(new_alt) = new_alt {
3064                if I::cursor_location(&before.cursor().inner) >= I::cursor_location(&new_alt.pos) {
3065                    inp.add_alt_err(&new_alt.pos, new_alt.err);
3066                }
3067            }
3068            inp.rewind_input(before);
3069        } else {
3070            // Can't fail!
3071            let new_alt = new_alt.unwrap();
3072            inp.add_alt_err(&new_alt.pos, new_alt.err);
3073        }
3074
3075        res
3076    }
3077
3078    go_extra!(O);
3079}
3080
3081/// See [`Parser::map_err`].
3082#[derive(Copy, Clone)]
3083pub struct MapErr<A, F> {
3084    pub(crate) parser: A,
3085    pub(crate) mapper: F,
3086}
3087
3088impl<'src, I, O, E, A, F> Parser<'src, I, O, E> for MapErr<A, F>
3089where
3090    I: Input<'src>,
3091    E: ParserExtra<'src, I>,
3092    A: Parser<'src, I, O, E>,
3093    F: Fn(E::Error) -> E::Error,
3094{
3095    #[doc(hidden)]
3096    #[cfg(feature = "debug")]
3097    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
3098        self.parser.node_info(scope)
3099    }
3100
3101    #[inline(always)]
3102    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
3103    where
3104        Self: Sized,
3105    {
3106        (&self.parser)
3107            .map_err_with_state(|e, _, _| (self.mapper)(e))
3108            .go::<M>(inp)
3109    }
3110
3111    go_extra!(O);
3112}
3113
3114// /// See [`Parser::map_err_with_span`].
3115// #[derive(Copy, Clone)]
3116// pub struct MapErrWithSpan<A, F> {
3117//     pub(crate) parser: A,
3118//     pub(crate) mapper: F,
3119// }
3120
3121// impl<'src, I, O, E, A, F> Parser<'src, I, O, E> for MapErrWithSpan<A, F>
3122// where
3123//     I: Input<'src>,
3124//     E: ParserExtra<'src, I>,
3125//     A: Parser<'src, I, O, E>,
3126//     F: Fn(E::Error, I::Span) -> E::Error,
3127// {
3128//     #[inline(always)]
3129//     fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
3130//     where
3131//         Self: Sized,
3132//     {
3133//         let start = inp.cursor();
3134//         let res = self.parser.go::<M>(inp);
3135
3136//         if res.is_err() {
3137//             let mut e = inp.take_alt();
3138//             let span = inp.span_since(start);
3139//             e.err = (self.mapper)(e.err, span);
3140//             inp.errors.alt = Some(e);
3141//         }
3142
3143//         res
3144//     }
3145
3146//     go_extra!(O);
3147// }
3148
3149// TODO: Remove combinator, replace with map_err_with
3150/// See [`Parser::map_err_with_state`].
3151#[derive(Copy, Clone)]
3152pub struct MapErrWithState<A, F> {
3153    pub(crate) parser: A,
3154    pub(crate) mapper: F,
3155}
3156
3157impl<'src, I, O, E, A, F> Parser<'src, I, O, E> for MapErrWithState<A, F>
3158where
3159    I: Input<'src>,
3160    E: ParserExtra<'src, I>,
3161    A: Parser<'src, I, O, E>,
3162    F: Fn(E::Error, I::Span, &mut E::State) -> E::Error,
3163{
3164    #[inline(always)]
3165    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
3166    where
3167        Self: Sized,
3168    {
3169        let start = inp.cursor();
3170        let old_alt = inp.take_alt();
3171        let res = self.parser.go::<M>(inp);
3172        let new_alt = inp.take_alt();
3173
3174        if res.is_ok() {
3175            inp.errors.alt = old_alt;
3176            if let Some(new_alt) = new_alt {
3177                inp.add_alt_err(&new_alt.pos, new_alt.err);
3178            }
3179        } else {
3180            // Can't fail!
3181            let mut new_alt = new_alt.unwrap();
3182            let span = inp.span_since(&start);
3183            new_alt.err = (self.mapper)(new_alt.err, span, inp.state());
3184
3185            inp.errors.alt = old_alt;
3186            inp.add_alt_err(&new_alt.pos, new_alt.err);
3187        }
3188
3189        res
3190    }
3191
3192    go_extra!(O);
3193}
3194
3195/// See [`Parser::validate`]
3196pub struct Validate<A, OA, F> {
3197    pub(crate) parser: A,
3198    pub(crate) validator: F,
3199    #[allow(dead_code)]
3200    pub(crate) phantom: EmptyPhantom<OA>,
3201}
3202
3203impl<A: Copy, OA, F: Copy> Copy for Validate<A, OA, F> {}
3204impl<A: Clone, OA, F: Clone> Clone for Validate<A, OA, F> {
3205    fn clone(&self) -> Self {
3206        Validate {
3207            parser: self.parser.clone(),
3208            validator: self.validator.clone(),
3209            phantom: EmptyPhantom::new(),
3210        }
3211    }
3212}
3213
3214impl<'src, I, OA, U, E, A, F> Parser<'src, I, U, E> for Validate<A, OA, F>
3215where
3216    I: Input<'src>,
3217    E: ParserExtra<'src, I>,
3218    A: Parser<'src, I, OA, E>,
3219    F: Fn(OA, &mut MapExtra<'src, '_, I, E>, &mut Emitter<E::Error>) -> U,
3220{
3221    #[doc(hidden)]
3222    #[cfg(feature = "debug")]
3223    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
3224        self.parser.node_info(scope)
3225    }
3226
3227    #[inline(always)]
3228    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, U>
3229    where
3230        Self: Sized,
3231    {
3232        let before = inp.cursor();
3233        let out = self.parser.go::<Emit>(inp)?;
3234
3235        let mut emitter = Emitter::new();
3236        let out = (self.validator)(out, &mut MapExtra::new(&before, inp), &mut emitter);
3237        for err in emitter.errors() {
3238            inp.emit_at(before.clone(), err);
3239        }
3240        Ok(M::bind(|| out))
3241    }
3242
3243    go_extra!(U);
3244}
3245
3246// /// See [`Parser::or_else`].
3247// #[derive(Copy, Clone)]
3248// pub struct OrElse<A, F> {
3249//     pub(crate) parser: A,
3250//     pub(crate) or_else: F,
3251// }
3252
3253// impl<'src, I, O, E, A, F> Parser<'src, I, O, E> for OrElse<A, F>
3254// where
3255//     I: Input<'src>,
3256//     E: ParserExtra<'src, I>,
3257//     A: Parser<'src, I, O, E>,
3258//     F: Fn(E::Error) -> Result<O, E::Error>,
3259// {
3260//     #[inline(always)]
3261//     fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O>
3262//     where
3263//         Self: Sized,
3264//     {
3265//         let before = inp.save();
3266//         match self.parser.go::<M>(inp) {
3267//             Ok(out) => Ok(out),
3268//             Err(()) => {
3269//                 let err = inp.take_alt();
3270//                 match (self.or_else)(err.err) {
3271//                     Ok(out) => {
3272//                         inp.rewind(before);
3273//                         Ok(M::bind(|| out))
3274//                     }
3275//                     Err(new_err) => {
3276//                         inp.errors.alt = Some(Located {
3277//                             pos: err.pos,
3278//                             err: new_err,
3279//                         });
3280//                         Err(())
3281//                     }
3282//                 }
3283//             }
3284//         }
3285//     }
3286
3287//     go_extra!(O);
3288// }
3289
3290/// See [`Parser::contextual`].
3291#[derive(Copy, Clone)]
3292pub struct Contextual<A> {
3293    pub(crate) inner: A,
3294}
3295
3296impl<'src, I, O, E, A> Parser<'src, I, O, E> for Contextual<A>
3297where
3298    I: Input<'src>,
3299    E: ParserExtra<'src, I>,
3300    A: Parser<'src, I, O, E>,
3301{
3302    #[inline]
3303    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
3304        Self::go_cfg::<M>(self, inp, true)
3305    }
3306
3307    go_extra!(O);
3308}
3309
3310impl<'src, I, O, E, A> ConfigParser<'src, I, O, E> for Contextual<A>
3311where
3312    I: Input<'src>,
3313    E: ParserExtra<'src, I>,
3314    A: Parser<'src, I, O, E>,
3315{
3316    type Config = bool;
3317
3318    #[inline]
3319    fn go_cfg<M: Mode>(
3320        &self,
3321        inp: &mut InputRef<'src, '_, I, E>,
3322        cfg: Self::Config,
3323    ) -> PResult<M, O> {
3324        let before = inp.cursor();
3325        if cfg {
3326            self.inner.go::<M>(inp)
3327        } else {
3328            let err_span = inp.span_since(&before);
3329            inp.add_alt([DefaultExpected::SomethingElse], None, err_span);
3330            Err(())
3331        }
3332    }
3333}
3334
3335#[cfg(test)]
3336mod tests {
3337    use crate::prelude::*;
3338
3339    #[test]
3340    fn separated_by_at_least() {
3341        let parser = just::<_, _, extra::Default>('-')
3342            .separated_by(just(','))
3343            .at_least(3)
3344            .collect();
3345
3346        assert_eq!(parser.parse("-,-,-").into_result(), Ok(vec!['-', '-', '-']));
3347    }
3348
3349    #[test]
3350    fn separated_by_at_least_without_leading() {
3351        let parser = just::<_, _, extra::Default>('-')
3352            .separated_by(just(','))
3353            .at_least(3)
3354            .collect::<Vec<_>>();
3355
3356        // Is empty means no errors
3357        assert!(parser.parse(",-,-,-").has_errors());
3358    }
3359
3360    #[test]
3361    fn separated_by_at_least_without_trailing() {
3362        let parser = just::<_, _, extra::Default>('-')
3363            .separated_by(just(','))
3364            .at_least(3)
3365            .collect::<Vec<_>>();
3366
3367        // Is empty means no errors
3368        assert!(parser.parse("-,-,-,").has_errors());
3369    }
3370
3371    #[test]
3372    fn separated_by_at_least_with_leading() {
3373        let parser = just::<_, _, extra::Default>('-')
3374            .separated_by(just(','))
3375            .allow_leading()
3376            .at_least(3)
3377            .collect();
3378
3379        assert_eq!(
3380            parser.parse(",-,-,-").into_result(),
3381            Ok(vec!['-', '-', '-'])
3382        );
3383        assert!(parser.parse(",-,-").has_errors());
3384    }
3385
3386    #[test]
3387    fn separated_by_at_least_with_trailing() {
3388        let parser = just::<_, _, extra::Default>('-')
3389            .separated_by(just(','))
3390            .allow_trailing()
3391            .at_least(3)
3392            .collect();
3393
3394        assert_eq!(
3395            parser.parse("-,-,-,").into_result(),
3396            Ok(vec!['-', '-', '-'])
3397        );
3398        assert!(parser.parse("-,-,").has_errors());
3399    }
3400
3401    #[test]
3402    fn separated_by_leaves_last_separator() {
3403        let parser = just::<_, _, extra::Default>('-')
3404            .separated_by(just(','))
3405            .collect::<Vec<_>>()
3406            .then(just(','));
3407        assert_eq!(
3408            parser.parse("-,-,-,").into_result(),
3409            Ok((vec!['-', '-', '-'], ',')),
3410        )
3411    }
3412}