minparser 0.14.0

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
/*
 * Minparser Simple parsing functions
 *
 * Copyright (C) 2024-2025 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/>.
 */
//! Parsing tools.
//!
//! This module provides the [`View`] object representing a string with its position inside a file,
//! and the [`Tool`] trait which is implemented by any object that respesents a parsing strategy.
use crate::pos::Position;

/// A view on a `str`.
///
/// This view carries a [`Position`] with respect of the initial string.
/// Each time a pattern is matched against a `View` object a new `View` object is returned,
/// returning the *remaining* part of the view which follows the matched prefix.
#[derive(Debug, Clone, Copy)]
pub struct View<'a> {
    pub(crate) view: &'a str,
    pub(crate) pos: Position,
}

#[derive(Debug, Clone, Copy)]
struct CursorData<'a, D> {
    pub(crate) view: &'a str,
    pos: Position,
    pub(crate) data: D,
}
#[must_use]
fn progress(pos: Position, view: &str, inc: usize) -> (&str, Position, &str) {
    if inc == 0 {
        ("", pos, view)
    } else {
        let (pfx, sfx) = view.split_at(inc);
        let mut fit = pfx.split('\n');
        let mut elem = fit.next().unwrap(); // at least one element
        let mut nls = 0;
        for el in fit {
            elem = el;
            nls += 1;
        }
        let (mut r, mut c) = pos.unpack();
        if nls > 0 {
            c = 0;
            r += nls;
        }
        c += u32::try_from(elem.len()).unwrap();
        (pfx, Position::new(r, c), sfx)
    }
}

/// A pointer to a location inside a string.
///
/// It is provided as an input argument of [`Tool`].
#[derive(Debug, Clone, Copy)]
pub struct CursorStart<'a>(CursorData<'a, ()>);

/// A [`Cursor`] that holds additional data.
#[derive(Debug, Clone, Copy)]
pub struct CursorLen<'a, D> {
    this: CursorData<'a, D>,
    // The length of the match, or equivalently how much bytes have been skipped, therefore this
    // points at the END of len.
    len: usize,
}

/// A position inside a string.
pub type Cursor<'a> = CursorLen<'a, ()>;

