tyrx 0.1.2

Typed, ergonomic regular expression library
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
//! Composable regex builder types for pre-defined, frequently-used subexpressions

use std::marker::PhantomData;
use std::str::FromStr;
use std::fmt::{self, Formatter, Debug, Display};
use either::Either;
use regex::{Match, Captures};
use crate::{FromMatch, RegexPattern, ErasedLifetime, Error};

#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize, de::Deserializer};


// Empty matchers

macro_rules! empty_matcher {
    ($($name:ident => $pat:expr;)+) => {$(
        #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
        #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
        pub struct $name;

        impl RegexPattern for $name {
            fn fmt_pattern(f: &mut Formatter<'_>) -> fmt::Result {
                Display::fmt(&$pat, f)
            }
        }

        impl FromMatch<'_> for $name {
            fn from_match(_name: &'static str, m: Match<'_>, _captures: &Captures<'_>) -> Result<Self, Error> {
                assert!(m.is_empty());
                Ok($name)
            }
        }

        impl ErasedLifetime for $name {
            type Erased = Self;
        }
    )+}
}

empty_matcher! {
    LineStart => '^';
    LineEnd => '$';
    HaystackStart => r"\A";
    HaystackEnd => r"\z";
    WordStart => r"\<";
    WordEnd => r"\>";
    WordBoundary => r"\b";
}

/// writes a character as a regex literal, potentially escaping it if necessary
#[derive(Clone, Copy, Debug)]
struct EscapeRegex(char);

impl Display for EscapeRegex {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let &EscapeRegex(ch) = self;

        if regex_syntax::is_meta_character(ch) {
            // always escape regex control/metacharacters
            write!(f, r"\{ch}")
        } else if ch.is_whitespace() {
            write!(f, "{}", ch.escape_unicode()) // escape WS in case we are in verbose mode `(?x:...)`
        } else {
            write!(f, "{}", ch.escape_default()) // NB: escape_default() produces valid regex syntax!
        }
    }
}

// Single-character matchers

/// Captures any character.
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, Debug)]
pub struct Char<const CHAR: char>;

impl<const CHAR: char> Char<CHAR> {
    pub const fn value(&self) -> char {
        CHAR
    }
}

impl<const CHAR: char> TryFrom<char> for Char<CHAR> {
    type Error = Error;

    fn try_from(value: char) -> Result<Self, Self::Error> {
        if value == CHAR {
            Ok(Self)
        } else {
            let (expected, actual) = (u32::from(CHAR), u32::from(value));
            Err(Error::message(format_args!("expected U+{expected:04X}, got U+{actual:04X}")))
        }
    }
}

impl<const CHAR: char> From<Char<CHAR>> for char {
    fn from(c: Char<CHAR>) -> char {
        c.value()
    }
}

impl<const CHAR: char> RegexPattern for Char<CHAR> {
    fn fmt_pattern(f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(&EscapeRegex(CHAR), f)
    }
}

impl<const CHAR: char> FromMatch<'_> for Char<CHAR> {
    fn from_match(_name: &'static str, m: Match<'_>, _captures: &Captures<'_>) -> Result<Self, Error> {
        assert_eq!(m.as_str().parse::<char>().expect("single-character match"), CHAR);
        Ok(Char)
    }
}

impl<const CHAR: char> ErasedLifetime for Char<CHAR> {
    type Erased = Self;
}

/// Captures a range of characters.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct CharRange<const START: char, const END: char>(char);

impl<const START: char, const END: char> CharRange<START, END> {
    pub const fn value(&self) -> char {
        self.0
    }
}

impl<const START: char, const END: char> TryFrom<char> for CharRange<START, END> {
    type Error = Error;

    fn try_from(value: char) -> Result<Self, Self::Error> {
        if (START..=END).contains(&value) {
            Ok(CharRange(value))
        } else {
            let (start, end, value) = (START as u32, END as u32, value as u32);
            Err(Error::message(format_args!("expected range U+{start:04X}-{end:04X}, got U+{value:04X}")))
        }
    }
}

