chumsky 0.12.0

A parser library for humans with powerful error recovery
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
//! Parser primitives that accept specific token patterns.
//!
//! *“These creatures you call mice, you see, they are not quite as they appear. They are merely the protrusion into
//! our dimension of vastly hyperintelligent pandimensional beings.”*
//!
//! Chumsky parsers are created by combining together smaller parsers. Right at the bottom of the pile are the parser
//! primitives, a parser developer's bread & butter. Each of these primitives are very easy to understand in isolation,
//! usually only doing one thing.
//!
//! ## The Important Ones
//!
//! - [`just`]: parses a specific input or sequence of inputs
//! - [`any`]: parses any single input
//! - [`one_of`]: parses any one of a sequence of inputs
//! - [`none_of`]: parses any input that does not appear in a sequence of inputs
//! - [`end`]: parses the end of input (i.e: if there any more inputs, this parse fails)

use super::*;

/// See [`end`].
pub struct End<I, E>(EmptyPhantom<(E, I)>);

/// A parser that accepts only the end of input.
///
/// The output type of this parser is `()`.
pub const fn end<'src, I: Input<'src>, E: ParserExtra<'src, I>>() -> End<I, E> {
    End(EmptyPhantom::new())
}

impl<I, E> Copy for End<I, E> {}
impl<I, E> Clone for End<I, E> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'src, I, E> Parser<'src, I, (), E> for End<I, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
        let before = inp.save();
        match inp.next_maybe_inner() {
            None => Ok(M::bind(|| ())),
            Some(tok) => {
                let span = inp.span_since(before.cursor());
                inp.rewind(before);
                inp.add_alt([DefaultExpected::EndOfInput], Some(tok.into()), span);
                Err(())
            }
        }
    }

    go_extra!(());
}

/// See [`empty`].
pub struct Empty<I, E>(EmptyPhantom<(E, I)>);

/// A parser that parses no inputs.
///
/// The output type of this parser is `()`.
pub const fn empty<I, E>() -> Empty<I, E> {
    Empty(EmptyPhantom::new())
}

impl<I, E> Copy for Empty<I, E> {}
impl<I, E> Clone for Empty<I, E> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'src, I, E> Parser<'src, I, (), E> for Empty<I, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, _: &mut InputRef<'src, '_, I, E>) -> PResult<M, ()> {
        Ok(M::bind(|| ()))
    }

    go_extra!(());
}

/// Configuration for [`just`], used in [`ConfigParser::configure`]
pub struct JustCfg<T> {
    seq: Option<T>,
}

impl<T> JustCfg<T> {
    /// Set the sequence to be used while parsing
    #[inline]
    pub fn seq(mut self, new_seq: T) -> Self {
        self.seq = Some(new_seq);
        self
    }
}

impl<T> Default for JustCfg<T> {
    #[inline]
    fn default() -> Self {
        JustCfg { seq: None }
    }
}

/// See [`just`].
pub struct Just<T, I, E = EmptyErr> {
    seq: T,
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, I)>,
}

impl<T: Copy, I, E> Copy for Just<T, I, E> {}
impl<T: Clone, I, E> Clone for Just<T, I, E> {
    fn clone(&self) -> Self {
        Self {
            seq: self.seq.clone(),
            phantom: EmptyPhantom::new(),
        }
    }
}

/// A parser that accepts only the given input.
///
/// The output type of this parser is `T`, the input or sequence that was provided.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let question = just::<_, _, extra::Err<Simple<char>>>('?');
///
/// assert_eq!(question.parse("?").into_result(), Ok('?'));
/// // This fails because '?' was not found
/// assert!(question.parse("!").has_errors());
/// // This fails because the parser expects an end to the input after the '?'
/// assert!(question.parse("?!").has_errors());
/// ```
pub const fn just<'src, T, I, E>(seq: T) -> Just<T, I, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    I::Token: PartialEq,
    T: OrderedSeq<'src, I::Token> + Clone,
{
    Just {
        seq,
        phantom: EmptyPhantom::new(),
    }
}

impl<'src, I, E, T> Parser<'src, I, T, E> for Just<T, I, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    I::Token: PartialEq,
    T: OrderedSeq<'src, I::Token> + Clone,
{
    #[doc(hidden)]
    #[cfg(feature = "debug")]
    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
        debug::NodeInfo::Just(self.seq.seq_info(scope))
    }

    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, T> {
        Self::go_cfg::<M>(self, inp, JustCfg::default())
    }

    go_extra!(T);
}

impl<'src, I, E, T> ConfigParser<'src, I, T, E> for Just<T, I, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    I::Token: PartialEq,
    T: OrderedSeq<'src, I::Token> + Clone,
{
    type Config = JustCfg<T>;

    #[inline]
    fn go_cfg<M: Mode>(
        &self,
        inp: &mut InputRef<'src, '_, I, E>,
        cfg: Self::Config,
    ) -> PResult<M, T> {
        let seq = cfg.seq.as_ref().unwrap_or(&self.seq);
        for next in seq.seq_iter() {
            let before = inp.save();
            match inp.next_maybe_inner() {
                Some(tok) if next.borrow() == tok.borrow() => {}
                found => {
                    let span = inp.span_since(before.cursor());
                    inp.rewind(before);
                    inp.add_alt(
                        [DefaultExpected::Token(T::to_maybe_ref(next))],
                        found.map(|f| f.into()),
                        span,
                    );
                    return Err(());
                }
            }
        }

        Ok(M::bind(|| seq.clone()))
    }
}

