minparser 0.13.4

Simple parsing functions
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
/*
 * Minparser Simple parsing functions
 *
 * Copyright (C) 2024-2026 Paolo De Donato
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
//! Additional parsing strategies.
//!
//! Most of the objects provided here deals with repetitions, in particular [`Repeat`], 
//! [`RepeatAny`], [`LazyRepeat`] and [`LazyRepeatAny`].

use crate::tools::{Tool, AlwaysTool, View};

/// Simple either tuple
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Either<L, R>{
    /// Left variant.
    L(L),
    /// Right variant.
    R(R)
}

impl<L, R> Either<L, R>{
    /// Maps each variant.
    pub fn map<LR, RR, LF : FnOnce(L) -> LR, RF : FnOnce(R) -> RR>(self, lf : LF, rf : RF) -> Either<LR, RR> {
        match self {
            Self::L(l) => Either::L(lf(l)),
            Self::R(r) => Either::R(rf(r))
        }
    }
    /// Exchanges the variants.
    pub fn invert(self) -> Either<R, L> {
        match self {
            Self::L(l) => Either::R(l),
            Self::R(r) => Either::L(r)
        }
    }
}
impl<L, R, E> Either<Result<L, E>, Result<R, E>>{
    /// Puts the error out when they have the same error.
    #[allow(clippy::missing_errors_doc)]
    pub fn flatten(self) -> Result<Either<L, R>, E> {
        match self {
            Self::L(l) => l.map(Either::L),
            Self::R(r) => r.map(Either::R)
        }
    }
}
impl<T> Either<T, T>{
    /// Merge both the variants when they have the same type.
    pub fn merge(self) -> T {
        match self {
            Self::L(t) | Self::R(t) => t
        }
    }
}
impl<T> Either<T, ::core::convert::Infallible> {
    /// Safetly drop the second variant.
    pub fn into_first(self) -> T {
        match self {
            Self::L(t) => t,
            Self::R(imp) => match imp {}
        }
    }
}
impl<T> Either<::core::convert::Infallible, T> {
    /// Safetly drop the first variant.
    pub fn into_second(self) -> T {
        match self {
            Self::R(t) => t,
            Self::L(imp) => match imp {}
        }
    }
}

mod _priv {
    use super::{Tool, View};

    /// Utility for saving intermediate values.
    ///
    /// Complex parsing tools usually use several other tools to perform to perform simple
    /// subtasks. However, dealing with many of these tools makes harder to keep consistent both
    /// returned data and the total length of the match, which we remember should be consistent
    /// with the number of bytes skipped by the `View` object.
    ///
    /// This object keeps an instance of intermediate returned data, actual number of bytes skipped
    /// and the last instance of `View`, keeping them consistent.
    #[derive(Debug, Copy, Clone, Eq, PartialEq)]
    pub struct TupData<D, M>{
        pub(crate) data : D,
        pub(crate) this : M,
        pub(crate) len : usize
    }
    pub(crate) type TupVal<M> = TupData<(), M>;

    impl<D, M> TupData<D, M>{
        /// Creates a new instance of this object.
        pub fn new(this : M) -> Self where D : Default {
            Self{this, data : D::default(), len : 0}
        }
        /// Applies a function to the saved data without modifying other fields.
        pub fn map_data<DD, F : FnOnce(D) -> DD>(self, f : F) -> TupData<DD, M> {
            TupData{this : self.this, len : self.len, data : f(self.data)}
        }
        /// Moves stored data outside.
        pub fn get_data(self) -> (D, TupData<(), M>) {
            (self.data, TupData{this : self.this, len : self.len, data : ()})
        }
        /// Unpack this objects and returns all its fields.
        pub fn finalize(self) -> (D, usize, M) {
            (self.data, self.len, self.this)
        }
    }

    impl<'a, D> TupData<D, View<'a>> {
        /// Match a `Tool` and replace stored data with returned data.
        #[allow(clippy::missing_errors_doc)]
        pub fn chain_replace<T>(self, t : &T) -> Result<TupData<T::Data, View<'a>>, T::Error> where T : Tool<'a> {
            self.chain_map(t, |_, b, _| b)
        }
        /// Match a `Tool` but discards returned data.
        #[allow(clippy::missing_errors_doc)]
        pub fn chain_nodata<T>(self, t : &T) -> Result<Self, T::Error> where T : Tool<'a> {
            self.chain_map(t, |a, _, _| a)
        }
        /// Match a `Tool` and keeps both saved and returned data.
        #[allow(clippy::missing_errors_doc)]
        #[allow(clippy::type_complexity)]
        pub fn chain_save<T>(self, t : &T) -> Result<TupData<(D, T::Data), View<'a>>, T::Error> where T : Tool<'a> {
            self.chain_map(t, |a, b, _| (a, b))
        }
        /// Match a `Tool` and keeps returned data separated from original data.
        #[allow(clippy::missing_errors_doc)]
        #[allow(clippy::type_complexity)]
        #[allow(dead_code)]
        pub fn chain_save_out<T>(self, t : &T) -> Result<(Self, T::Data), T::Error> where T : Tool<'a> {
            self.this.match_tool_data_len(t)
                .map(|(data, len, this)| (TupData{this, data : self.data, len : len + self.len}, data))
        }
        /// Match a `Tool` and saves returned data at a different location.
        #[allow(clippy::missing_errors_doc)]
        #[allow(clippy::type_complexity)]
        #[allow(dead_code)]
        pub fn chain_save_at<T>(self, t : &T, to : &mut T::Data) -> Result<Self, T::Error> where T : Tool<'a> {
            self.chain_map(t, |a, b, _| {*to = b; a} )
        }
        pub(crate) fn chain_map<T, F, O>(self, t : &T, f : F) -> Result<TupData<O, View<'a>>, T::Error> where 
            T : Tool<'a>, 
            F : FnOnce(D, T::Data, usize) -> O
        {
            self.this.match_tool_data_len(t)
                .map(|(data, len, this)| TupData{this, data : f(self.data, data, len), len : len + self.len})
        }
    }

    impl<'a> TupData<(), View<'a>>{
        /// Match a [`Tool`](crate::prelude::Tool) object.
        #[allow(clippy::missing_errors_doc)]
        pub fn chain<T>(self, t : &T) -> Result<TupData<T::Data, View<'a>>, T::Error> where T : Tool<'a> {
            self.chain_replace(t)
        }
    }
}
#[cfg(any(feature="unstable-features", doc))]
pub use _priv::*;
#[cfg(not(any(feature="unstable-features", doc)))]
pub(crate) use _priv::*;

// Inserter for both T and SEP
pub(crate) trait InsertB<TD, SEPD> {
    fn insert(&mut self, data : TD);
    fn insert_sep(&mut self, data : SEPD);
}

/*
#[derive(Debug, Copy, Clone, Default)]
pub(crate) struct NullDo;

impl<TD, SEPD> InsertB<TD, SEPD> for NullDo{
    fn insert(&mut self, _ : TD){}
    fn insert_sep(&mut self, _ : SEPD){}
}
*/