impl<const START: char, const END: char> From<CharRange<START, END>> for char {
    fn from(cr: CharRange<START, END>) -> char {
        cr.value()
    }
}

impl<const START: char, const END: char> FromStr for CharRange<START, END> {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<char>().map_err(Error::other).and_then(Self::try_from)
    }
}

impl<const START: char, const END: char> RegexPattern for CharRange<START, END> {
    fn fmt_pattern(f: &mut Formatter<'_>) -> fmt::Result {
        assert!(
            START <= END,
            "range should have start <= end; got: U+{:04X}-{:04X}`",
            START as u32, END as u32
        );

        write!(f, "[{start}-{end}]", start = EscapeRegex(START), end = EscapeRegex(END))
    }
}

impl<const START: char, const END: char> FromMatch<'_> for CharRange<START, END> {
    fn from_match(name: &'static str, m: Match<'_>, _captures: &Captures<'_>) -> Result<Self, Error> {
        m.as_str()
            .parse::<Self>()
            .map_err(|error| Error::group_from_str(name, m.range(), error))
    }
}

impl<const START: char, const END: char> ErasedLifetime for CharRange<START, END> {
    type Erased = Self;
}

#[cfg(feature = "serde")]
impl<'de, const START: char, const END: char> Deserialize<'de> for CharRange<START, END> {
    fn deserialize<D>(de: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>
    {
        char::deserialize(de).and_then(|ch| {
            Self::try_from(ch).map_err(serde::de::Error::custom)
        })
    }
}

/// Captures a character class.
#[derive(PartialEq, Eq, Hash, Debug)]
pub struct CharClass<C: ?Sized> {
    value: char,
    class: PhantomData<fn() -> C>,
}

impl<C: ?Sized> CharClass<C> {
    pub const fn value(&self) -> char {
        self.value
    }
}

impl<C: ?Sized> Clone for CharClass<C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<C: ?Sized> Copy for CharClass<C> {}

impl<C: ?Sized> From<CharClass<C>> for char {
    fn from(cc: CharClass<C>) -> char {
        cc.value()
    }
}

impl<C> RegexPattern for CharClass<C>
where
    C: ?Sized + CharClassMarker
{
    fn fmt_pattern(f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(C::PATTERN)
    }
}

impl<C> FromMatch<'_> for CharClass<C>
where
    C: ?Sized + CharClassMarker,
{
    fn from_match(name: &'static str, m: Match<'_>, _captures: &Captures<'_>) -> Result<Self, Error> {
        m.as_str()
            .parse::<char>()
            .map(|value| CharClass { value, class: PhantomData })
            .map_err(|error| Error::group_from_str(name, m.range(), error))
    }
}

impl<C> ErasedLifetime for CharClass<C>
where
    C: ?Sized + ErasedLifetime,
{
    type Erased = CharClass<C::Erased>;
}

/// Implemented by the various marker types which can be used for parameterizing
/// the [`CharClass`] builder.
pub trait CharClassMarker {
    /// The regular expression pattern of the character class denoted by `Self`.
    const PATTERN: &'static str;
}

macro_rules! impl_char_class_marker {
    ($($ty:ident => $pat:literal;)+) => {$(
        #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
        #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
        pub struct $ty;

        impl CharClassMarker for $ty {
            const PATTERN: &'static str = $pat;
        }

        impl ErasedLifetime for $ty {
            type Erased = Self;
        }
    )+}
}

impl_char_class_marker!{
    Whitespace => r"\s";
    NotWhitespace => r"\S";
    Digit => r"\d";
    NotDigit => r"\D";

    AsciiAlnum => "[[:alnum:]]";
    AsciiAlpha => "[[:alpha:]]";
    AsciiAscii => "[[:ascii:]]";
    AsciiBlank => "[[:blank:]]";
    AsciiCntrl => "[[:cntrl:]]";
    AsciiDigit => "[[:digit:]]";
    AsciiGraph => "[[:graph:]]";
    AsciiLower => "[[:lower:]]";
    AsciiPrint => "[[:print:]]";
    AsciiPunct => "[[:punct:]]";
    AsciiSpace => "[[:space:]]";
    AsciiUpper => "[[:upper:]]";
    AsciiWord => "[[:word:]]";
    AsciiXdigit => "[[:xdigit:]]";

    AsciiNotAlnum => "[[:^alnum:]]";
    AsciiNotAlpha => "[[:^alpha:]]";
    AsciiNotAscii => "[[:^ascii:]]";
    AsciiNotBlank => "[[:^blank:]]";
    AsciiNotCntrl => "[[:^cntrl:]]";
    AsciiNotDigit => "[[:^digit:]]";
    AsciiNotGraph => "[[:^graph:]]";
    AsciiNotLower => "[[:^lower:]]";
    AsciiNotPrint => "[[:^print:]]";
    AsciiNotPunct => "[[:^punct:]]";
    AsciiNotSpace => "[[:^space:]]";
    AsciiNotUpper => "[[:^upper:]]";
    AsciiNotWord => "[[:^word:]]";
    AsciiNotXdigit => "[[:^xdigit:]]";
}

// Composite expressions

/// Expect a pattern that is repeated at least `MIN`, at most `MAX` times.
/// Type parameter `P` provides the sub-pattern to be repeated.
/// Type parameter `T` denotes a type that can parse itself from the
/// _repeated_ match.
///
/// TODO(H2CO3): add a type parameter for deciding between eager and lazy mode
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Repeat<const MIN: usize, const MAX: usize, P: ?Sized, T: ?Sized> {
    marker: PhantomData<fn() -> P>,
    value: T,
}

impl<const MIN: usize, const MAX: usize, P: ?Sized, T: ?Sized> Repeat<MIN, MAX, P, T> {
    pub fn value(&self) -> &T {
        &self.value
    }
}

impl<const MIN: usize, const MAX: usize, P: ?Sized, T> Repeat<MIN, MAX, P, T> {
    pub fn into_inner(self) -> T {
        self.value
    }
}

impl<const MIN: usize, const MAX: usize, P, T> RegexPattern for Repeat<MIN, MAX, P, T>
where
    P: ?Sized + RegexPattern,
    T: ?Sized,
{
    fn fmt_pattern(f: &mut Formatter<'_>) -> fmt::Result {
        assert!(MIN <= MAX, "expected repeat MIN <= MAX; got MIN={MIN}, MAX={MAX}");

        let subexpr = P::pattern_display();

        // pretty-print some common special cases
        match (MIN, MAX) {
            (0, 1) => write!(f, "(?:{subexpr})?"),
            (0, usize::MAX) => write!(f, "(?:{subexpr})*"),
            (1, usize::MAX) => write!(f, "(?:{subexpr})+"),
            (_, usize::MAX) => write!(f, "(?:{subexpr}){{{MIN},}}"),
            (_, _) => write!(f, "(?:{subexpr}){{{MIN},{MAX}}}"),
        }
    }
}

impl<'h, const MIN: usize, const MAX: usize, P, T> FromMatch<'h> for Repeat<MIN, MAX, P, T>
where
    P: ?Sized,
    T: /* ?Sized + */ FromMatch<'h>,
{
    fn from_match(name: &'static str, m: Match<'h>, captures: &Captures<'h>) -> Result<Self, Error> {
        T::from_match(name, m, captures)
            .map(|value| Repeat { marker: PhantomData, value })
            .map_err(|error| Error::group_from_str(name, m.range(), error))
    }
}

impl<const MIN: usize, const MAX: usize, P, T> ErasedLifetime for Repeat<MIN, MAX, P, T>
where
    P: ?Sized + ErasedLifetime,
    T: ?Sized + ErasedLifetime,
{
    type Erased = Repeat<MIN, MAX, P::Erased, T::Erased>;
}

pub type AtLeast<const MIN: usize, P, T> = Repeat<MIN, {usize::MAX}, P, T>;
pub type AtMost<const MAX: usize, P, T> = Repeat<0, MAX, P, T>;
pub type Maybe<T> = Repeat<0, 1, T, Option<T>>; // functionally identical to `Option<T>`
pub type Any<P, T> = Repeat<0, {usize::MAX}, P, T>;
pub type Any1<P, T> = Repeat<1, {usize::MAX}, P, T>;

/// Binary (two-way), ordered alternation. This is an alias for [`either::Either`].
///
/// This type tries to match the left-hand side type (`L`) first, and only if
/// that fails, does it then proceed to matching the right-hand side type (`R`).
///
/// You can achieve multiple/N-way alternation by nesting/chaining several
/// `Alternation`s together, e.g.: `Alternation<Alternation<T, U>, V>` will
/// match `T|U|V`, in this order.
pub type Alternation<L, R> = Either<L, R>;

impl<L, R> RegexPattern for Alternation<L, R>
where
    L: RegexPattern,
    R: RegexPattern,
{
    fn fmt_pattern(f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "(?:{})|(?:{})", L::pattern_display(), R::pattern_display())
    }
}

