tygr 0.1.0

Define your grammar once as Rust types and get a parser, printer, and EBNF presentation for free.
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
//! Character class support for grammars.
//!
//! - [`CharClass`] — trait for character predicates
//! - [`CharOf<M>`] — match one character
//! - [`StringOf<M>`] — match zero or more characters
//! - [`StringOf1<M>`] — match one or more characters
//! - [`StringEq<T>`] — match a literal token described by the type-level chain `T`

use std::char;
use std::fmt;
use std::marker::PhantomData;

#[cfg(feature = "trace_attempts")]
use crate::Expectation;
use crate::bnf::Expr;
use crate::char_class;
use crate::grammar::{AnyCharFirst, CharFirst, CharFirstCI, EmptyFirst, First, Grammar};
use crate::state::State;
use crate::{IntoInner, Raw};

/// Trait for character-class predicates.
///
/// The easiest way to define one is the [`char_class!`](crate::char_class)
/// macro:
///
/// ```
/// # use tygr::*;
/// char_class!(IsDigit, "digit", |ch| ch.is_ascii_digit());
/// char_class!(IsSpace, "space", |ch| matches!(ch, ' ' | '\t'));
/// char_class!(IsLower, "lower", |ch| matches!(ch, 'a'..='z'));
/// ```
///
/// For advanced cases you can implement the trait manually on a zero-sized
/// struct:
///
/// ```
/// # use tygr::*;
/// struct IsDigit;
/// impl CharClass for IsDigit {
///     fn matches(ch: char) -> bool { ch.is_ascii_digit() }
///     fn name() -> &'static str { "digit" }
/// }
/// ```
pub trait CharClass: 'static {
    /// Does `ch` belong to this character class?
    fn matches(ch: char) -> bool;

    /// Human-readable label (used in error messages and BNF).
    fn name() -> &'static str;
}

char_class!(pub AnyChar, "any", |_c| true);

/// Matches exactly one character satisfying `M`.
pub struct CharOf<M: CharClass>(pub char, PhantomData<M>);

impl<M: CharClass> Clone for CharOf<M> {
    fn clone(&self) -> Self {
        Self(self.0, self.1)
    }
}

impl<M: CharClass> PartialEq for CharOf<M> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<M: CharClass> Eq for CharOf<M> {}

impl<M: CharClass> fmt::Debug for CharOf<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CharOf({:?})", self.0)
    }
}

impl<M: CharClass> CharOf<M> {
    pub fn new(ch: char) -> Self {
        CharOf(ch, PhantomData)
    }

    pub fn value(&self) -> char {
        self.0
    }
}

impl<M: CharClass> Grammar for CharOf<M> {
    type First = AnyCharFirst;

    #[inline]
    fn parse_at(
        input: &str,
        pos: usize,
        #[allow(unused_variables, unused_mut)] mut state: State,
    ) -> Option<(Self, usize)> {
        let ch = match input.as_bytes().get(pos) {
            // If ASCII, skips &str invariant checks
            Some(&b) if b < 0x80 => {
                if M::matches(b as char) {
                    Some((b as char, 1))
                } else {
                    None
                }
            }
            Some(_) => input[pos..]
                .chars()
                .next()
                .filter(|c: &char| M::matches(*c))
                .map(|c| (c, c.len_utf8())),
            None => None,
        };
        if let Some((ch, len)) = ch {
            Some((CharOf(ch, PhantomData), pos + len))
        } else {
            #[cfg(feature = "trace_any")]
            state.expect(
                pos,
                #[cfg(feature = "trace_attempts")]
                Expectation::CharClass(M::name()),
            );
            None
        }
    }

    #[inline]
    fn scan_at(input: &str, pos: usize, state: State) -> Option<usize> {
        Self::parse_at(input, pos, state).map(|(_, pos)| pos)
    }

    fn print_to(&self, buf: &mut String) {
        buf.push(self.0);
    }

    fn to_bnf() -> Expr {
        Expr::CharOf(M::name().to_string())
    }
}

/// Matches **zero or more** characters satisfying `M`, collected into a `String`.
///
/// ```
/// # use tygr::*;
/// # char_class!(IsSpace, "space", |ch| matches!(ch, ' ' | '\t'));
/// type Ws = StringOf<IsSpace>;  // optional whitespace
/// ```
pub struct StringOf<C: CharClass>(Raw<Vec<CharOf<C>>>);

