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
/*
 * 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,
}

impl<'a> From<&'a str> for View<'a> {
    fn from(s : &'a str) -> Self {
        Self::new(s)
    }
}

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
    }
    /// Progress the view and its position.
    ///
    /// The first element returned is the portion of the string that is skipped.
    ///
    /// # Panics
    /// Panics if `inc` doesn't lie on UTF-8 code point boundaries.
    #[must_use]
    pub fn progress(self, inc : usize) -> (&'a str, Self) {
        if inc == 0 {
            ("", self)
        }
        else{
            let (pfx, sfx) = self.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) = self.pos.unpack();
            if nls > 0 {
                c = 0;
                r += nls;
            }
            c += u32::try_from(elem.len()).unwrap();
            (pfx, Self{
                pos : Position::new(r, c),
                view : sfx,
            })
        }
    }
    /// Match a parsing tool.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_tool<T : Tool<'a>>(self, t : &T) -> Result<Self, T::Error> {
        t.parse(self).map(|i| i.2)
    }
    /// Apply a tool that always match.
    #[allow(clippy::missing_errors_doc)]
    #[must_use]
    pub fn match_always<T : AlwaysTool<'a>>(self, t : &T) -> Self {
        t.parse_always(self).2
    }
    /// Matches a parsing tool and returns the matched string.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_tool_string<T : Tool<'a>>(self, t : &T) -> Result<(&'a str, Self), T::Error> {
        let vw = self.get_view();
        t.parse(self).map(|i| (&vw[0..i.1], i.2))
    }
    /// Matches a parsing tool and returns associated data.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_tool_data<T : Tool<'a>>(self, t : &T) -> Result<(T::Data, Self), T::Error> {
        t.parse(self).map(|i| (i.0, i.2))
    }
    /// Matches an infallible tool and returns associated data.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_always_data<T : AlwaysTool<'a>>(self, t : &T) -> (T::Data, Self) {
        let i = t.parse_always(self);
        (i.0, i.2)
    }
    /// Matches a parsing tool and returns associated data and the length of the match.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_tool_data_len<T : Tool<'a>>(self, t : &T) -> Result<(T::Data, usize, Self), T::Error> {
        t.parse(self)
    }
    /// Matches a tool and applies a transformation on the returned data.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_map<D, T, F>(self, t : &T, f : F) -> Result<(D, Self), T::Error> where 
        T : Tool<'a>,
        F : FnOnce(T::Data, Position) -> D
    {
        self.match_tool_data(t)
            .map(|(d, s)| (f(d, s.pos), s))
    }
    /// Matches a tool and applies a transformation on both the data and the error object.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_map_err<D, E, T, F, G>(self, t : &T, f : F, g : G) -> Result<(D, Self), E> where 
        T : Tool<'a>,
        F : FnOnce(T::Data, Position) -> D,
        G : FnOnce(T::Error) -> E 
    {
        self.match_tool_data(t)
            .map(|(d, s)| (f(d, s.pos), s))
            .map_err(g)
    }
    /// Matches a tool only if another tool matches.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_if_matches<PRE : Tool<'a>, R : Tool<'a>>(self, pre : &PRE, t : &R) -> Result<Self, R::Error> {
        self.match_tool(pre).map_or(
            Ok(self),
            |next| next.match_tool(t))
    }
    /// Match the `th` tool only if `test` tool matches, otherwise execute `els` closure.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_if_else_data<PRE : Tool<'a>, R : Tool<'a>, ELS>(self, pre : &PRE, t : &R, els : ELS) -> Result<(R::Data, Self), R::Error> where 
        ELS : FnOnce(Self) -> Result<(R::Data, Self), R::Error> 
    {
        self.match_tool(pre)
            .map_or_else(
                |_| els(self),
                |next|next.match_tool_data(t))
    }
    /// Match (with length) the `th` tool only if `test` tool matches, otherwise execute `els` closure.
    #[allow(clippy::missing_errors_doc)]
    pub fn match_if_else_data_len<PRE : Tool<'a>, R : Tool<'a>, ELS>(self, pre : &PRE, t : &R, els : ELS) -> Result<(R::Data, usize, Self), R::Error> where 
        ELS : FnOnce(Self) -> Result<(R::Data, usize, Self), R::Error> 
    {
        self.match_tool(pre)
            .map_or_else(
                |_| els(self),
                |next| next.match_tool_data_len(t))
    }
}

/// 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.
    ///
    /// # Errors
    /// If no prefix of `st` satisfies this parsing strategy then `Error` is returned.
    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>;
}
/// 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 : View<'a>) -> (Self::Data, usize, View<'a>);

    /// Automatically discards the generated data.
    fn parse_always_nodata(&self, st : View<'a>) -> ((), usize, View<'a>) {
        let (_, l, s) = self.parse_always(st);
        ((), l, s)
    }
}

/// Set arbitrary error type for [`AlwaysTool`].
///
/// Some objects here require tools with a specific error type. Tools implementing [`AlwaysTool`]
/// never issue an error therefore it should be possible to pass them to these objects. This
/// wrapper reimplement [`Tool`] but allows you to explicitly select any type as error type.
#[derive(Debug)]
pub struct SetError<T, E>(pub T, pub ::core::marker::PhantomData<fn() -> E>);

impl<T, E> SetError<T, E> {
    /// Creates a new `SetError`.
    pub fn new(d : T) -> Self {
        Self(d, ::core::marker::PhantomData)
    }
}
impl<T : Clone, E> Clone for SetError<T, E> {
    fn clone(&self) -> Self {
        Self::new(self.0.clone())
    }
}
impl<T : Copy, E> Copy for SetError<T, E> {}
impl<T : Default, E> Default for SetError<T, E> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T, E, B> AsRef<B> for SetError<T, E> where T : AsRef<B>, B : ?Sized {
    fn as_ref(&self) -> &B {
        self.0.as_ref()
    }
}

impl<'a, T, E> AlwaysTool<'a> for SetError<T, E> where T : AlwaysTool<'a> {
    fn parse_always(&self, st : View<'a>) -> (Self::Data, usize, View<'a>) {
        self.0.parse_always(st)
    }
}
impl<'a, T, E> Tool<'a> for SetError<T, E> where T : AlwaysTool<'a> {
    type Error = E;
    type Data = T::Data;

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

/// Applies a function to both data and error value.
#[derive(Debug, Copy, Clone)]
pub struct MapTool<T, FD, FE>(pub T, pub FD, pub FE);

impl<'a, T, D, E, FD, FE> Tool<'a> for MapTool<T, FD, FE> where
    T : Tool<'a>,
    FD : Fn(T::Data) -> D,
    FE : Fn(T::Error) -> E
{
    type Data = D;
    type Error = E;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error> {
        self.0.parse(st)
            .map(|(d, l, st)| ((self.1)(d), l, st) )
            .map_err(&self.2)
    }
}
impl<'a, T, D, E, FD, FE> AlwaysTool<'a> for MapTool<T, FD, FE> where
    T : AlwaysTool<'a>,
    FD : Fn(T::Data) -> D,
    FE : Fn(T::Error) -> E
{
    fn parse_always(&self, st : View<'a>) -> (Self::Data, usize, View<'a>) {
        let (d, l, st) = self.0.parse_always(st);
        ((self.1)(d), l, st)
    }
}

/// 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 : View<'a>) -> Result<(Self::Data, usize, View<'a>), 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 : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        T::parse(*self, st)
    }
}
impl<'a, T> AlwaysTool<'a> for &T where T : AlwaysTool<'a> + ?Sized {
    fn parse_always(&self, st : View<'a>) -> (Self::Data, usize, View<'a>) {
        T::parse_always(*self, st)
    }
}

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

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        st.get_view().chars().next()
            .and_then(|c| if c == *self {
                Some((c, c.len_utf8(), st.progress(c.len_utf8()).1))
            }
            else {
                None
            })
        .ok_or(st)
    }
}

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

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        if st.get_view().starts_with(self) {
            Ok((&st.get_view()[0..self.len()], self.len(), st.progress(self.len()).1))
        }
        else {
            Err(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 : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        let mut err = None;

        for (i, t) in self.iter().enumerate() {
            match t.parse(st) {
                Ok(r) => return Ok(((i, r.0), r.1, r.2)),
                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 : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        let mut err = None;

        for (i, t) in self.iter().enumerate() {
            match t.parse(st) {
                Ok(r) => return Ok(((i, r.0), r.1, r.2)),
                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 : View<'a>) -> (Self::Data, usize, View<'a>) {
        ((), 0, st)
    }
}
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 = View<'a>;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        st.get_view().chars().next().and_then(
                |c| if (self.predicate)(c) {
                    Some((c, c.len_utf8(), st.progress(c.len_utf8()).1))
                }
                else {
                    None
                })
            .ok_or(st)
    }
}
/// 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<D, P : Fn(char) -> Option<D> > PredicateData<P> {
    /// Tests if the first character satisfy the predicate, and in the affirmative case the matched
    /// character and its length are returned.
    pub fn parse_char(&self, st : &str) -> Option<(D, usize)> {
        st.chars().next().and_then(|c| {
            (self.predicate)(c).map(|d| (d, c.len_utf8()))
        })
    }
}
impl<'a, D, P : Fn(char) -> Option<D>> Tool<'a> for PredicateData<P>{
    type Data = D;
    type Error = View<'a>;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        st.get_view().chars().next().and_then(
                |c| (self.predicate)(c).map(|d| (d, c.len_utf8())))
            .map(|(d, l)| (d, l, st.progress(l).1))
            .ok_or(st)
    }
}

/// 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 = View<'a>;

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        st.get_view().chars().next()
            .map(|c| (c, c.len_utf8(), st.progress(c.len_utf8()).1))
            .ok_or(st)
    }
}

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

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

    fn parse(&self, st : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        if st.is_empty() {
            Ok(((), 0, st))
        }
        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 : View<'a>) -> Result<(Self::Data, usize, View<'a>), Self::Error>{
        self.0.parse(st)
            .map_err(Some)
            .and_then(|d| if d.1 > 0 {Ok(d)} else {Err(None)})
    }
}