/// Parsing tool trait.
///
/// An object implementing this trait represents a parsing rule that are applied to string
/// prefixes. If any prefix of a string satisfy this rule then the match is successful and
/// additional data parsed from the matching prefix is returned. If instead no prefix satisfies the
/// rule then an error is returned.
pub trait Tool<'a> {
    /// Error type.
    type Error;
    /// Associated data type.
    type Data;

    /// The main parsing algorithm.
    ///
    /// On a successful match, it additionally returns the parsed data and the length of the match
    /// in bytes. You don't need to call this methos directly, just use [`chain`](CursorLen::chain)
    /// method of [`CursorLen`].
    ///
    /// # Errors
    /// If no prefix of `st` satisfies this parsing strategy then `Error` is returned.
    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error>;

    /// Applies a closure to generated data.
    fn map<D, F: Fn(Self::Data) -> D>(self, f: F) -> MapData<D, Self, F>
    where
        Self: Sized,
    {
        MapData(self, f, core::marker::PhantomData)
    }
}
/// A parsing tool that always match a prefix.
///
/// Any object implementing this trait must also implement the [`Tool`] trait and their
/// implementation of the [`parse`](Tool::parse) must be equivalent to
/// `Ok(self.parse_always(st))`.
///
/// It is a good practice to set [`core::convert::Infallible`] (or [`!`] when it will become
/// stable) as `Error`, but it is not mandatory.
pub trait AlwaysTool<'a>: Tool<'a> {
    /// The main parsing algorithm.
    fn parse_always(&self, st: CursorStart<'a>) -> CursorLen<'a, Self::Data>;

    /// Automatically discards the generated data.
    fn parse_always_nodata(&self, st: CursorStart<'a>) -> CursorLen<'a, ()> {
        self.parse_always(st).map_data(|_| ())
    }

    /// Sets a specific error type.
    fn set_error<E>(self) -> SetError<E, Self>
    where
        Self: Sized,
    {
        SetError(self, core::marker::PhantomData)
    }
}

impl<'a, D, DI> From<CursorData<'a, D>> for CursorLen<'a, DI>
where
    D: Into<DI>,
{
    fn from(v: CursorData<'a, D>) -> Self {
        Self {
            this: CursorData {
                view: v.view,
                pos: v.pos,
                data: v.data.into(),
            },
            len: 0,
        }
    }
}
impl<'a> From<CursorStart<'a>> for CursorLen<'a, ()> {
    fn from(v: CursorStart<'a>) -> Self {
        v.0.into()
    }
}

impl<'a> From<&'a str> for CursorLen<'a, ()> {
    fn from(s: &'a str) -> Self {
        Self {
            len: 0,
            this: CursorData {
                data: (),
                view: s,
                pos: Position::new_zero(),
            },
        }
    }
}
impl<'a, D> CursorLen<'a, D> {
    /// Evaluate the current position of the cursor.
    pub const fn get_pos(self) -> (Position, Self) {
        (self.this.pos, self)
    }
    /// Returns the remaining string.
    pub const fn get_view(self) -> (&'a str, Self) {
        (self.this.view, self)
    }
    /// Applies a function to the saved data without modifying other fields.
    pub fn map_data<DD, F: FnOnce(D) -> DD>(self, f: F) -> CursorLen<'a, DD> {
        CursorLen {
            len: self.len,
            this: CursorData {
                view: self.this.view,
                pos: self.this.pos,
                data: f(self.this.data),
            },
        }
    }
    /// Like [`map_data`] but it may fail.
    #[allow(clippy::missing_errors_doc)]
    pub fn try_map_data<DD, E, F: FnOnce(D) -> Result<DD, E>>(
        self,
        f: F,
    ) -> Result<CursorLen<'a, DD>, E> {
        Ok(CursorLen {
            len: self.len,
            this: CursorData {
                view: self.this.view,
                pos: self.this.pos,
                data: f(self.this.data)?,
            },
        })
    }
    /// Like [`map_data`] but it may fail.
    pub fn opt_map_data<DD, F: FnOnce(D) -> Option<DD>>(self, f: F) -> Option<CursorLen<'a, DD>> {
        Some(CursorLen {
            len: self.len,
            this: CursorData {
                view: self.this.view,
                pos: self.this.pos,
                data: f(self.this.data)?,
            },
        })
    }
    /// Moves stored data outside.
    pub fn get_data(self) -> (D, CursorLen<'a, ()>) {
        (
            self.this.data,
            CursorLen {
                len: self.len,
                this: CursorData {
                    view: self.this.view,
                    pos: self.this.pos,
                    data: (),
                },
            },
        )
    }
    /// Match a `Tool` and replace stored data with returned data.
    #[allow(clippy::missing_errors_doc)]
    pub fn chain_replace<T>(self, t: &T) -> Result<CursorLen<'a, T::Data>, T::Error>
    where
        T: Tool<'a> + ?Sized,
    {
        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> + ?Sized,
    {
        self.chain_map(t, |a, _, _| a)
    }
    /// Match a `Tool` and keeps both saved and returned data.
    #[allow(clippy::missing_errors_doc)]
    pub fn chain_save<T>(self, t: &T) -> Result<CursorLen<'a, (D, T::Data)>, T::Error>
    where
        T: Tool<'a> + ?Sized,
    {
        self.chain_map(t, |a, b, _| (a, b))
    }
    /// Match a `Tool` and keeps returned data separated from original data.
    #[allow(clippy::missing_errors_doc)]
    pub fn chain_save_out<T>(self, t: &T) -> Result<(Self, T::Data), T::Error>
    where
        T: Tool<'a> + ?Sized,
    {
        let ret = self.chain_save(t)?;
        Ok((
            CursorLen {
                len: ret.len,
                this: CursorData {
                    view: ret.this.view,
                    pos: ret.this.pos,
                    data: ret.this.data.0,
                },
            },
            ret.this.data.1,
        ))
    }
    /// Match a `Tool` and saves returned data at a different location.
    #[allow(clippy::missing_errors_doc)]
    pub fn chain_save_at<T>(self, t: &T, to: &mut T::Data) -> Result<Self, T::Error>
    where
        T: Tool<'a> + ?Sized,
    {
        self.chain_map(t, |a, b, _| {
            *to = b;
            a
        })
    }
    pub(crate) fn chain_map<T, F, O>(self, t: &T, f: F) -> Result<CursorLen<'a, O>, T::Error>
    where
        T: Tool<'a> + ?Sized,
        F: FnOnce(D, T::Data, usize) -> O,
    {
        let c = CursorStart(CursorData {
            view: self.this.view,
            pos: self.this.pos,
            data: (),
        });
        t.parse(c).map(|cnew| CursorLen {
            len: self.len + cnew.len,
            this: CursorData {
                view: cnew.this.view,
                pos: cnew.this.pos,
                data: f(self.this.data, cnew.this.data, cnew.len),
            },
        })
    }
    /// Match an `AlwaysTool` and replace stored data with returned data.
    #[allow(clippy::missing_errors_doc)]
    pub fn always_replace<T>(self, t: &T) -> CursorLen<'a, T::Data>
    where
        T: AlwaysTool<'a> + ?Sized,
    {
        self.always_map(t, |_, b, _| b)
    }
    /// Match an `AlwaysTool` but discards returned data.
    #[allow(clippy::missing_errors_doc)]
    #[must_use]
    pub fn always_nodata<T>(self, t: &T) -> Self
    where
        T: AlwaysTool<'a> + ?Sized,
    {
        self.always_map(t, |a, _, _| a)
    }
    /// Match an `AlwaysTool` and keeps both saved and returned data.
    #[allow(clippy::missing_errors_doc)]
    pub fn always_save<T>(self, t: &T) -> CursorLen<'a, (D, T::Data)>
    where
        T: AlwaysTool<'a> + ?Sized,
    {
        self.always_map(t, |a, b, _| (a, b))
    }
    /// Match an `AlwaysTool` and keeps returned data separated from original data.
    #[allow(clippy::missing_errors_doc)]
    pub fn always_save_out<T>(self, t: &T) -> (Self, T::Data)
    where
        T: AlwaysTool<'a> + ?Sized,
    {
        let ret = self.always_save(t);
        (
            CursorLen {
                len: ret.len,
                this: CursorData {
                    view: ret.this.view,
                    pos: ret.this.pos,
                    data: ret.this.data.0,
                },
            },
            ret.this.data.1,
        )
    }
    /// Match an `AlwaysTool` and saves returned data at a different location.
    #[allow(clippy::missing_errors_doc)]
    #[must_use]
    pub fn always_save_at<T>(self, t: &T, to: &mut T::Data) -> Self
    where
        T: AlwaysTool<'a> + ?Sized,
    {
        self.always_map(t, |a, b, _| {
            *to = b;
            a
        })
    }
    pub(crate) fn always_map<T, F, O>(self, t: &T, f: F) -> CursorLen<'a, O>
    where
        T: AlwaysTool<'a> + ?Sized,
        F: FnOnce(D, T::Data, usize) -> O,
    {
        let c = CursorStart(CursorData {
            view: self.this.view,
            pos: self.this.pos,
            data: (),
        });
        let cnew = t.parse_always(c);
        CursorLen {
            len: self.len + cnew.len,
            this: CursorData {
                view: cnew.this.view,
                pos: cnew.this.pos,
                data: f(self.this.data, cnew.this.data, cnew.len),
            },
        }
    }
}