/// See [`one_of`].
pub struct OneOf<T, I, E> {
    seq: T,
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, I)>,
}

impl<T: Copy, I, E> Copy for OneOf<T, I, E> {}
impl<T: Clone, I, E> Clone for OneOf<T, I, E> {
    fn clone(&self) -> Self {
        Self {
            seq: self.seq.clone(),
            phantom: EmptyPhantom::new(),
        }
    }
}

/// A parser that accepts one of a sequence of specific inputs.
///
/// The output type of this parser is `I`, the input that was found.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let digits = one_of::<_, _, extra::Err<Simple<char>>>("0123456789")
///     .repeated()
///     .at_least(1)
///     .collect::<String>();
///
/// assert_eq!(digits.parse("48791").into_result(), Ok("48791".to_string()));
/// assert!(digits.parse("421!53").has_errors());
/// ```
pub const fn one_of<'src, T, I, E>(seq: T) -> OneOf<T, I, E>
where
    I: ValueInput<'src>,
    E: ParserExtra<'src, I>,
    I::Token: PartialEq,
    T: Seq<'src, I::Token>,
{
    OneOf {
        seq,
        phantom: EmptyPhantom::new(),
    }
}

impl<'src, I, E, T> Parser<'src, I, I::Token, E> for OneOf<T, I, E>
where
    I: ValueInput<'src>,
    E: ParserExtra<'src, I>,
    I::Token: PartialEq,
    T: Seq<'src, I::Token>,
{
    #[doc(hidden)]
    #[cfg(feature = "debug")]
    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
        debug::NodeInfo::OneOf(self.seq.seq_info(scope))
    }

    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, I::Token> {
        let before = inp.save();
        match inp.next_inner() {
            #[allow(suspicious_double_ref_op)] // Is this a clippy bug?
            Some(tok) if self.seq.contains(tok.borrow()) => Ok(M::bind(|| tok)),
            found => {
                let err_span = inp.span_since(before.cursor());
                inp.rewind(before);
                inp.add_alt(
                    self.seq
                        .seq_iter()
                        .map(|e| DefaultExpected::Token(T::to_maybe_ref(e))),
                    found.map(|f| f.into()),
                    err_span,
                );
                Err(())
            }
        }
    }

    go_extra!(I::Token);
}

/// See [`none_of`].
pub struct NoneOf<T, I, E> {
    seq: T,
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, I)>,
}

impl<T: Copy, I, E> Copy for NoneOf<T, I, E> {}
impl<T: Clone, I, E> Clone for NoneOf<T, I, E> {
    fn clone(&self) -> Self {
        Self {
            seq: self.seq.clone(),
            phantom: EmptyPhantom::new(),
        }
    }
}

/// A parser that accepts any input that is *not* in a sequence of specific inputs.
///
/// The output type of this parser is `I`, the input that was found.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let string = one_of::<_, _, extra::Err<Simple<char>>>("\"'")
///     .ignore_then(none_of("\"'").repeated().collect::<String>())
///     .then_ignore(one_of("\"'"));
///
/// assert_eq!(string.parse("'hello'").into_result(), Ok("hello".to_string()));
/// assert_eq!(string.parse("\"world\"").into_result(), Ok("world".to_string()));
/// assert!(string.parse("\"421!53").has_errors());
/// ```
pub const fn none_of<'src, T, I, E>(seq: T) -> NoneOf<T, I, E>
where
    I: ValueInput<'src>,
    E: ParserExtra<'src, I>,
    I::Token: PartialEq,
    T: Seq<'src, I::Token>,
{
    NoneOf {
        seq,
        phantom: EmptyPhantom::new(),
    }
}

impl<'src, I, E, T> Parser<'src, I, I::Token, E> for NoneOf<T, I, E>
where
    I: ValueInput<'src>,
    E: ParserExtra<'src, I>,
    I::Token: PartialEq,
    T: Seq<'src, I::Token>,
{
    #[doc(hidden)]
    #[cfg(feature = "debug")]
    fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
        debug::NodeInfo::NoneOf(self.seq.seq_info(scope))
    }

    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, I::Token> {
        let before = inp.save();
        match inp.next_inner() {
            // #[allow(suspicious_double_ref_op)] // Is this a clippy bug?
            Some(tok) if !self.seq.contains(tok.borrow()) => Ok(M::bind(|| tok)),
            found => {
                let err_span = inp.span_since(before.cursor());
                inp.rewind(before);
                inp.add_alt(
                    [DefaultExpected::SomethingElse],
                    found.map(|f| f.into()),
                    err_span,
                );
                Err(())
            }
        }
    }

    go_extra!(I::Token);
}

/// See [`custom`].
pub struct Custom<F, I, O, E> {
    f: F,
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, O, I)>,
}

impl<F: Copy, I, O, E> Copy for Custom<F, I, O, E> {}
impl<F: Clone, I, O, E> Clone for Custom<F, I, O, E> {
    fn clone(&self) -> Self {
        Self {
            f: self.f.clone(),
            phantom: EmptyPhantom::new(),
        }
    }
}

