fn_bnf/
rules.rs

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
use core::ops::{Index, Range, RangeTo};

#[allow(clippy::wildcard_imports)]
use super::*;

#[macro_export]
/// Convenience macro for quickly defining errors with static messages for use in your grammars.
/// 
/// # Usage
/// ```ignore
/// err! {
///     pub InvalidFloat: "floating point literals must have an integer part",
///     pub(crate) InternalError: "internal error (this is a bug, please report)"
/// }
/// ```
macro_rules! err {
    ($($vis: vis $name: ident: $message: literal),*$(,)?) => {$(
        #[derive(Debug, Copy, Clone, Default)]
        #[doc = $message]
        $vis struct $name;
        impl ::core::fmt::Display for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                write!(f, $message)
            }
        }
        impl ::core::error::Error for $name {}
    )*};
}

/// Maps a function over the output of a rule. See [`Rule::map_parsed`].
#[derive(Debug, Clone, PartialEq, NamedRule)]
pub struct Map<
    'input, SliceType: ?Sized, 
    R: Rule<'input, SliceType>, O, 
    Func: Fn(R::Output) -> O
> {
    pub(crate) inner: R,
    pub(crate) func: Func,
    pub(crate) _p: PhantomData<(&'input SliceType, O)>
}
impl<
    'input, SliceType: ?Sized, 
    R: Rule<'input, SliceType>, O, 
    Func: Fn(R::Output) -> O
> Rule<'input, SliceType> for Map<'input, SliceType, R, O, Func> {
    type Output = Func::Output;

    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input SliceType, index: &'index mut usize)
        -> Result<Self::Output, ParseError> where 'input: 'this 
    {
        self.inner.parse_at(input, index)
            .map(&self.func)
    }
}


/// Attempts to map a function over the output of a rule. See [`Rule::try_map_parsed`].
#[derive(Debug, Clone, PartialEq, NamedRule)]
pub struct TryMap<
    'input, SliceType: ?Sized, 
    R: Rule<'input, SliceType>, O, E: Error + 'static,
    Func: Fn(R::Output) -> Result<O, E>
> {
    pub(crate) inner: R,
    pub(crate) func: Func,
    pub(crate) _p: PhantomData<(&'input SliceType, O)>
}
impl<
    'input, SliceType: ?Sized, 
    R: Rule<'input, SliceType>, O, E: Error + 'static,
    Func: Fn(R::Output) -> Result<O, E>
> Rule<'input, SliceType> for TryMap<'input, SliceType, R, O, E, Func> {
    type Output = O;

    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input SliceType, index: &'index mut usize)
        -> Result<Self::Output, ParseError> where 'input: 'this 
    {
        let start_index = *index;
        let start_input = *input;
        self.inner.parse_at(input, index)
            .and_then(|res| (self.func)(res)
                .map_err(|err| {
                    *index = start_index;
                    *input = start_input;
                    ParseError::new(Some(Box::new(err)), self.inner.name(), start_index)
                })
            )
    }
}


/// Errors if a rule matches.  See [`Rule::prevent`].
#[derive(Debug, Clone, PartialEq, NamedRule)]
pub struct Not<R>(pub(crate) R);

impl<'input, T: ?Sized + 'input, R: Rule<'input, T>> Rule<'input, T> for Not<R> {
    type Output = ();

    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input T, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        let start = *index;
        let res = self.0.parse_at(input, index);
        *index = start;
        let Err(_) = res else {
            return Err(ParseError::new(
                Some(Box::new(UnexpectedMatch)),
                self.name(), start
            ));
        };
        Ok(())
    }
}

/// Attempts to parse a rule, returning its result. See [`Rule::attempt`].
#[derive(NamedRule)]
pub struct Attempt<'input, T: 'input + ?Sized, R: Rule<'input, T>>(pub R, pub(crate) PhantomData<&'input T>);

impl<'input, T: 'input + ?Sized, R: Rule<'input, T>> Rule<'input, T> for Attempt<'input, T, R> {
    type Output = Result<R::Output, ParseError>;
    
    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input T, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        // core::array::try_from_fn(|_| self.0.parse_at(input, index))
        let before = (*input, *index);
        let res = self.0.parse_at(input, index);
        if res.is_err() { (*input, *index) = before; }
        Ok(res)
    }
}

/// Matches a rule forever, failing if it does. See [`Rule::consume_all`].
#[derive(NamedRule)]
pub struct Consume<'input, T: 'input + ?Sized, R: Rule<'input, T>>(pub R, pub(crate) PhantomData<&'input T>);