#[derive(Debug, Copy, Clone, Default)]
pub(crate) struct Count(pub(crate) usize);

impl<TD, SEPD> InsertB<TD, SEPD> for Count{
    fn insert(&mut self, _ : TD){
        self.0 += 1;
    }
    fn insert_sep(&mut self, _ : SEPD){}
}
impl Count {
    pub(crate) const fn new() -> Self {
        Self(0)
    }
}

#[cfg(feature = "alloc")]
impl<TD, SEPD> InsertB<TD, SEPD> for alloc::vec::Vec<TD>{
    fn insert(&mut self, data : TD){
        self.push(data);
    }
    fn insert_sep(&mut self, _ : SEPD){}
}

pub(crate) fn ihelp<'a, T, SEP, I>(atom : &T, sep : &SEP, st : TupVal<View<'a>>, vec : &mut I) -> Option<TupVal<View<'a>>> where
    T : Tool<'a>,
    SEP : Tool<'a>,
    I : InsertB<T::Data, SEP::Data>
{
    st.chain(sep).ok()
        .and_then(|d| d.chain_save(atom).ok())
        .map(|d| d.map_data(|(sd, ad)| {
            vec.insert_sep(sd);
            vec.insert(ad);
        }))
}
pub(crate) fn ihelpe<'a, T, SEP, E, I>(atom : &T, sep : &SEP, st : TupVal<View<'a>>, vec : &mut I) -> Result<TupVal<View<'a>>, E> where
    T : Tool<'a, Error = E>,
    SEP : Tool<'a, Error = E>,
    I : InsertB<T::Data, SEP::Data>
{
    st.chain(sep)
        .and_then(|d| d.chain_save(atom))
        .map(|d| d.map_data(|(sd, ad)| {
            vec.insert_sep(sd);
            vec.insert(ad);
        }))
}