impl<C: CharClass> Grammar for StringOf<C> {
    type First = <Raw<Vec<CharOf<C>>> as Grammar>::First;

    fn parse_at(input: &str, pos: usize, state: State) -> Option<(Self, usize)> {
        let (inner, pos) = Raw::parse_at(input, pos, state)?;
        Some((StringOf(inner), pos))
    }

    fn scan_at(input: &str, pos: usize, state: State) -> Option<usize> {
        Raw::<Vec<CharOf<C>>>::scan_at(input, pos, state)
    }

    fn print_to(&self, buf: &mut String) {
        self.0.print_to(buf);
    }

    fn to_bnf() -> Expr {
        Raw::<Vec<CharOf<C>>>::to_bnf()
    }
}

/// Matches **one or more** characters satisfying `M`, collected into a `String`.
///
/// ```
/// # use tygr::*;
/// # char_class!(IsDigit, "digit", |ch| ch.is_ascii_digit());
/// #[derive(Grammar)]
/// struct Number(StringOf1<IsDigit>);  // one or more digits
/// ```
pub struct StringOf1<C: CharClass>(Raw<(CharOf<C>, Vec<CharOf<C>>)>);

impl<C: CharClass> Grammar for StringOf1<C> {
    type First = <Raw<(CharOf<C>, Vec<CharOf<C>>)> as Grammar>::First;

    fn parse_at(input: &str, pos: usize, state: State) -> Option<(Self, usize)> {
        let (inner, pos) = Raw::parse_at(input, pos, state)?;
        Some((StringOf1(inner), pos))
    }

    fn scan_at(input: &str, pos: usize, state: State) -> Option<usize> {
        Raw::<(CharOf<C>, Vec<CharOf<C>>)>::scan_at(input, pos, state)
    }

    fn print_to(&self, buf: &mut String) {
        self.0.print_to(buf);
    }

    fn to_bnf() -> Expr {
        Raw::<(CharOf<C>, Vec<CharOf<C>>)>::to_bnf()
    }
}

/// Delegates the string-facing trait impls to the inner `Raw`.
macro_rules! impl_string_wrapper {
    ($ty:ident) => {
        impl<C: CharClass> fmt::Debug for $ty<C> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Debug::fmt(&self.0, f)
            }
        }
        impl<C: CharClass> fmt::Display for $ty<C> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Display::fmt(&self.0, f)
            }
        }
        impl<C: CharClass> Clone for $ty<C> {
            fn clone(&self) -> Self {
                $ty(self.0.clone())
            }
        }
        impl<C: CharClass> PartialEq for $ty<C> {
            fn eq(&self, other: &Self) -> bool {
                self.0 == other.0
            }
        }
        impl<C: CharClass> Eq for $ty<C> {}
        impl<C: CharClass> std::hash::Hash for $ty<C> {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                self.0.hash(state);
            }
        }
        impl<C: CharClass> std::ops::Deref for $ty<C> {
            type Target = str;
            fn deref(&self) -> &str {
                &self.0
            }
        }
        impl<C: CharClass> AsRef<str> for $ty<C> {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }
        impl<C: CharClass> IntoInner<String> for $ty<C> {
            fn into_inner(self) -> String {
                self.0.0
            }
        }
    };
}

impl_string_wrapper!(StringOf);
impl_string_wrapper!(StringOf1);

/// Describes a literal-token chain: enough to match (`scan_at`) and describe
/// (`add_expectation`) itself; no `Self` value is ever built.
// `pub`, not private: `StringEq<T>`'s `Grammar::First = T::First` would
// otherwise leak a private trait's associated type (E0446).
#[doc(hidden)]
pub trait Token: 'static {
    type First: First;

    fn scan_at(input: &str, pos: usize, state: State) -> Option<usize>;

    fn add_expectation(str: &mut String);

    fn expectation() -> String {
        let mut str = String::new();
        Self::add_expectation(&mut str);
        str
    }
}

impl Token for () {
    type First = EmptyFirst;

    fn scan_at(_input: &str, pos: usize, _state: State) -> Option<usize> {
        Some(pos)
    }

    fn add_expectation(_: &mut String) {}
}

/// Matches literal char `CH`, then `T`. `StringEq!("…")` expands to a chain of these.
pub struct CharThen<const CH: char, T>(PhantomData<T>);

impl<const CH: char, T: Token> Token for CharThen<CH, T> {
    type First = CharFirst<CH>;