/// Declare a parser that uses custom imperative parsing logic.
///
/// This is useful when a particular parser is difficult or impossible to express with chumsky's built-in combinators
/// alone. For example, custom context-sensitive logic can often be implemented using a custom parser and then
/// integrated seamlessly into a more 'vanilla' chumsky parser.
///
/// See the [`InputRef`] docs for information about what operations custom parsers can perform.
///
/// If you are building a library of custom parsers, it is recommended to make use of the [`extension`] API.
///
/// # Example
///
/// ```
/// # use chumsky::{prelude::*, error::{Simple, LabelError}};
///
/// let question = custom::<_, &str, _, extra::Err<Simple<char>>>(|inp| {
///     let before = inp.cursor();
///     match inp.next() {
///         Some('?') => Ok(()),
///         found => Err(Simple::new(found.map(Into::into), inp.span_since(&before))),
///     }
/// });
///
/// assert_eq!(question.parse("?").into_result(), Ok(()));
/// assert!(question.parse("!").has_errors());
/// ```
pub const fn custom<'src, F, I, O, E>(f: F) -> Custom<F, I, O, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    F: Fn(&mut InputRef<'src, '_, I, E>) -> Result<O, E::Error>,
{
    Custom {
        f,
        phantom: EmptyPhantom::new(),
    }
}

impl<'src, I, O, E, F> Parser<'src, I, O, E> for Custom<F, I, O, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    F: Fn(&mut InputRef<'src, '_, I, E>) -> Result<O, E::Error>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        let before = inp.cursor();
        match (self.f)(inp) {
            Ok(out) => Ok(M::bind(|| out)),
            Err(err) => {
                inp.add_alt_err(&before.inner, err);
                Err(())
            }
        }
    }

    go_extra!(O);
}

/// See [`select!`].
pub struct Select<F, I, O, E> {
    filter: F,
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, O, I)>,
}

impl<F: Copy, I, O, E> Copy for Select<F, I, O, E> {}
impl<F: Clone, I, O, E> Clone for Select<F, I, O, E> {
    fn clone(&self) -> Self {
        Self {
            filter: self.filter.clone(),
            phantom: EmptyPhantom::new(),
        }
    }
}

/// See [`select!`].
pub const fn select<'src, F, I, O, E>(filter: F) -> Select<F, I, O, E>
where
    I: Input<'src>,
    I::Token: Clone + 'src,
    E: ParserExtra<'src, I>,
    F: Fn(I::Token, &mut MapExtra<'src, '_, I, E>) -> Option<O>,
{
    Select {
        filter,
        phantom: EmptyPhantom::new(),
    }
}

impl<'src, I, O, E, F> Parser<'src, I, O, E> for Select<F, I, O, E>
where
    I: Input<'src>,
    I::Token: Clone + 'src,
    E: ParserExtra<'src, I>,
    F: Fn(I::Token, &mut MapExtra<'src, '_, I, E>) -> Option<O>,
{
    #[doc(hidden)]
    #[cfg(feature = "debug")]
    fn node_info(&self, _scope: &mut debug::NodeScope) -> debug::NodeInfo {
        debug::NodeInfo::Filter(Box::new(debug::NodeInfo::Any))
    }

    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        let before = inp.save();
        let next = inp.next_maybe_inner();
        let found = match next {
            Some(tok) => {
                match (self.filter)(
                    tok.borrow().clone(),
                    &mut MapExtra::new(before.cursor(), inp),
                ) {
                    Some(out) => return Ok(M::bind(|| out)),
                    None => Some(tok.into()),
                }
            }
            found => found.map(|f| f.into()),
        };
        let err_span = inp.span_since(before.cursor());
        inp.rewind(before);
        inp.add_alt([DefaultExpected::SomethingElse], found, err_span);
        Err(())
    }

    go_extra!(O);
}

/// See [`select_ref!`].
pub struct SelectRef<F, I, O, E> {
    filter: F,
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, O, I)>,
}

impl<F: Copy, I, O, E> Copy for SelectRef<F, I, O, E> {}
impl<F: Clone, I, O, E> Clone for SelectRef<F, I, O, E> {
    fn clone(&self) -> Self {
        Self {
            filter: self.filter.clone(),
            phantom: EmptyPhantom::new(),
        }
    }
}

/// See [`select_ref!`].
pub const fn select_ref<'src, F, I, O, E>(filter: F) -> SelectRef<F, I, O, E>
where
    I: BorrowInput<'src>,
    I::Token: 'src,
    E: ParserExtra<'src, I>,
    F: Fn(&'src I::Token, &mut MapExtra<'src, '_, I, E>) -> Option<O>,
{
    SelectRef {
        filter,
        phantom: EmptyPhantom::new(),
    }
}

impl<'src, I, O, E, F> Parser<'src, I, O, E> for SelectRef<F, I, O, E>
where
    I: BorrowInput<'src>,
    I::Token: 'src,
    E: ParserExtra<'src, I>,
    F: Fn(&'src I::Token, &mut MapExtra<'src, '_, I, E>) -> Option<O>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        let before = inp.save();
        let next = inp.next_ref_inner();
        let found = match next {
            Some(tok) => match (self.filter)(tok, &mut MapExtra::new(before.cursor(), inp)) {
                Some(out) => return Ok(M::bind(|| out)),
                None => Some(tok.into()),
            },
            found => found.map(|f| f.into()),
        };
        let err_span = inp.span_since(before.cursor());
        inp.rewind(before);
        inp.add_alt([DefaultExpected::SomethingElse], found, err_span);
        Err(())
    }

    go_extra!(O);
}

/// See [`any`].
pub struct Any<I, E> {
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, I)>,
}