impl<'a> CursorStart<'a> {
    /// Convert it into a [`CursorLen`]
    #[must_use]
    pub fn into_clen(self) -> CursorLen<'a, ()> {
        self.into()
    }
}
impl<'a> CursorLen<'a, ()> {
    /// Match a [`Tool`](crate::prelude::Tool) object.
    #[allow(clippy::missing_errors_doc)]
    pub fn chain<T>(self, t: &T) -> Result<CursorLen<'a, T::Data>, T::Error>
    where
        T: Tool<'a> + ?Sized,
    {
        self.chain_replace(t)
    }
    /// Match an [`AlwaysTool`] object.
    pub fn always<T>(self, t: &T) -> CursorLen<'a, T::Data>
    where
        T: AlwaysTool<'a> + ?Sized,
    {
        self.always_replace(t)
    }
    /// On error, return the initial `Cursor` instead of the error.
    #[allow(clippy::missing_errors_doc)]
    pub fn chain_err<T>(self, t: &T) -> Result<CursorLen<'a, T::Data>, Self>
    where
        T: Tool<'a> + ?Sized,
    {
        self.chain(t).map_err(|_| self)
    }
}

impl<'a> View<'a> {
    /// Creates a new [`View`] object from a string.
    ///
    /// The initial position is set at line `0` and column `0`.
    #[must_use]
    pub const fn new(view: &'a str) -> Self {
        Self {
            view,
            pos: Position::new_zero(),
        }
    }
    /// Returns the underlying string.
    #[must_use]
    pub const fn get_view(&self) -> &'a str {
        self.view
    }
    /// Tests if the underlying string is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.view.is_empty()
    }
    /// Returns the position of the first character with respect to the main file.
    #[must_use]
    pub const fn top_position(&self) -> &Position {
        &self.pos
    }
    /// Consumes the view and returns the actual [`Position`].
    #[must_use]
    pub const fn into_pos(self) -> Position {
        self.pos
    }
}