/// Matches both the provided atoms, trying `first` before `second`.
pub struct Seq<F, S>{
    /// The first atom to be checked
    pub first : F,
    /// The second atom to be checked.
    pub second : S,
}

impl<F, S> Seq<F, S> {
    /// Creates a new `Seq`.
    pub const fn new(first : F, second : S) -> Self {
        Self{first, second}
    }
}

impl<'a, F, S> Tool<'a> for Seq<F, S> where F : Tool<'a>, S : Tool<'a> {
    type Data = (F::Data, S::Data);
    type Error = Either<F::Error, S::Error>;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        TupData::new(st)
            .chain(&self.first)
            .map_err(Either::L)?
            .chain_save(&self.second)
            .map_err(Either::R)
            .map(TupData::finalize)
    }
}
impl<'a, F, S> AlwaysTool<'a> for Seq<F, S> where F : AlwaysTool<'a>, S : AlwaysTool<'a> {
    fn parse_always(&self, st : View<'a>) -> (Self::Data, usize, View<'a>) {
        let (d0, l0, st) = self.first.parse_always(st);
        let (d1, l1, st) = self.second.parse_always(st);
        ((d0, d1), l0 + l1, st)
    }
}

/// Matches at least one of the provided atoms, trying `first` before `second`.
///
/// ```
/// use minparser::prelude::*;
///
/// let (st, step) = View::new("AB").match_tool_data(&Or{first : 'A', second : "AB"}).unwrap();
/// assert_eq!(st, Either::L('A'));
/// assert_eq!(step.get_view(), "B");
/// ```
pub struct Or<F, S>{
    /// The first atom to be checked
    pub first : F,
    /// The second atom to be checked.
    ///
    /// If `first` matches then `second` would not be tested.
    pub second : S,
}

impl<'a, F, S> Tool<'a> for Or<F, S> where F : Tool<'a>, S : Tool<'a> {
    type Data = Either<F::Data, S::Data>;
    type Error = (F::Error, S::Error);

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        match self.first.parse(st) {
            Ok(d) => Ok((Either::L(d.0), d.1, d.2)),
            Err(f) => match self.second.parse(st) {
                Ok(d) => Ok((Either::R(d.0), d.1, d.2)),
                Err(s) => Err((f, s))
            },
        }
    }
}
impl<'a, F, S> AlwaysTool<'a> for Or<F, S> where F : AlwaysTool<'a>, S : Tool<'a> {
    /// The second tool is never used due to ordering.
    fn parse_always(&self, st : View<'a>) -> (Self::Data, usize, View<'a>) {
        let (d, l, st) = self.first.parse_always(st);
        (Either::L(d), l, st)
    }
}

/// Only checks the provided atom, without progressing.
///
/// ```rust
/// use minparser::prelude::*;
///
/// View::from("a").match_tool(&Check('a')).unwrap()
///     .match_tool(&'a').unwrap();
/// ```
#[derive(Debug, Copy, Clone, Default)]
pub struct Check<T>(pub T);

impl<'a, T> Tool<'a> for Check<T> where T : Tool<'a>{
    type Error = T::Error;
    type Data = T::Data;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        let d = self.0.parse(st)?;
        Ok((d.0, 0, st))
    }
}

/// Matches only if the provided atom doesn't match.
///
/// ```rust
/// use minparser::prelude::*;
///
/// View::from("ab").match_tool(&CheckInv('c')).unwrap()
///     .match_tool(&CheckInv('b')).unwrap();
/// ```
#[derive(Debug, Copy, Clone, Default)]
pub struct CheckInv<T>(pub T);

impl<'a, T> Tool<'a> for CheckInv<T> where T : Tool<'a>{
    type Error = T::Data;
    type Data = T::Error;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        match self.0.parse(st) {
            Ok(d) => Err(d.0),
            Err(e) => Ok((e, 0, st))
        }
    }
}

/// Tool that matches repetitions with separator.
///
/// Like [`Repeat`] but without specifying a minimum number of repetitions. Therefore. it will
/// always match.
#[derive(Debug, Clone, Copy)]
pub struct RepeatAny<T, SEP>{
    pub(crate) atom : T,
    pub(crate) sep : SEP,
    pub(crate) max : Option<usize>,
}