impl<I, E> Copy for Any<I, E> {}
impl<I, E> Clone for Any<I, E> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'src, I, E> Parser<'src, I, I::Token, E> for Any<I, E>
where
    I: ValueInput<'src>,
    E: ParserExtra<'src, I>,
{
    #[doc(hidden)]
    #[cfg(feature = "debug")]
    fn node_info(&self, _scope: &mut debug::NodeScope) -> debug::NodeInfo {
        debug::NodeInfo::Any
    }

    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, I::Token> {
        let before = inp.save();
        match inp.next_inner() {
            Some(tok) => Ok(M::bind(|| tok)),
            found => {
                let err_span = inp.span_since(before.cursor());
                inp.rewind(before);
                inp.add_alt([DefaultExpected::Any], found.map(|f| f.into()), err_span);
                Err(())
            }
        }
    }

    go_extra!(I::Token);
}

/// A parser that accepts any input (but not the end of input).
///
/// The output type of this parser is `I::Token`, the input that was found.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let any = any::<_, extra::Err<Simple<char>>>();
///
/// assert_eq!(any.parse("a").into_result(), Ok('a'));
/// assert_eq!(any.parse("7").into_result(), Ok('7'));
/// assert_eq!(any.parse("\t").into_result(), Ok('\t'));
/// assert!(any.parse("").has_errors());
/// ```
pub const fn any<'src, I: Input<'src>, E: ParserExtra<'src, I>>() -> Any<I, E> {
    Any {
        phantom: EmptyPhantom::new(),
    }
}

/// See [`any_ref`].
pub struct AnyRef<I, E> {
    #[allow(dead_code)]
    phantom: EmptyPhantom<(E, I)>,
}

impl<I, E> Copy for AnyRef<I, E> {}
impl<I, E> Clone for AnyRef<I, E> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'src, I, E> Parser<'src, I, &'src I::Token, E> for AnyRef<I, E>
where
    I: BorrowInput<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, &'src I::Token> {
        let before = inp.save();
        match inp.next_ref_inner() {
            Some(tok) => Ok(M::bind(|| tok)),
            found => {
                let err_span = inp.span_since(before.cursor());
                inp.rewind(before);
                inp.add_alt([DefaultExpected::Any], found.map(|f| f.into()), err_span);
                Err(())
            }
        }
    }

    go_extra!(&'src I::Token);
}

/// A parser that accepts any input (but not the end of input).
///
/// The output type of this parser is `&'src I::Token`, the input that was found.
///
/// This function is the borrowing equivalent of [any]. Where possible, it's recommended to use [any] instead.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let any_ref_0 = any_ref::<_, extra::Err<Simple<char>>>();
/// let any_ref_1 = any_ref::<_, extra::Err<Simple<char>>>();
///
/// assert_eq!(any_ref_1.parse(&['a'; 1]).into_result(), Ok(&'a'));
/// assert_eq!(any_ref_1.parse(&['7'; 1]).into_result(), Ok(&'7'));
/// assert_eq!(any_ref_1.parse(&['\t'; 1]).into_result(), Ok(&'\t'));
/// assert!(any_ref_0.parse(&[]).has_errors());
/// ```
pub const fn any_ref<'src, I: BorrowInput<'src>, E: ParserExtra<'src, I>>() -> AnyRef<I, E> {
    AnyRef {
        phantom: EmptyPhantom::new(),
    }
}

/// See [`map_ctx`].
pub struct MapCtx<A, AE, F, E> {
    pub(crate) parser: A,
    pub(crate) mapper: F,
    #[allow(dead_code)]
    pub(crate) phantom: EmptyPhantom<(AE, E)>,
}

impl<A: Copy, AE, F: Copy, E> Copy for MapCtx<A, AE, F, E> {}
impl<A: Clone, AE, F: Clone, E> Clone for MapCtx<A, AE, F, E> {
    fn clone(&self) -> Self {
        MapCtx {
            parser: self.parser.clone(),
            mapper: self.mapper.clone(),
            phantom: EmptyPhantom::new(),
        }
    }
}

impl<'src, I, O, E, EI, A, F> Parser<'src, I, O, E> for MapCtx<A, EI, F, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    EI: ParserExtra<'src, I, Error = E::Error, State = E::State>,
    A: Parser<'src, I, O, EI>,
    F: Fn(&E::Context) -> EI::Context,
    EI::Context: 'src,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        inp.with_ctx(&(self.mapper)(inp.ctx()), |inp| self.parser.go::<M>(inp))
    }

    go_extra!(O);
}