/// Tool that returns the matched string as data instead of data provided by inner tool.
#[derive(Debug, Clone, Copy, Default)]
pub struct GetStr<T>(pub T);

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

    fn parse(&self, c: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        let cnew = c.into_clen().chain_nodata(&self.0)?;
        let l = cnew.len;
        Ok(cnew.map_data(|()| &c.0.view[0..l]))
    }
}
impl<'a, T> AlwaysTool<'a> for GetStr<T>
where
    T: AlwaysTool<'a>,
{
    fn parse_always(&self, c: CursorStart<'a>) -> CursorLen<'a, Self::Data> {
        let cnew = c.into_clen().always_nodata(&self.0);
        let l = cnew.len;
        cnew.map_data(|()| &c.0.view[0..l])
    }
}

/// Automatically implements [`Tool`] for an object without templates implementing [`AlwaysTool`].
#[macro_export]
macro_rules! always_impl {
    ($i:ident) => {
        always_impl!($i, ());
    };
    ($i:ident, $t:ty) => {
        impl<'a> Tool<'a> for $i {
            type Error = core::convert::Infallible;
            type Data = $t;

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

impl<'a, T> Tool<'a> for &T
where
    T: Tool<'a> + ?Sized,
{
    type Error = T::Error;
    type Data = T::Data;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        T::parse(*self, st)
    }
}
impl<'a, T> AlwaysTool<'a> for &T
where
    T: AlwaysTool<'a> + ?Sized,
{
    fn parse_always(&self, st: CursorStart<'a>) -> CursorLen<'a, Self::Data> {
        T::parse_always(*self, st)
    }
}

/// Wrapper for [`AlwaysTool`] objects that sets a different error type.
#[derive(Debug)]
pub struct SetError<E, T>(pub T, pub core::marker::PhantomData<fn() -> E>);

impl<E, T: Clone> Clone for SetError<E, T> {
    fn clone(&self) -> Self {
        Self(self.0.clone(), core::marker::PhantomData)
    }
}
impl<E, T: Copy> Copy for SetError<E, T> {}
impl<E, T: Default> Default for SetError<E, T> {
    fn default() -> Self {
        Self(T::default(), core::marker::PhantomData)
    }
}
impl<'a, E, T> Tool<'a> for SetError<E, T>
where
    T: AlwaysTool<'a>,
{
    type Data = T::Data;
    type Error = E;

    fn parse(&self, c: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        Ok(self.0.parse_always(c))
    }
}

/// Wrapper for [`Tool`] objects that applies a closure to returned data.
#[derive(Debug)]
pub struct MapData<D, T, CD>(pub T, pub CD, pub core::marker::PhantomData<fn() -> D>);

impl<D, CD: Clone, T: Clone> Clone for MapData<D, T, CD> {
    fn clone(&self) -> Self {
        Self(self.0.clone(), self.1.clone(), core::marker::PhantomData)
    }
}
impl<D, CD: Copy, T: Copy> Copy for MapData<D, T, CD> {}
impl<D, CD: Default, T: Default> Default for MapData<D, T, CD> {
    fn default() -> Self {
        Self(T::default(), CD::default(), core::marker::PhantomData)
    }
}
impl<'a, D, CD, T> Tool<'a> for MapData<D, T, CD>
where
    T: Tool<'a>,
    CD: Fn(T::Data) -> D,
{
    type Data = D;
    type Error = T::Error;

    fn parse(&self, c: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        self.0.parse(c).map(|d| d.map_data(&self.1))
    }
}

/// Matches any single character.
///
/// It is exactly the opposite of [`EOFTool`].
#[derive(Debug, Copy, Clone, Default)]
pub struct AnyChar;

impl<'a> Tool<'a> for AnyChar {
    type Data = char;
    type Error = Cursor<'a>;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        st.0.view.chars().next().map_or_else(
            || Err(Cursor::from(st)),
            |c| {
                let (_, pos, view) = progress(st.0.pos, st.0.view, c.len_utf8());
                Ok(CursorLen {
                    len: c.len_utf8(),
                    this: CursorData { data: c, pos, view },
                })
            },
        )
    }
}

/// Matches exactly the first character.
impl<'a> Tool<'a> for char {
    type Error = Cursor<'a>;
    type Data = Self;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        AnyChar.parse(st).and_then(|ret| {
            if ret.this.data == *self {
                Ok(ret)
            } else {
                Err(Cursor::from(st))
            }
        })
    }
}

/// Matches exactly the string prefix.
impl<'a> Tool<'a> for str {
    type Error = Cursor<'a>;
    #[allow(clippy::needless_borrows_for_generic_args, clippy::use_self)]
    type Data = &'a str;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        if st.0.view.starts_with(self) {
            let (_, pos, view) = progress(st.0.pos, st.0.view, self.len());
            Ok(CursorLen {
                len: self.len(),
                this: CursorData {
                    data: &st.0.view[0..self.len()],
                    view,
                    pos,
                },
            })
        } else {
            Err(Cursor::from(st))
        }
    }
}