impl<T, SEP> RepeatAny<T, SEP>{
    /// Create a new [`RepeatAny`] with specified separator.
    pub const fn new(atom : T, sep : SEP, max : Option<usize>) -> Self {
        Self{
            atom,
            sep,
            max,
        }
    }
    /// Create a new [`RepeatAny`] with specified separator and upper bound.
    pub const fn new_bounds(atom : T, sep : SEP, max : usize) -> Self {
        Self::new(atom, sep, Some(max))
    }
    /// Create a new [`RepeatAny`] with specified separator without upper bound
    pub const fn new_unbounded(atom : T, sep : SEP) -> Self {
        Self::new(atom, sep, None)
    }
}

impl<T, SEP> RepeatAny<T, SEP> { 
    // Starts with a separator instead of the atom.
    //
    // This is useful if you need to just contine the work of another repetition tool that has
    // already parsed one or more atoms.
    fn parse_logic_continue<'a, I>(&self, mut st : TupVal<View<'a>>, vec : &mut I, precount : usize) -> TupVal<View<'a>> where
        T : Tool<'a>,
        SEP : Tool<'a>,
        I : InsertB<T::Data, SEP::Data>
    {
        match self.max {
            None => loop {
                if let Some(tval) = ihelp(&self.atom, &self.sep, st, vec) {
                    st = tval;
                }
                else {
                    break st;
                }
            },
            Some(mx) => {
                let mut i = precount;
                loop {
                    if i >= mx {
                        break st;
                    }
                    else if let Some(tval) = ihelp(&self.atom, &self.sep, st, vec) {
                        st = tval;
                        i += 1;
                    }
                    else {
                        break st;
                    }
                }
            }
        }
    }
    pub(crate) fn parse_logic<'a, I>(&self, st : View<'a>, vec : &mut I) -> TupVal<View<'a>> where
        T : Tool<'a>,
        SEP : Tool<'a>,
        I : InsertB<T::Data, SEP::Data>
    {
        if Some(0) == self.max {
            TupData::new(st)
        }
        else {
            TupData::new(st).chain(&self.atom)
                .map_or_else(
                    |_| TupData::new(st),
                    |tval| {
                        let (data, tval) = tval.get_data();
                        vec.insert(data);
                        self.parse_logic_continue(tval, vec, 1)
                    })
        }
    }
}

impl<'a, T, SEP> AlwaysTool<'a> for RepeatAny<T, SEP> where T : Tool<'a>, SEP : Tool<'a> {
    fn parse_always(&self, st : View<'a>) -> (Self::Data, usize, View<'a>) {
        let mut count = Count::new();
        let ((), l, s) = self.parse_logic(st, &mut count).finalize();
        (count.0, l, s)
    }
}
impl<'a, T, SEP> Tool<'a> for RepeatAny<T, SEP> where T : Tool<'a>, SEP : Tool<'a> {
    /// Number of repetitions.
    type Data = usize;
    type Error = ::core::convert::Infallible;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        Ok(self.parse_always(st))
    }
}

/// Tool that matches repetitions with separator requiring a minimum number of repetitions.
///
/// If you do not need to specify a minimum number of repetitons then you should instead use
/// [`RepeatAny`].
///
/// ```rust
/// use minparser::prelude::*;
/// let lt = View::from("a a a a b");
/// assert_eq!(lt.match_tool_string(&Repeat::new_bounds('a', ' ', 0, 3))
/// .unwrap().0, "a a a", "Failed 1");
/// assert_eq!(lt.match_tool_string(&Repeat::new_bounds('a', ' ', 2, 3))
/// .unwrap().0, "a a a", "Failed 2");
/// assert_eq!(lt.match_tool_string(&Repeat::new_unbounded('a', ' ', 0))
/// .unwrap().0, "a a a a", "Failed 3");
/// assert_eq!(lt.match_tool_string(&Repeat::new_unbounded('a', ' ', 2))
/// .unwrap().0, "a a a a");
/// assert!(lt.match_tool_string(&Repeat::new_unbounded('a', ' ', 5))
/// .is_err());
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Repeat<T, SEP>{
    pub(crate) sup : RepeatAny<T, SEP>,
    pub(crate) min : usize,
}