impl<'input, R: Rule<'input, str>> Rule<'input, str> for Consume<'input, str, R> {
    type Output = Vec<R::Output>;
    
    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input str, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        // core::array::try_from_fn(|_| self.0.parse_at(input, index))
        let before = (*input, *index);
        let mut els = Vec::new();
        while !input.is_empty() {
            let el = match self.0.parse_at(input, index) {
                Ok(v) => v,
                Err(err) => { (*input, *index) = before; return Err(err); }
            };
            els.push(el);
        }
        Ok(els)
    }
}
impl<'input, T: 'input, R: Rule<'input, [T]>> Rule<'input, [T]> for Consume<'input, [T], R> {
    type Output = Vec<R::Output>;
    
    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input [T], index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        // core::array::try_from_fn(|_| self.0.parse_at(input, index))
        let before = (*input, *index);
        let mut els = Vec::new();
        while !input.is_empty() {
            let el = match self.0.parse_at(input, index) {
                Ok(v) => v,
                Err(err) => { (*input, *index) = before; return Err(err); }
            };
            els.push(el);
        }
        Ok(els)
    }
}

/// Repeatedly matches a rule a known amount of times. See [`Rule::repeat_for`].
#[derive(NamedRule)]
pub struct RepeatFor<'input, T: 'input + ?Sized, R: Rule<'input, T>, const REPETITIONS: usize>(pub R, pub(crate) PhantomData<&'input T>);
impl<'input, T: 'input + ?Sized, R: Rule<'input, T>, const REPETITIONS: usize> Rule<'input, T> for RepeatFor<'input, T, R, REPETITIONS> {
    type Output = [R::Output; REPETITIONS];
    
    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input T, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        // core::array::try_from_fn(|_| self.0.parse_at(input, index))
        let before = (*input, *index);
        let mut arr: [Option<R::Output>; REPETITIONS] = [const { None }; REPETITIONS];
        for el in &mut arr {
            el.replace(match self.0.parse_at(input, index) {
                Ok(v) => v,
                Err(err) => {
                    (*input, *index) = before;
                    return Err(err);
                }
            });
        }
        Ok(arr.map(|v| v.unwrap()))
    }
}

/// Matches a rule a set amount of times. See [`Rule::repeat`]
#[derive(NamedRule)]
pub struct Repeat<'input, T: 'input + ?Sized, R: Rule<'input, T>>(pub R, pub usize, pub(crate) PhantomData<&'input T>);
impl<'input, T: 'input + ?Sized, R: Rule<'input, T>> Rule<'input, T> for Repeat<'input, T, R> {
    type Output = Vec<R::Output>;
    
    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input T, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        // core::array::try_from_fn(|_| self.0.parse_at(input, index))
        let before = (*input, *index);
        let mut arr = Vec::with_capacity(self.1);
        for _ in 0..self.1 {
            arr.push(match self.0.parse_at(input, index) {
                Ok(v) => v,
                Err(err) => {
                    (*input, *index) = before;
                    return Err(err);
                }
            });
        }
        Ok(arr)
    }
}

/// Matches a rule an arbitrary amount of times. See [`Rule::take`].
#[derive(NamedRule)]
pub struct Many<'input, T: 'input + ?Sized, R: Rule<'input, T>> {
    rule: R,
    limit: Option<usize>,
    _p: PhantomData<&'input T>
}

impl<'input, T: 'input + ?Sized, R: Rule<'input, T>> Many<'input, T, R> {
    /// Matches a potentially infinite amount of times
    pub fn unlimited(rule: R) -> Self {
        Self { rule, limit: None, _p: PhantomData }
    }

    /// Matches at most a set amount of times.
    pub fn limited(rule: R, limit: usize) -> Self {
        Self { rule, limit: Some(limit), _p: PhantomData }
    }
}

impl<'input, T: 'input + ?Sized, R: Rule<'input, T>> Rule<'input, T> for Many<'input, T, R> {
    type Output = Vec<R::Output>;
    
    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input T, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        // core::array::try_from_fn(|_| self.0.parse_at(input, index))
        let mut arr = Vec::new();
        let mut i = 0;
        while let Ok(res) = self.rule.parse_at(input, index) {
            arr.push(res);
            i += 1;
            if self.limit.is_some_and(|limit| limit >= i) {
                break;
            }
        }
        Ok(arr)
    }
}

/// Matches one of any character or slice member. Fails on empty input.
/// 
/// # Example
/// ```ignore
/// Double: (char, char) = Any, arg_0;
/// ```
#[derive(Debug, Copy, Clone, NamedRule)]
pub struct Any;
impl<'input, T: 'input> Rule<'input, [T]> for Any {
    type Output = &'input T;

    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input [T], index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        (!input.is_empty())
            .then(|| {
                let source = &input[0];
                *input = &input[1..];
                *index += 1;
                source
            })
            .ok_or(ParseError::new(Some(Box::new(UnexpectedEOF)), self.name(), *index))
    }
}