    #[inline]
    fn scan_at(
        input: &str,
        pos: usize,
        #[allow(unused_variables, unused_mut)] mut state: State,
    ) -> Option<usize> {
        if input[pos..].starts_with(CH) {
            T::scan_at(input, pos + CH.len_utf8(), state)
        } else {
            #[cfg(feature = "trace_any")]
            state.expect(
                pos,
                #[cfg(feature = "trace_attempts")]
                Expectation::StringEq(Self::expectation()),
            );
            None
        }
    }

    fn add_expectation(str: &mut String) {
        str.push(CH);
        T::add_expectation(str);
    }
}

/// Case-insensitive [`CharThen`]. `StringEqCI!("…")` expands to a chain of these.
pub struct CharCIThen<const CH: char, T>(PhantomData<T>);

impl<const CH: char, T: Token> Token for CharCIThen<CH, T> {
    type First = CharFirstCI<CH>;

    #[inline]
    fn scan_at(
        input: &str,
        pos: usize,
        #[allow(unused_variables, unused_mut)] mut state: State,
    ) -> Option<usize> {
        match input[pos..].chars().next() {
            Some(c) if c.eq_ignore_ascii_case(&CH) => T::scan_at(input, pos + c.len_utf8(), state),
            _ => {
                #[cfg(feature = "trace_any")]
                state.expect(
                    pos,
                    #[cfg(feature = "trace_attempts")]
                    Expectation::StringEqCI(Self::expectation()),
                );
                None
            }
        }
    }

    fn add_expectation(str: &mut String) {
        str.push(CH);
        T::add_expectation(str);
    }
}

/// `Grammar` for a `StringEq!` chain. Case-sensitive, so the matched text is
/// always exactly `T::expectation()` — nothing needs to be stored per match.
pub struct StringEq<T>(PhantomData<T>);

impl<T: Token> Grammar for StringEq<T> {
    type First = T::First;

    #[inline]
    fn parse_at(input: &str, pos: usize, state: State) -> Option<(Self, usize)> {
        let end = T::scan_at(input, pos, state)?;
        Some((StringEq(PhantomData), end))
    }

    #[inline]
    fn scan_at(input: &str, pos: usize, state: State) -> Option<usize> {
        T::scan_at(input, pos, state)
    }

    fn print_to(&self, buf: &mut String) {
        T::add_expectation(buf);
    }

    fn to_bnf() -> Expr {
        Expr::Literal(T::expectation())
    }
}

impl<T: Token> fmt::Debug for StringEq<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("StringEq").field(&T::expectation()).finish()
    }
}

// Hand-written: derive would add a `T` bound, but `T` is a phantom marker
// that's never stored, so these hold unconditionally.
impl<T> Clone for StringEq<T> {
    fn clone(&self) -> Self {
        *self
    }
}

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

impl<T> Default for StringEq<T> {
    fn default() -> Self {
        StringEq(PhantomData)
    }
}

impl<T> PartialEq for StringEq<T> {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl<T> Eq for StringEq<T> {}

/// `Grammar` for a `StringEqCI!` chain. Case-insensitive, so the matched text
/// can differ from `T::expectation()`'s casing — it's captured once here
/// rather than per chain link.
pub struct StringEqCI<T>(String, PhantomData<T>);

impl<T: Token> Grammar for StringEqCI<T> {
    type First = T::First;

    #[inline]
    fn parse_at(input: &str, pos: usize, state: State) -> Option<(Self, usize)> {
        let end = T::scan_at(input, pos, state)?;
        Some((StringEqCI(input[pos..end].to_string(), PhantomData), end))
    }

    #[inline]
    fn scan_at(input: &str, pos: usize, state: State) -> Option<usize> {
        T::scan_at(input, pos, state)
    }

    fn print_to(&self, buf: &mut String) {
        buf.push_str(&self.0);
    }

    fn to_bnf() -> Expr {
        Expr::LiteralCI(T::expectation())
    }
}

impl<T> fmt::Debug for StringEqCI<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("StringEqCI").field(&self.0).finish()
    }
}

impl<T> Clone for StringEqCI<T> {
    fn clone(&self) -> Self {
        StringEqCI(self.0.clone(), PhantomData)
    }
}

impl<T: Token> Default for StringEqCI<T> {
    fn default() -> Self {
        StringEqCI(T::expectation(), PhantomData)
    }
}

impl<T> PartialEq for StringEqCI<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> Eq for StringEqCI<T> {}