impl<T, SEP> Repeat<T, SEP>{
    /// Create a new [`Repeat`] with specified separator and upper bound.
    ///
    /// # Panics
    /// It panic when `max` is strictly less than `min`, because in such case no matches are
    /// possible
    pub fn new_bounds(atom : T, sep : SEP, min : usize, max : usize) -> Self {
        assert!(min <= max, "Maximum value {max} is strictly less than minimum {min}");
        Self {
            sup : RepeatAny::new_bounds(atom, sep, max),
            min,
        }
    }
    /// Create a new [`Repeat`] with specified separator without upper bound
    pub const fn new_unbounded(atom : T, sep : SEP, min : usize) -> Self {
        Self {
            sup : RepeatAny::new_unbounded(atom, sep),
            min,
        }
    }
}

impl<T, SEP> Repeat<T, SEP> { 
    pub(crate) fn parse_logic<'a, I, E>(&self, st : View<'a>, vec : &mut I) -> Result<TupVal<View<'a>>, E> where
        T : Tool<'a, Error = E>,
        SEP : Tool<'a, Error = E>,
        I : InsertB<T::Data, SEP::Data>
    {
        if self.min > 0 {
            let mut helper = {
                let (data, h) = TupVal::new(st).chain(&self.sup.atom)?.get_data();
                vec.insert(data);
                h
            };
            for _ in 1..(self.min) {
                helper = ihelpe(&self.sup.atom, &self.sup.sep, helper, vec)?;
            }
            Ok(self.sup.parse_logic_continue(helper, vec, self.min))
        }
        else {
            Ok(self.sup.parse_logic(st, vec))
        }
    }
}
impl<'a, T, SEP, E> Tool<'a> for Repeat<T, SEP> where T : Tool<'a, Error = E>, SEP : Tool<'a, Error = E> {
    /// Number of repetitions.
    type Data = usize;
    type Error = E;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        let mut count = Count::new();
        let ((), l, s) = self.parse_logic(st, &mut count)?.finalize();
        Ok((count.0, l, s))
    }
}

/// Lazily parse a string with a specified termination.
///
/// It matches the least number of `T` atom (sepatared by `SEP`) which are followed by `TERM` atom.
/// The difference with respect to a [`RepeatAny`] followed by `TERM` is that here repetitions are
/// evaluated lazily: it interrupts at the first match of `TERM`, whereas `RepeatAny` evaluates
/// repetitions eagerly and so `TERM` is matched only after the repetition ends.
///
/// ```rust
/// use minparser::prelude::*;
/// let mh = View::new("\"ABC\" \"defg\" \"hi");
/// let (su, mh) = mh.match_tool_string(&Seq{
///     first : '\"',
///     second : LazyRepeatAny::new_unbounded(AnyChar, TrueTool, '\"')
///     }).unwrap();
/// assert_eq!(su, "\"ABC\"");
/// let (su, mh) = mh.match_tool_string(&Seq{
///     first : " \"",
///     second : LazyRepeatAny::new_unbounded(AnyChar, TrueTool, '\"')
///     }).unwrap();
/// assert_eq!(su, " \"defg\"");
/// assert!(mh.match_tool_string(&Seq{
///     first : " \"",
///     second : LazyRepeatAny::new_unbounded(AnyChar, TrueTool, '\"')
///     }).is_err());
/// ```
#[derive(Copy, Clone, Debug)]
pub struct LazyRepeatAny<T, SEP, TERM>{
    atom : T,
    sep : SEP,
    term : TERM,
    max : Option<usize>,
}

impl<T, SEP, TERM> LazyRepeatAny<T, SEP, TERM>{
    /// Create a new `LazyRepeatAny` with specified upper bound.
    pub const fn new_bounds(atom : T, sep : SEP, term : TERM, max : usize) -> Self {
        Self {
            atom,
            sep,
            term,
            max : Some(max)
        }
    }
    /// Create a new `LazyRepeatAny` without upper bound.
    pub const fn new_unbounded(atom : T, sep : SEP, term : TERM) -> Self {
        Self {
            atom,
            sep,
            term,
            max : None
        }
    }
}