/// Matches any tool in the given slice.
///
/// Tools are evaluated with increasing index ordering, so a later tool would not be tested is a
/// previous tool has already matched.
impl<'a, T> Tool<'a> for [T]
where
    T: Tool<'a>,
{
    type Data = (usize, T::Data);
    /// Only the last error is returned.
    ///
    /// If you want to keep track of every returned error, use instead multiple nested instances of
    /// [`Or`](crate::moretools::Or) tool.
    type Error = Option<T::Error>;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        let mut err = None;

        for (i, t) in self.iter().enumerate() {
            match t.parse(st) {
                Ok(r) => return Ok(r.map_data(|d| (i, d))),
                Err(e) => err = Some(e),
            }
        }
        Err(err)
    }
}

/// Matches any tool in the given array.
///
/// Tools are evaluated with increasing index ordering, so a later tool would not be tested is a
/// previous tool has already matched.
impl<'a, T, const N: usize> Tool<'a> for [T; N]
where
    T: Tool<'a>,
{
    type Data = (usize, T::Data);
    /// Only the last error is returned.
    ///
    /// If you want to keep track of every returned error, use instead multiple nested instances of
    /// [`Or`](crate::moretools::Or) tool.
    type Error = Option<T::Error>;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        let mut err = None;

        for (i, t) in self.iter().enumerate() {
            match t.parse(st) {
                Ok(r) => return Ok(r.map_data(|d| (i, d))),
                Err(e) => err = Some(e),
            }
        }
        Err(err)
    }
}