impl<'h, L, R> FromMatch<'h> for Alternation<L, R>
where
    L: FromMatch<'h>,
    R: FromMatch<'h>,
{
    fn from_match(name: &'static str, m: Match<'h>, captures: &Captures<'h>) -> Result<Self, Error> {
        // just like regex matching, we first try the left-hand side,
        // and only if it fails do we proceed to parsing the right-hand side.
        L::from_match(name, m, captures)
            .map(Alternation::Left)
            .or_else(|left_err| {
                R::from_match(name, m, captures)
                    .map(Alternation::Right)
                    .map_err(|right_err| {
                        // preserve both sides' error to avoid misleading user when
                        // LHS legitimately fails (do not just show RHS error in that case)
                        Error::group_from_str(name, m.range(), Error::message(format_args!(
                            "both sides of alternation failed; left: {left_err}; right: {right_err}"
                        )))
                    })
            })
    }
}

impl<L, R> ErasedLifetime for Alternation<L, R>
where
    L: ErasedLifetime,
    L::Erased: Sized,
    R: ErasedLifetime,
    R::Erased: Sized,
{
    type Erased = Alternation<L::Erased, R::Erased>;
}

// TODO(H2CO3): set operations -- negation, intersection, symmetric difference

/// Matches a pattern but does not parse the underlying value.
///
/// This may be useful e.g. for avoiding allocations and/or parsing values and
/// sub-patterns that you need to match but do not care about in the final result.
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct Ignore<T: ?Sized>(PhantomData<fn() -> T>);

impl<T: ?Sized> Ignore<T> {
    pub const fn new() -> Self {
        Ignore(PhantomData)
    }
}

impl<T: ?Sized> Clone for Ignore<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized> Copy for Ignore<T> {}

impl<T: ?Sized> Default for Ignore<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: ?Sized> Debug for Ignore<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "Ignore<{}>(..)", std::any::type_name::<T>())
    }
}

impl<T> RegexPattern for Ignore<T>
where
    T: ?Sized + RegexPattern
{
    fn fmt_pattern(f: &mut Formatter<'_>) -> fmt::Result {
        T::fmt_pattern(f) // just forward to the underlying type
    }
}

impl<T> FromMatch<'_> for Ignore<T> {
    fn from_match(_name: &'static str, _m: Match<'_>, _captures: &Captures<'_>) -> Result<Self, Error> {
        Ok(Self::new())
    }
}

impl<T: ?Sized + ErasedLifetime> ErasedLifetime for Ignore<T> {
    type Erased = Ignore<T::Erased>;
}