/// Apply a mapping function to the context of this parser.
///
/// Note that this combinator will behave differently from all other maps, in terms of which
/// parsers it effects - while other maps apply to the output of the parser, and thus read left-to-right, this one
/// applies to the _input_ of the parser, and as such applies right-to-left.
///
/// More technically, if all combinators form a 'tree' of parsers, where each node executes
/// its children in turn, normal maps apply up the tree. This means a parent mapper gets the
/// result of its children, applies the map, then passes the new result to its parent. This map,
/// however, applies down the tree. Context is provided from the parent,
/// such as [`Parser::ignore_with_ctx`] and [`Parser::then_with_ctx`],
/// and gets altered before being provided to the children.
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
///
/// let upper = just::<u8, &[u8], extra::Context<u8>>(b'0').configure(|cfg, ctx: &u8| cfg.seq(*ctx));
///
/// let inc = one_of::<_, _, extra::Default>(b'a'..=b'z')
///     .ignore_with_ctx(map_ctx::<_, u8, &[u8], extra::Context<u8>, extra::Context<u8>, _>(|c: &u8| c.to_ascii_uppercase(), upper))
///     .to_slice()
///     .repeated()
///     .at_least(1)
///     .collect::<Vec<_>>();
///
/// assert_eq!(inc.parse(b"aAbB" as &[_]).into_result(), Ok(vec![b"aA" as &[_], b"bB"]));
/// assert!(inc.parse(b"aB").has_errors());
/// ```
/// You can not only change the value of the context but also change the type entirely:
/// ```
/// # use chumsky::{
///         extra,
///         primitive::{just, map_ctx},
///         ConfigParser, Parser,
/// };
///
/// fn string_ctx<'src>() -> impl Parser<'src, &'src str, (), extra::Context<String>> {
///     just("".to_owned())
///         .configure(|cfg, s: &String| cfg.seq(s.clone()))
///         .ignored()
/// }
///
/// fn usize_ctx<'src>() -> impl Parser<'src, &'src str, (), extra::Context<usize>> {
///     map_ctx::<_, _, _, extra::Context<usize>, extra::Context<String>, _>(
///        |num: &usize| num.to_string(),
///        string_ctx(),
///     )
/// }
///
/// fn specific_usize<'src>(num: usize) -> impl Parser<'src, &'src str, ()> {
///     usize_ctx().with_ctx(num)
/// }
/// assert!(!specific_usize(10).parse("10").has_errors());
/// ```
pub const fn map_ctx<'src, P, OP, I, E, EP, F>(mapper: F, parser: P) -> MapCtx<P, EP, F, E>
where
    F: Fn(&E::Context) -> EP::Context,
    I: Input<'src>,
    P: Parser<'src, I, OP, EP>,
    E: ParserExtra<'src, I>,
    EP: ParserExtra<'src, I>,
    EP::Context: 'src,
{
    MapCtx {
        parser,
        mapper,
        phantom: EmptyPhantom::new(),
    }
}

/// See [`fn@todo`].
pub struct Todo<I, O, E> {
    location: Location<'static>,
    #[allow(dead_code)]
    phantom: EmptyPhantom<(O, E, I)>,
}

impl<I, O, E> Copy for Todo<I, O, E> {}
impl<I, O, E> Clone for Todo<I, O, E> {
    fn clone(&self) -> Self {
        *self
    }
}

/// A parser that can be used wherever you need to implement a parser later.
///
/// This parser is analogous to the [`todo!`] and [`unimplemented!`] macros, but will produce a panic when used to
/// parse input, not immediately when invoked.
///
/// This function is useful when developing your parser, allowing you to prototype and run parts of your parser without
/// committing to implementing the entire thing immediately.
///
/// The output type of this parser is whatever you want it to be: it'll never produce output!
///
/// # Examples
///
/// ```should_panic
/// # use chumsky::prelude::*;
/// let int = just::<_, _, extra::Err<Simple<char>>>("0x").ignore_then(todo())
///     .or(just("0b").ignore_then(text::digits(2).to_slice()))
///     .or(text::int(10).to_slice());
///
/// // Decimal numbers are parsed
/// assert_eq!(int.parse("12").into_result(), Ok("12"));
/// // Binary numbers are parsed
/// assert_eq!(int.parse("0b00101").into_result(), Ok("00101"));
/// // Parsing hexidecimal numbers results in a panic because the parser is unimplemented
/// int.parse("0xd4");
/// ```
#[track_caller]
pub fn todo<'src, I: Input<'src>, O, E: ParserExtra<'src, I>>() -> Todo<I, O, E> {
    Todo {
        location: *Location::caller(),
        phantom: EmptyPhantom::new(),
    }
}

impl<'src, I, O, E> Parser<'src, I, O, E> for Todo<I, O, E>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, _inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        todo!(
            "Attempted to use an unimplemented parser at {}",
            self.location
        )
    }

    go_extra!(O);
}

/// See [`choice`].
#[derive(Copy, Clone)]
pub struct Choice<T> {
    parsers: T,
}

/// Parse using a tuple of many parsers, producing the output of the first to successfully parse.
///
/// This primitive has a twofold improvement over a chain of [`Parser::or`] calls:
///
/// - Rust's trait solver seems to resolve the [`Parser`] impl for this type much faster, significantly reducing
///   compilation times.
///
/// - Parsing is likely a little faster in some cases because the resulting parser is 'less careful' about error
///   routing, and doesn't perform the same fine-grained error prioritization that [`Parser::or`] does.
///
/// These qualities make this parser ideal for lexers.
///
/// The output type of this parser is the output type of the inner parsers.
///
/// # Examples
///
/// ```
/// # use chumsky::prelude::*;
/// #[derive(Clone, Debug, PartialEq)]
/// enum Token<'src> {
///     If,
///     For,
///     While,
///     Fn,
///     Int(u64),
///     Ident(&'src str),
/// }
///
/// let tokens = choice((
///     text::ascii::keyword::<_, _, extra::Err<Simple<char>>>("if").to(Token::If),
///     text::ascii::keyword("for").to(Token::For),
///     text::ascii::keyword("while").to(Token::While),
///     text::ascii::keyword("fn").to(Token::Fn),
///     text::int(10).from_str().unwrapped().map(Token::Int),
///     text::ascii::ident().map(Token::Ident),
/// ))
///     .padded()
///     .repeated()
///     .collect::<Vec<_>>();
///
/// use Token::*;
/// assert_eq!(
///     tokens.parse("if 56 for foo while 42 fn bar").into_result(),
///     Ok(vec![If, Int(56), For, Ident("foo"), While, Int(42), Fn, Ident("bar")]),
/// );
/// ```
pub const fn choice<T>(parsers: T) -> Choice<T> {
    Choice { parsers }
}