/// A tool that matches the empty prefix.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct TrueTool;

impl<'a> AlwaysTool<'a> for TrueTool {
    fn parse_always(&self, st: CursorStart<'a>) -> CursorLen<'a, Self::Data> {
        st.into()
    }
}
always_impl!(TrueTool);

/// Tool that matches characters satisfying a predicate.
#[derive(Debug, Clone, Copy)]
pub struct Predicate<P> {
    pub(crate) predicate: P,
}

impl<P> Predicate<P> {
    /// Create a new [`Predicate`] from a predicate.
    pub const fn new(predicate: P) -> Self {
        Self { predicate }
    }
}

impl<'a, P: Fn(char) -> bool> Tool<'a> for Predicate<P> {
    type Data = char;
    type Error = Cursor<'a>;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        AnyChar.parse(st).and_then(|ret| {
            if (self.predicate)(ret.this.data) {
                Ok(ret)
            } else {
                Err(st.into())
            }
        })
    }
}
/// Tool that matches characters satisfying a predicate that also transform the matched character.
#[derive(Debug, Clone, Copy)]
pub struct PredicateData<P> {
    pub(crate) predicate: P,
}

impl<P> PredicateData<P> {
    /// Create a new [`PredicateData`] from a predicate.
    pub const fn new(predicate: P) -> Self {
        Self { predicate }
    }
}

impl<'a, D, P: Fn(char) -> Option<D>> Tool<'a> for PredicateData<P> {
    type Data = (D, usize);
    type Error = Cursor<'a>;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        AnyChar.parse(st).and_then(|ret| {
            ret.try_map_data(|c| {
                (self.predicate)(c)
                    .map(|d| (d, c.len_utf8()))
                    .ok_or_else(|| st.into())
            })
        })
    }
}

/// Parses only the end of the input.
///
/// ```rust
/// use minparser::prelude::*;
/// let st = Cursor::from("My data ");
/// st.chain(&"My data ").unwrap().chain_nodata(&EOFTool).unwrap();
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct EOFTool;

impl<'a> Tool<'a> for EOFTool {
    type Data = ();
    type Error = CursorStart<'a>;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        if st.0.view.is_empty() {
            Ok(st.into())
        } else {
            Err(st)
        }
    }
}

/// Discards empty strings from a match.
///
/// Some atoms that needs to match an undefined number of other atoms (like
/// [`Repeat`](crate::prelude::Repeat) or [`LazyRepeat`](crate::prelude::LazyRepeat))
/// may enter in an infinite loop if the inner atom matches an empty string `""`.
/// In that case there is always a match but the atom does not progress, resulting so in an
/// endless cycle.
///
/// This tool takes another tool and converts any match with an empty string with a missing match,
/// avoiding this issue.
#[derive(Debug, Clone, Copy, Default)]
pub struct NonEmpty<P>(pub P);

impl<'a, P> Tool<'a> for NonEmpty<P>
where
    P: Tool<'a>,
{
    type Data = P::Data;
    type Error = Option<P::Error>;

    fn parse(&self, st: CursorStart<'a>) -> Result<CursorLen<'a, Self::Data>, Self::Error> {
        self.0
            .parse(st)
            .map_err(Some)
            .and_then(|d| if d.len > 0 { Ok(d) } else { Err(None) })
    }
}