impl<'input> Rule<'input, str> for Any {
    type Output = char;

    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input str, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        input.chars().next()
            .inspect(|chr| {
                let len = chr.len_utf8();
                *input = &input[len..];
                *index += len;
            })
            .ok_or(ParseError::new(Some(Box::new(UnexpectedEOF)), self.name(), *index))
    }
}

/// Takes input until a given function fails.
/// 
/// # Example
/// ```ignore
/// number: &'input str = While::from(char::is_ascii_digit)
/// ```
#[derive(Debug, Clone, PartialEq, NamedRule)]
pub struct While<F, T> { func: F, _p: PhantomData<T> }

impl<T, F: Fn(&T) -> bool> While<F, T> {
    /// Creates a [`While`] rule from a function. 
    pub fn from(func: F) -> Self {
        Self { func, _p: PhantomData }
    }
}

impl<'input, F: Fn(&char) -> bool> Rule<'input, str> for While<F, char> {
    type Output = &'input str;

    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input str, index: &'index mut usize)
        -> Result<Self::Output, ParseError> where 'input: 'this
    {
        let offset = input.find(|c: char| !(self.func)(&c))
            .unwrap_or(input.len());

        let res = &input[..offset];
        *input = &input[offset..];
        *index += offset;
        Ok(res)
    }
}

impl<'input, T: 'input, F: Fn(&T) -> bool> Rule<'input, [T]> for While<F, T> {
    type Output = &'input [T];

    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input [T], index: &'index mut usize)
        -> Result<Self::Output, ParseError> where 'input: 'this
    {
        let offset = (*input).iter().position(|c: &T| !(self.func)(c))
            .unwrap_or(input.len());

        let res = &input[..offset];
        *input = &input[offset..];
        *index += offset;
        Ok(res)
    }
}

/// Struct returned by [`Rule::spanned`] to store the span and source of a given parsed rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span<'input, T: 'input + ?Sized, O> {
    /// The range of the input that the rule parsed over.
    pub span: Range<usize>,
    /// The original input that the rule parsed.
    pub source: &'input T,
    /// The output of the rule's parsing.
    pub output: O
}

/// Records the span of a given rule. See [`Rule::spanned`].
#[derive(NamedRule)]
pub struct Spanned<'input, T: 'input + ?Sized, R: Rule<'input, T>> { pub(crate) rule: R, pub(crate) _p: PhantomData<&'input T> }

impl<'input, T: 'input + Index<RangeTo<usize>, Output = T> + ?Sized, R: Rule<'input, T>> Rule<'input, T> for Spanned<'input, T, R> {
    type Output = Span<'input, T, R::Output>;
    
    fn parse_at<'cursor, 'this, 'index>(&'this self, input: &'cursor mut &'input T, index: &'index mut usize) -> Result<Self::Output, ParseError> where 'input: 'this {
        let before = (*input, *index);
        let res = self.rule.parse_at(input, index)?;
        Ok(Span {
            span: before.1 .. *index,
            source: &before.0[..*index - before.1],
            output: res
        })
    }
}


/// Always fails with a given error.
/// 
/// # Example
/// ```ignore
/// uh_oh: u32 = Fail::new(Error::new("oh no!"))
/// ```
#[derive(Debug, PartialEq, NamedRule)]
pub struct Fail<E: core::error::Error + Clone + 'static>(pub E);

impl<E: core::error::Error + Clone + 'static> Fail<E> {
    /// Creates a new instance of this type.
    #[inline]
    pub fn new(err: E) -> Self {
        Self(err)
    }
}

impl<'input, T: ?Sized + 'input, E: core::error::Error + Clone + 'static> Rule<'input, T> for Fail<E> {
    type Output = crate::Never;

    fn parse_at<'cursor, 'this, 'index>(&'this self, _input: &'cursor mut &'input T, index: &'index mut usize)
        -> Result<Self::Output, ParseError> where 'input: 'this
    {
        Err(ParseError::new(Some(Box::new(self.0.clone())), self.name(), *index))
    }
}

/// Alias for a refernce to a `dyn` Rule object of a given type and output.
/// 
/// You can use this with an `as` cast in a `match` statement to allow each statement to be a separate rule:
/// ```ignore
/// t: (char, char) = Any, match arg_0 {
///     'a' => &'b' as AnyRule<str, char>,
///     'b' => &Any as AnyRule<str, char>,
///     other => &Fail(Unexpected::new(other)) as AnyRule<str, char>
/// };
/// ```
pub type AnyRule<'rule, 'input, In, Out> = &'rule dyn Rule<'input, In, Output = Out>;