macro_rules! impl_choice_for_tuple {
    () => {};
    ($head:ident $($X:ident)*) => {
        impl_choice_for_tuple!($($X)*);
        impl_choice_for_tuple!(~ $head $($X)*);
    };
    (~ $Head:ident $($X:ident)+) => {
        #[allow(unused_variables, non_snake_case)]
        impl<'src, I, E, $Head, $($X),*, O> Parser<'src, I, O, E> for Choice<($Head, $($X,)*)>
        where
            I: Input<'src>,
            E: ParserExtra<'src, I>,
            $Head: Parser<'src, I, O, E>,
            $($X: Parser<'src, I, O, E>),*
        {
            #[doc(hidden)]
            #[cfg(feature = "debug")]
            fn node_info(&self, scope: &mut debug::NodeScope) -> debug::NodeInfo {
                let Choice { parsers: ($Head, $($X,)*), .. } = self;
                debug::NodeInfo::Choice(vec![$Head.node_info(scope), $($X.node_info(scope)),*])
            }

            #[inline]
            fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
                let before = inp.save();

                let Choice { parsers: ($Head, $($X,)*), .. } = self;

                match $Head.go::<M>(inp) {
                    Ok(out) => return Ok(out),
                    Err(()) => inp.rewind(before.clone()),
                }

                $(
                    match $X.go::<M>(inp) {
                        Ok(out) => return Ok(out),
                        Err(()) => inp.rewind(before.clone()),
                    }
                )*

                Err(())
            }

            go_extra!(O);
        }
    };
    (~ $Head:ident) => {
        impl<'src, I, E, $Head, O> Parser<'src, I, O, E> for Choice<($Head,)>
        where
            I: Input<'src>,
            E: ParserExtra<'src, I>,
            $Head:  Parser<'src, I, O, E>,
        {
            #[inline]
            fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
                self.parsers.0.go::<M>(inp)
            }

            go_extra!(O);
        }
    };
}

impl_choice_for_tuple!(A_ B_ C_ D_ E_ F_ G_ H_ I_ J_ K_ L_ M_ N_ O_ P_ Q_ R_ S_ T_ U_ V_ W_ X_ Y_ Z_);

impl<'src, A, I, O, E> Parser<'src, I, O, E> for Choice<&[A]>
where
    A: Parser<'src, I, O, E>,
    I: Input<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        if self.parsers.is_empty() {
            let offs = inp.cursor();
            let err_span = inp.span_since(&offs);
            inp.add_alt([], None, err_span);
            Err(())
        } else {
            let before = inp.save();
            for parser in self.parsers.iter() {
                inp.rewind(before.clone());
                if let Ok(out) = parser.go::<M>(inp) {
                    return Ok(out);
                }
            }
            Err(())
        }
    }

    go_extra!(O);
}

impl<'src, A, I, O, E> Parser<'src, I, O, E> for Choice<Vec<A>>
where
    A: Parser<'src, I, O, E>,
    I: Input<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        choice(&self.parsers[..]).go::<M>(inp)
    }
    go_extra!(O);
}

impl<'src, A, I, O, E, const N: usize> Parser<'src, I, O, E> for Choice<[A; N]>
where
    A: Parser<'src, I, O, E>,
    I: Input<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, O> {
        choice(&self.parsers[..]).go::<M>(inp)
    }
    go_extra!(O);
}

/// See [`group`].
#[derive(Copy, Clone)]
pub struct Group<T> {
    parsers: T,
}

/// Parse using a tuple of many parsers, producing a tuple of outputs if all successfully parse,
/// otherwise returning an error if any parsers fail.
///
/// This parser is to [`Parser::then`] as [`choice`] is to [`Parser::or`]
pub const fn group<T>(parsers: T) -> Group<T> {
    Group { parsers }
}

impl<'src, I, O, E, P, const N: usize> Parser<'src, I, [O; N], E> for Group<[P; N]>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    P: Parser<'src, I, O, E>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, [O; N]> {
        let mut arr: [MaybeUninit<_>; N] = MaybeUninitExt::uninit_array();
        self.parsers
            .iter()
            .zip(arr.iter_mut())
            .try_for_each(|(p, res)| {
                res.write(p.go::<M>(inp)?);
                Ok(())
            })?;
        // SAFETY: We guarantee that all parers succeeded and as such all items have been initialized
        //         if we reach this point
        Ok(M::array(unsafe { MaybeUninitExt::array_assume_init(arr) }))
    }

    go_extra!([O; N]);
}

macro_rules! flatten_map {
    // map a single element into a 1-tuple
    (<$M:ident> $head:ident) => {
        $M::map(
            $head,
            |$head| ($head,),
        )
    };
    // combine two elements into a 2-tuple
    (<$M:ident> $head1:ident $head2:ident) => {
        $M::combine(
            $head1,
            $head2,
            |$head1, $head2| ($head1, $head2),
        )
    };
    // combine and flatten n-tuples from recursion
    (<$M:ident> $head:ident $($X:ident)+) => {
        $M::combine(
            $head,
            flatten_map!(
                <$M>
                $($X)+
            ),
            |$head, ($($X),+)| ($head, $($X),+),
        )
    };
}