impl<T, SEP, TERM> LazyRepeatAny<T, SEP, TERM> {
    pub(crate) fn parse_logic_continue<'a, I>(&self, mut st : TupVal<View<'a>>, vec : &mut I, precount : usize) -> Result<TupVal<View<'a>>, TERM::Error > where 
        T : Tool<'a>,
        SEP : Tool<'a>,
        TERM : Tool<'a>,
        I : InsertB<T::Data, SEP::Data>
    {
        match self.max {
            Some(mx) => {
                let mut i = precount;
                loop {
                    match st.chain_nodata(&self.term) {
                        Ok(hh) => {
                            break Ok(hh);
                        }
                        Err(e) => {
                            if i >= mx {
                                break Err(e);
                            }
                            else if let Some(h) = ihelp(&self.atom, &self.sep, st, vec) {
                                st = h;
                                i += 1;
                            }
                            else{
                                break Err(e);
                            }
                        }
                    }
                }
            }
            None => {
                loop {
                    match st.chain_nodata(&self.term) {
                        Ok(hh) => {
                            break Ok(hh);
                        }
                        Err(e) => {
                            if let Some(h) = ihelp(&self.atom, &self.sep, st, vec) {
                                st = h;
                            }
                            else{
                                break Err(e);
                            }
                        }
                    }
                }
            }
        }
    }

    pub(crate) fn parse_logic<'a, I>(&self, st : View<'a>, vec : &mut I) -> Result<TupVal<View<'a>>, TERM::Error> where
        T : Tool<'a>,
        SEP : Tool<'a>,
        TERM : Tool<'a>,
        I : InsertB<T::Data, SEP::Data>
    {
        let st = TupVal::new(st);
        if Some(0) == self.max {
            st.chain_nodata(&self.term)
        }
        else {
            st.chain_nodata(&self.term)
                .map_or_else(
                    |e| {
                        st.chain(&self.atom).map_or_else(
                            |_| Err(e), 
                            |tval| {
                                let (i, h) = tval.get_data();
                                vec.insert(i);
                                self.parse_logic_continue(h, vec, 1)
                            })
                    },
                    Ok)
        }
    }
    #[cfg(feature = "alloc")]
    /// Parse and store data in `vec`.
    #[allow(clippy::missing_errors_doc)]
    pub fn parse_store<'a>(&self, st : View<'a>, vec : &mut alloc::vec::Vec<T::Data>) -> Result<View<'a>, TERM::Error> where 
        T : Tool<'a>, 
        SEP : Tool<'a>, 
        TERM : Tool<'a> 
    {
        self.parse_logic(st, vec)
            .map(|d| d.finalize().2)
    }
    /// Parse and counts the number of occurrences.
    #[allow(clippy::missing_errors_doc)]
    pub fn parse_count<'a>(&self, st : View<'a>) -> Result<(usize, usize, View<'a>), TERM::Error> where 
        T : Tool<'a>, 
        SEP : Tool<'a>, 
        TERM : Tool<'a> 
    {
        let mut count = Count::new();
        let st = self.parse_logic(st, &mut count)?;
        Ok((count.0, st.len, st.this))
    }
}
impl<'a, T, SEP, TERM> Tool<'a> for LazyRepeatAny<T, SEP, TERM> where T : Tool<'a>, SEP : Tool<'a>, TERM : Tool<'a> {
    /// Number of repetitions.
    type Data = usize;
    type Error = TERM::Error;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        let mut count = Count::new();
        let ((), l, s) = self.parse_logic(st, &mut count)?.finalize();
        Ok((count.0, l, s))
    }
}

/// Tool that matches repetitions lazily with a minimum number of repetitions.
#[derive(Copy, Clone, Debug)]
pub struct LazyRepeat<T, SEP, TERM>{
    sup : LazyRepeatAny<T, SEP, TERM>,
    min : usize,
}

impl<T, SEP, TERM> LazyRepeat<T, SEP, TERM>{
    /// Create a new `LazyRepeat` with specified upper bound.
    ///
    /// # Panics
    /// Panic if `max` is strictly lesser than `min`.
    pub fn new_bounds(atom : T, sep : SEP, term : TERM, min : usize, max : usize) -> Self {
        assert!(min <= max, "Maximum value {max} is strictly less than minimum {min}");
        Self {
            sup : LazyRepeatAny::new_bounds(atom, sep, term, max),
            min
        }
    }
    /// Create a new `LazyRepeat` without upper bound.
    pub const fn new_unbounded(atom : T, sep : SEP, term : TERM, min : usize) -> Self {
        Self {
            sup : LazyRepeatAny::new_unbounded(atom, sep, term),
            min
        }
    }
}

