textparse 0.1.0

A library to declaratively implement parsers that are based on Packrat Parsing
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
//! Basic components.
use crate::{Parse, Parser, Position, Span};
use std::marker::PhantomData;

/// Empty item.
#[derive(Debug, Clone, Copy, Span)]
pub struct Empty {
    position: Position,
}

impl Parse for Empty {
    fn parse(parser: &mut Parser) -> Option<Self> {
        Some(Self {
            position: parser.current_position(),
        })
    }
}

/// Either `A` or `B`.
#[derive(Debug, Clone, Copy, Span, Parse)]
#[allow(missing_docs)]
pub enum Either<A, B> {
    A(A),
    B(B),
}

/// One of `A`, `B`, or `C`.
#[derive(Debug, Clone, Copy, Span, Parse)]
#[allow(missing_docs)]
pub enum OneOfThree<A, B, C> {
    A(A),
    B(B),
    C(C),
}

/// One of `A`, `B`, `C`, or `D`.
#[derive(Debug, Clone, Copy, Span, Parse)]
#[allow(missing_docs)]
pub enum OneOfFour<A, B, C, D> {
    A(A),
    B(B),
    C(C),
    D(D),
}

/// Optional item.
#[derive(Debug, Clone, Copy, Span)]
pub struct Maybe<T>(Either<T, Empty>);

impl<T> Maybe<T> {
    /// Returns `Some(T)` if the item exists, otherwise `None`.
    pub fn get(&self) -> Option<&T> {
        if let Either::A(t) = &self.0 {
            Some(t)
        } else {
            None
        }
    }
}

impl<T: Parse> Parse for Maybe<T> {
    fn parse(parser: &mut Parser) -> Option<Self> {
        parser.parse().map(Self)
    }
}

/// Indicating to continue parsing while `T::parse()` is succeeded.
#[derive(Debug, Span)]
pub struct While<T> {
    start_position: Position,
    _phantom: PhantomData<T>,
    end_position: Position,
}

impl<T: Parse> Parse for While<T> {
    fn parse(parser: &mut Parser) -> Option<Self> {
        let start_position = parser.current_position();
        while parser.parse::<T>().is_some() {}
        let end_position = parser.current_position();
        Some(Self {
            start_position,
            end_position,
            _phantom: PhantomData,
        })
    }
}

impl<T> Clone for While<T> {
    fn clone(&self) -> Self {
        Self {
            start_position: self.start_position,
            _phantom: self._phantom,
            end_position: self.end_position,
        }
    }
}

impl<T> Copy for While<T> {}

/// A whitespace (cf. [`char::is_ascii_whitespace()`]).
#[derive(Debug, Clone, Copy, Span)]
pub struct Whitespace {
    start_position: Position,
    end_position: Position,
}

impl Parse for Whitespace {
    fn parse(parser: &mut Parser) -> Option<Self> {
        let start_position = parser.current_position();
        parser
            .read_char()
            .filter(|c| c.is_ascii_whitespace())
            .map(|_| Self {
                start_position,
                end_position: parser.current_position(),
            })
    }
}

/// A character.
#[derive(Debug, Clone, Copy, Span)]
pub struct AnyChar {
    start_position: Position,
    value: char,
    end_position: Position,
}

impl AnyChar {
    /// Returns the character value.
    pub fn get(&self) -> char {
        self.value
    }
}

impl Parse for AnyChar {
    fn parse(parser: &mut Parser) -> Option<Self> {
        let start_position = parser.current_position();
        let value = parser.read_char()?;
        let end_position = parser.current_position();
        Some(Self {
            start_position,
            value,
            end_position,
        })
    }
}

/// A specific character.
#[derive(Debug, Clone, Copy, Span)]
pub struct Char<const T: char, const NAMED: bool = true> {
    start_position: Position,
    end_position: Position,
}

impl<const T: char, const NAMED: bool> Parse for Char<T, NAMED> {
    fn parse(parser: &mut Parser) -> Option<Self> {
        let start_position = parser.current_position();
        parser.read_char().filter(|c| *c == T).map(|_| Self {
            start_position,
            end_position: parser.current_position(),
        })
    }

    fn name() -> Option<fn() -> String> {
        if NAMED {
            Some(|| format!("{T:?}"))
        } else {
            None
        }
    }
}

/// A specified string (characters).
#[derive(Debug, Clone, Copy, Span)]
pub struct Str<
    const C0: char = '\0',
    const C1: char = '\0',
    const C2: char = '\0',
    const C3: char = '\0',
    const C4: char = '\0',
    const C5: char = '\0',
    const C6: char = '\0',
    const C7: char = '\0',
    const C8: char = '\0',
    const C9: char = '\0',
> {
    start_position: Position,
    end_position: Position,
}