macro_rules! impl_group_for_tuple {
    () => {};
    ($head:ident $ohead:ident $($X:ident $O:ident)*) => {
        impl_group_for_tuple!($($X $O)*);
        impl_group_for_tuple!(~ $head $ohead $($X $O)*);
    };
    (~ $($X:ident $O:ident)*) => {
        #[allow(unused_variables, non_snake_case)]
        impl<'src, I, E, $($X),*, $($O),*> Parser<'src, I, ($($O,)*), E> for Group<($($X,)*)>
        where
            I: Input<'src>,
            E: ParserExtra<'src, I>,
            $($X: Parser<'src, I, $O, E>),*
        {
            #[inline]
            fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ($($O,)*)> {
                let Group { parsers: ($($X,)*) } = self;

                $(
                    let $X = $X.go::<M>(inp)?;
                )*

                Ok(flatten_map!(<M> $($X)*))
            }

            go_extra!(($($O,)*));
        }
    };
}

impl_group_for_tuple! {
    A_ OA
    B_ OB
    C_ OC
    D_ OD
    E_ OE
    F_ OF
    G_ OG
    H_ OH
    I_ OI
    J_ OJ
    K_ OK
    L_ OL
    M_ OM
    N_ ON
    O_ OO
    P_ OP
    Q_ OQ
    R_ OR
    S_ OS
    T_ OT
    U_ OU
    V_ OV
    W_ OW
    X_ OX
    Y_ OY
    Z_ OZ
}

/// See [`set`].
#[derive(Copy, Clone)]
pub struct Set<T> {
    parsers: T,
}

/// Parse using a tuple of parsers in any order, producing the output of the parser set in the provided order.
///
/// The output type of this parser is a tuple of the output types of the inner parsers.
///
/// All parsers must successfully parse.
///
/// Parsers are always tried in the provided order, which means that most specific parsers must be
/// provided first or they might never match. In other words, if two parsers match the same item,
/// the `set`'s input must containt this item twice for the `set` to be successful.
///
/// Be careful! This combinator is O(n^2), which means that in the worst case you could slow down parsing with
/// a lot of parser calls. The worst case happens when all items are present but in the reverse
/// order compared to the list of parsers. To mitigate this you should order your parsers in the
/// same order input usually happens. And you should avoid having too many parsers in the set.
///
/// Parsers that match without making progress (like `empty()` or `something.or_not()`) are applied
/// last to make sure they have no better alternative.
///
/// This means that you can make a parser optional by adding a call to `.or_not()` to it.
///
/// # Examples
///
/// ```
/// # use chumsky::prelude::*;
/// let options = set((
///     just::<_, _, extra::Err<Simple<char>>>("apple\n"),
///     just("banana\n"),
///     just("carrot\n").or_not(),
/// ));
///
/// assert_eq!(
///     options.parse("banana\napple\n").into_result(),
///     Ok(("apple\n", "banana\n", None)),
/// );
/// ```
pub const fn set<T>(parsers: T) -> Set<T> {
    Set { parsers }
}

fn go_or_finish<'src, O, I, E, P, M>(
    item: &mut Option<M::Output<O>>,
    parser: &P,
    inp: &mut InputRef<'src, '_, I, E>,
) -> PResult<M, ()>
where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    P: Parser<'src, I, O, E>,
    M: Mode,
{
    if item.is_none() {
        match parser.go::<M>(inp) {
            Ok(out) => {
                *item = Some(out);
            }
            Err(()) => {
                return Err(());
            }
        }
    }
    Ok(M::bind(|| ()))
}

fn go_or_rewind<'src, O, I, E, P, M>(
    item: &mut Option<M::Output<O>>,
    parser: &P,
    inp: &mut InputRef<'src, '_, I, E>,
) where
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    P: Parser<'src, I, O, E>,
    M: Mode,
{
    if item.is_none() {
        let save_before = inp.save();
        let pos_before = inp.cursor();
        match parser.go::<M>(inp) {
            Ok(out) => {
                if pos_before == inp.cursor() {
                    inp.rewind(save_before.clone());
                } else {
                    *item = Some(out);
                }
            }
            Err(()) => inp.rewind(save_before.clone()),
        }
    }
}