impl<T, SEP, TERM> LazyRepeat<T, SEP, TERM> {
    pub(crate) fn parse_logic<'a, E, I>(&self, st : View<'a>, vec : &mut I) -> Result<TupVal<View<'a>>, E> where
        T : Tool<'a, Error = E>,
        SEP : Tool<'a, Error = E>,
        TERM : Tool<'a, Error = E>,
        I : InsertB<T::Data, SEP::Data>
    {
        if self.min > 0 {
            let mut helper = {
                let (i, h) = TupVal::new(st).chain(&self.sup.atom)?.get_data();
                vec.insert(i);
                h
            };
            for _ in 1..(self.min) {
                helper = ihelpe(&self.sup.atom, &self.sup.sep, helper, vec)?;
            }
            self.sup.parse_logic_continue(helper, vec, self.min)
        }
        else {
            self.sup.parse_logic(st, vec)
        }
    }
    #[cfg(feature = "alloc")]
    /// Parse and store data in `vec`.
    #[allow(clippy::missing_errors_doc)]
    pub fn parse_store<'a, E >(&self, st : View<'a>, vec : &mut alloc::vec::Vec<T::Data>) -> Result<View<'a>, E> 
        where T : Tool<'a, Error = E>, 
              SEP : Tool<'a, Error = E>, 
              TERM : Tool<'a, Error = E> {
            self.parse_logic(st, vec)
                .map(|d| d.finalize().2)
    }
}
impl<'a, T, SEP, TERM, E> Tool<'a> for LazyRepeat<T, SEP, TERM> where T : Tool<'a, Error = E>, SEP : Tool<'a, Error = E>, TERM : Tool<'a, Error = E> {
    /// Number of repetitions.
    type Data = usize;
    type Error = E;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        let mut count = Count::new();
        let ((), l, s) = self.parse_logic(st, &mut count)?.finalize();
        Ok((count.0, l, s))
    }
}

/// Wrapper for [`Repeat`], [`RepeatAny`], [`LazyRepeat`] and [`LazyRepeatAny`] that saves data into a `Vec`.
#[cfg(feature = "alloc")]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct VecStore<T>(pub T);

#[cfg(feature = "alloc")]
impl<'a, T, SEP, E> Tool<'a> for VecStore<Repeat<T, SEP>> where T : Tool<'a, Error = E>, SEP : Tool<'a, Error = E> {
    type Data = alloc::vec::Vec<T::Data>;
    type Error = E;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        let mut count = alloc::vec::Vec::new();
        let ((), l, s) = self.0.parse_logic(st, &mut count)?.finalize();
        Ok((count, l, s))
    }
}

#[cfg(feature = "alloc")]
impl<'a, T, SEP> Tool<'a> for VecStore<RepeatAny<T, SEP>> where T : Tool<'a>, SEP : Tool<'a> {
    type Data = alloc::vec::Vec<T::Data>;
    type Error = ::core::convert::Infallible;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        Ok(self.parse_always(st))
    }
}
#[cfg(feature = "alloc")]
impl<'a, T, SEP> AlwaysTool<'a> for VecStore<RepeatAny<T, SEP>> where T : Tool<'a>, SEP : Tool<'a> {
    fn parse_always(&self, st : View<'a>) -> (Self::Data, usize, View<'a>) {
        let mut count = alloc::vec::Vec::new();
        let ((), l, s) = self.0.parse_logic(st, &mut count).finalize();
        (count, l, s)
    }
}

#[cfg(feature = "alloc")]
impl<'a, T, SEP, TERM, E> Tool<'a> for VecStore<LazyRepeat<T, SEP, TERM>> where T : Tool<'a, Error = E>, SEP : Tool<'a, Error = E>, TERM : Tool<'a, Error = E> {
    type Data = alloc::vec::Vec<T::Data>;
    type Error = E;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        let mut count = alloc::vec::Vec::new();
        let ((), l, s) = self.0.parse_logic(st, &mut count)?.finalize();
        Ok((count, l, s))
    }
}

#[cfg(feature = "alloc")]
impl<'a, T, TERM, SEP> Tool<'a> for VecStore<LazyRepeatAny<T, SEP, TERM>> where T : Tool<'a>, SEP : Tool<'a>, TERM : Tool<'a> {
    type Data = alloc::vec::Vec<T::Data>;
    type Error = TERM::Error;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        let mut count = alloc::vec::Vec::new();
        let ((), l, s) = self.0.parse_logic(st, &mut count)?.finalize();
        Ok((count, l, s))
    }
}