impl<
        const C0: char,
        const C1: char,
        const C2: char,
        const C3: char,
        const C4: char,
        const C5: char,
        const C6: char,
        const C7: char,
        const C8: char,
        const C9: char,
    > Parse for Str<C0, C1, C2, C3, C4, C5, C6, C7, C8, C9>
{
    fn parse(parser: &mut Parser) -> Option<Self> {
        let start_position = parser.current_position();
        for c in [C0, C1, C2, C3, C4, C5, C6, C7, C8, C9] {
            if c == '\0' {
                break;
            }
            if parser.read_char() != Some(c) {
                return None;
            }
        }
        let end_position = parser.current_position();
        Some(Self {
            start_position,
            end_position,
        })
    }

    fn name() -> Option<fn() -> String> {
        Some(|| {
            let mut s = String::new();
            for c in [C0, C1, C2, C3, C4, C5, C6, C7, C8, C9] {
                if c == '\0' {
                    break;
                }
                s.push(c);
            }
            s
        })
    }
}

#[derive(Debug, Clone)]
struct NonEmptyItems<Item, Delimiter> {
    items: Vec<Item>,
    delimiters: Vec<Delimiter>,
}

impl<Item, Delimiter> NonEmptyItems<Item, Delimiter> {
    fn items(&self) -> &[Item] {
        &self.items
    }

    fn delimiters(&self) -> &[Delimiter] {
        &self.delimiters
    }
}

impl<Item: Span, Delimiter: Span> Span for NonEmptyItems<Item, Delimiter> {
    fn start_position(&self) -> Position {
        self.items[0].start_position()
    }

    fn end_position(&self) -> Position {
        self.items[self.items.len() - 1].end_position()
    }
}

impl<Item: Parse, Delimiter: Parse> Parse for NonEmptyItems<Item, Delimiter> {
    fn parse(parser: &mut Parser) -> Option<Self> {
        let mut items = vec![parser.parse::<Item>()?];
        let mut delimiters = Vec::new();
        while let Some(delimiter) = parser.parse::<Delimiter>() {
            delimiters.push(delimiter);
            items.push(parser.parse()?);
        }
        Some(Self { items, delimiters })
    }
}

/// Variable length items split by delimiters.
#[derive(Debug, Clone, Span, Parse)]
pub struct Items<Item, Delimiter>(Maybe<NonEmptyItems<Item, Delimiter>>);

impl<Item, Delimiter> Items<Item, Delimiter> {
    /// Returns items.
    pub fn items(&self) -> &[Item] {
        self.0.get().map_or(&[], |t| t.items())
    }

    /// Returns delimiters.
    pub fn delimiters(&self) -> &[Delimiter] {
        self.0.get().map_or(&[], |t| t.delimiters())
    }
}

/// Non-empty item.
#[derive(Debug, Clone, Copy, Span)]
pub struct NonEmpty<T>(T);

impl<T> NonEmpty<T> {
    /// Returns the item.
    pub fn get(&self) -> &T {
        &self.0
    }
}

impl<T: Parse> Parse for NonEmpty<T> {
    fn parse(parser: &mut Parser) -> Option<Self> {
        let item: T = parser.parse()?;
        if item.is_empty() {
            None
        } else {
            Some(Self(item))
        }
    }
}

/// End-Of-String.
#[derive(Debug, Clone, Copy, Span)]
pub struct Eos {
    position: Position,
}

impl Parse for Eos {
    fn parse(parser: &mut Parser) -> Option<Self> {
        if parser.is_eos() {
            Some(Self {
                position: parser.current_position(),
            })
        } else {
            None
        }
    }

    fn name() -> Option<fn() -> String> {
        Some(|| "EOS".to_owned())
    }
}

/// Not a specified item.
#[derive(Debug)]
pub struct Not<T> {
    position: Position,
    _item: PhantomData<T>,
}

impl<T> Clone for Not<T> {
    fn clone(&self) -> Self {
        Self {
            position: self.position,
            _item: self._item,
        }
    }
}

impl<T> Copy for Not<T> {}

impl<T> Span for Not<T> {
    fn start_position(&self) -> Position {
        self.position
    }

    fn end_position(&self) -> Position {
        self.position
    }
}

impl<T: Parse> Parse for Not<T> {
    fn parse(parser: &mut Parser) -> Option<Self> {
        if parser.parse::<T>().is_none() {
            let position = parser.current_position();
            Some(Self {
                position,
                _item: PhantomData,
            })
        } else {
            None
        }
    }

    fn name() -> Option<fn() -> String> {
        if T::name().is_none() {
            None
        } else {
            Some(|| format!("not {}", T::name().unwrap()()))
        }
    }
}

/// A digit.
#[derive(Debug, Clone, Copy, Span)]
pub struct Digit<const RADIX: u8 = 10> {
    start_position: Position,
    value: u8,
    end_position: Position,
}

impl<const RADIX: u8> Digit<RADIX> {
    /// Returns the digit value.
    pub const fn get(self) -> u8 {
        self.value
    }
}

impl<const RADIX: u8> Parse for Digit<RADIX> {
    fn parse(parser: &mut Parser) -> Option<Self> {
        let start_position = parser.current_position();
        let value = parser
            .read_char()
            .and_then(|c| c.to_digit(u32::from(RADIX)))? as u8;
        Some(Self {
            start_position,
            value,
            end_position: parser.current_position(),
        })
    }
}