macro_rules! impl_set_for_tuple {
    () => {};
    ($head_1:ident $head_2:ident $head_3:ident $($X:ident)*) => {
        impl_set_for_tuple!($($X)*);
        impl_set_for_tuple!(~ $head_1 $head_2 $head_3 $($X)*);
    };
    (~ $($O:ident $P:ident $I:ident)+) => {
        #[allow(unused_variables, non_snake_case)]
        impl<'src, I, E, $($P),*, $($O,)*> Parser<'src, I, ($($O,)*), E> for Set<($($P,)*)>
        where
            I: Input<'src>,
            E: ParserExtra<'src, I>,
            $($P: Parser<'src, I, $O, E>),*
        {
            #[inline]
            fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, ($($O,)*)> {
                let Set { parsers: ($($P,)*), .. } = self;
                $( let mut $I: Option<M::Output<$O>> = None; )*

                // first iterate until there are no progress
                loop {
                    let start = inp.cursor();
                    $( go_or_rewind::<_, _, _, _, M>(&mut $I, $P, inp); )*
                    // none matched during this loop
                    if start == inp.cursor() {
                        break;
                    }
                }

                // Then a final iteration that matches remaining empty parsers
                $( go_or_finish::<_, _, _, _, M>(&mut $I, $P, inp)?; )*

                // unwrap is ok since we matched all items in the set exactly once
                $( let $I = $I.unwrap(); )*
                Ok(flatten_map!(<M> $($I)*))
            }

            go_extra!(($($O,)*));
        }
    };
}

impl_set_for_tuple!(A1 A2 A3 B1 B2 B3 C1 C2 C3 D1 D2 D3 E1 E2 E3 F1 F2 F3 G1 G2 G3 H1 H2 H3 I1 I2 I3 J1 J2 J3 K1 K2 K3 L1 L2 L3 M1 M2 M3 N1 N2 N3 O1 O2 O3 P1 P2 P3 Q1 Q2 Q3 R1 R2 R3 S1 S2 S3 T1 T2 T3 U1 U2 U3 V1 V2 V3 W1 W2 W3 X1 X2 X3 Y1 Y2 Y3 Z1 Z2 Z3);

impl<'src, P, I, O, E> Parser<'src, I, Vec<O>, E> for Set<Vec<P>>
where
    P: Parser<'src, I, O, E>,
    I: Input<'src>,
    E: ParserExtra<'src, I>,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, Vec<O>> {
        let mut tmp = self
            .parsers
            .iter()
            .map(|_| None)
            .collect::<Vec<Option<M::Output<O>>>>();

        // first iterate until there are no progress
        loop {
            let start = inp.cursor();
            for (i, parser) in self.parsers.iter().enumerate() {
                go_or_rewind::<_, _, _, _, M>(&mut tmp[i], parser, inp);
            }
            // none matched during this loop
            if start == inp.cursor() {
                break;
            }
        }

        // Then a final iteration that matches remaining empty parsers
        for (i, parser) in self.parsers.iter().enumerate() {
            go_or_finish::<_, _, _, _, M>(&mut tmp[i], parser, inp)?;
        }

        // unwrap is ok since we matched all items in the se
        let mut result = M::bind(|| Vec::new());
        tmp.into_iter()
            .for_each(|x| M::combine_mut(&mut result, x.unwrap(), |result, x| result.push(x)));
        Ok(result)
    }

    go_extra!(Vec<O>);
}

impl<'src, P, I, O, E, const N: usize> Parser<'src, I, [O; N], E> for Set<[P; N]>
where
    P: Parser<'src, I, O, E>,
    I: Input<'src>,
    E: ParserExtra<'src, I>,
    // remove this requirement when MSRV > 1.80
    O: Copy,
{
    #[inline]
    fn go<M: Mode>(&self, inp: &mut InputRef<'src, '_, I, E>) -> PResult<M, [O; N]> {
        // Replace this when MRSV > 1.80
        //let mut tmp: [Option<M::Output<O>>; N] = [ const { None }; N];
        let mut tmp: [Option<O>; N] = [None; N];

        // first iterate until there are no progress
        loop {
            let start = inp.cursor();
            for (i, parser) in self.parsers.iter().enumerate() {
                // Replace this when MRSV > 1.80
                //go_or_rewind::<_, _, _, _, M>(&mut tmp[i], parser, inp);
                go_or_rewind::<_, _, _, _, Emit>(&mut tmp[i], parser, inp);
            }
            // none matched during this loop
            if start == inp.cursor() {
                break;
            }
        }

        // Then a final iteration that matches remaining empty parsers
        for (i, parser) in self.parsers.iter().enumerate() {
            // Replace this when MRSV > 1.80
            //go_or_finish::<_, _, _, _, M>(&mut tmp[i], parser, inp)?;
            go_or_finish::<_, _, _, _, Emit>(&mut tmp[i], parser, inp)?;
        }

        // unwrap is ok since we matched all items in the se
        // Replace this when MRSV > 1.80
        //Ok(M::array( tmp.map(|x| x.unwrap()) ))
        Ok(M::bind(|| tmp.map(|x| x.unwrap())))
    }

    go_extra!([O; N]);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn set_parser() {
        fn just(s: &str) -> Just<&str, &str, extra::Err<EmptyErr>> {
            super::just(s)
        }

        // test ordering
        let parser = set((just("abc"), just("def"), just("ijk")));
        assert_eq!(
            parser.parse("ijkdefabc").into_result(),
            Ok(("abc", "def", "ijk")),
        );
        assert_eq!(
            parser.parse("abcdefijk").into_result(),
            Ok(("abc", "def", "ijk")),
        );

        // test inclusion
        let parser = set((choice((just("abc"), just("def"))), just("abc")));
        assert_eq!(parser.parse("defabc").into_result(), Ok(("def", "abc")),);
        let parser = set((choice((just("abc"), just("def"))), just("abc")));
        assert!(parser.parse("abcdef").into_result().is_err());

        // test optionals
        let parser = set((
            just("abc").or_not(),
            just("def").or_not(),
            just("ijk").or_not(),
        ));
        assert_eq!(
            parser.parse("ijkdefabc").into_result(),
            Ok((Some("abc"), Some("def"), Some("ijk"))),
        );
        assert_eq!(
            parser.parse("ijkabc").into_result(),
            Ok((Some("abc"), None, Some("ijk"))),
        );
        assert_eq!(parser.parse("").into_result(), Ok((None, None, None)),);

        // test types
        let parser = set(vec![just("abc"), just("def"), just("ijk")]);
        assert_eq!(
            parser.parse("ijkdefabc").into_result(),
            Ok(vec!["abc", "def", "ijk"]),
        );
        let parser = set([just("abc"), just("def"), just("ijk")]);
        assert_eq!(
            parser.parse("ijkdefabc").into_result(),
            Ok(["abc", "def", "ijk"]),
        );
    }
}