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
//! Implements character classes.
use crate::base::{Element, Rec};
use std::ops::{Add, BitOr, Not};

impl Add<Ch<'_>> for &str {
    type Output = Rec;

    #[inline]
    /// Adds `&str` and [`Ch`].
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!("hello" + Ch::digit(), String::from(r"hello\d").into_rec());
    /// ```
    fn add(self, rhs: Ch<'_>) -> Rec {
        self.into_rec() + rhs
    }
}

/// Represents a character that can match one or more characters.
#[derive(Debug)]
pub struct Ch<'a> {
    /// The [`Char`] representing the character.
    c: Char<'a>,
    /// If `c` needs to be negated.
    is_negated: bool,
}

impl Ch<'_> {
    /// Creates a `Ch` with the given [`Char`].
    const fn with_char(c: Char<'_>) -> Ch<'_> {
        Ch {
            c,
            is_negated: false,
        }
    }

    fn negate_sign(&self) -> String {
        if self.is_negated {
            String::from("^")
        } else {
            String::new()
        }
    }

    /// Creates a `Ch` that matches any character other than a newline.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::any().into_rec(), String::from(".").into_rec());
    /// ```
    pub const fn any() -> Ch<'static> {
        Ch::with_char(Char::Any)
    }

    /// Creates a `Ch` that matches any alphabetic character.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::alpha().into_rec(), String::from("[[:alpha:]]").into_rec());
    /// ```
    pub const fn alpha() -> Ch<'static> {
        Ch::with_char(Char::Class(CharClass::Alpha))
    }

    /// Creates a `Ch` that matches any alphabetic or numerical digit character.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::alphanum().into_rec(), String::from("[[:alnum:]]").into_rec());
    pub const fn alphanum() -> Ch<'static> {
        Ch::with_char(Char::Class(CharClass::AlphaNum))
    }

    /// Creates a `Ch` that matches any numerical digit character.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::digit().into_rec(), String::from(r"\d").into_rec());
    /// ```
    pub const fn digit() -> Ch<'static> {
        Ch::with_char(Char::Digit)
    }

    /// Creates a `Ch` that matches any whitespace character.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::whitespace().into_rec(), String::from(r"\s").into_rec());
    /// ```
    pub const fn whitespace() -> Ch<'static> {
        Ch::with_char(Char::Whitespace)
    }

    /// Creates a `Ch` that matches with the start of the text.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::start().into_rec(), String::from("^").into_rec());
    /// ```
    pub const fn start() -> Ch<'static> {
        Ch::with_char(Char::Start)
    }

    /// Creates a `Ch` that matches with the end of the text.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::end().into_rec(), String::from("$").into_rec());
    /// ```
    pub const fn end() -> Ch<'static> {
        Ch::with_char(Char::End)
    }

    /// Creates a `Ch` that matches with the sign character of a number.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::sign().into_rec(), String::from(r"[+\-]").into_rec());
    /// ```
    pub fn sign() -> Ch<'static> {
        Ch::union(r"+-")
    }

    /// Creates a `Ch` that matches with any of the given characters.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::union("abc").into_rec(), String::from("[abc]").into_rec());
    /// ```
    ///
    /// ## `-` is not interpreted as range
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::union("a-c").into_rec(), String::from(r"[a\-c]").into_rec());
    /// ```
    pub fn union(chars: &str) -> Ch<'_> {
        Ch::with_char(Char::Union(chars))
    }

    /// Creates a `Ch` that matches with any character between or including the given characters.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::range('a', 'c').into_rec(), String::from(r"[a-c]").into_rec());
    /// ```
    pub fn range(first: char, last: char) -> Ch<'static> {
        Ch::with_char(Char::Range(first, last))
    }

    /// Creates a `Ch` that matches with any digit that is not `0`.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::digitnz().into_rec(), String::from(r"[1-9]").into_rec());
    /// ```
    pub fn digitnz() -> Ch<'static> {
        Ch::with_char(Char::Range('1', '9'))
    }

    /// Creates a `Ch` that matches with any hexidecimal digit.
    ///
    /// # Examples
    /// ```
    /// use rec::{Ch, Element};
    ///
    /// assert_eq!(Ch::hexdigit().into_rec(), String::from("[[:xdigit:]]").into_rec());
    /// ```
    pub fn hexdigit() -> Ch<'static> {
        Ch::with_char(Char::Class(CharClass::HexDigit))
    }
}

impl<Rhs: Element> Add<Rhs> for Ch<'_> {
    type Output = Rec;

    #[inline]
    fn add(self, rhs: Rhs) -> Rec {
        self.into_rec() + rhs
    }
}

/// ```
/// use rec::{Ch, Element};
///
/// assert_eq!(Ch::union("ab") | Ch::union("c"), String::from("[abc]").into_rec());
/// ```
///
/// ```
/// use rec::{Ch, Element};
///
/// assert_eq!(Ch::alpha() | Ch::whitespace(), String::from(r"[[:alpha:]\s]").into_rec());
/// ```
///
/// ```
/// use rec::{Ch, Element};
///
/// assert_eq!(Ch::alpha() | "0", String::from("[[:alpha:]0]").into_rec());
/// ```
///
/// Make sure alternation with multiple characters is not combined into 1 union.
/// ```
/// use rec::{Ch, Element};
///
/// assert_eq!(Ch::alpha() | "12", String::from("(?:[[:alpha:]]|12)").into_rec());
impl<Rhs: Element> BitOr<Rhs> for Ch<'_> {
    type Output = Rec;

    #[inline]
    fn bitor(self, rhs: Rhs) -> Rec {
        if let Some(l_value) = self.unionable_value() {
            if let Some(r_value) = rhs.unionable_value() {
                return format!("[{}{}]", l_value, r_value).into_rec();
            }
        }

        self.into_rec() | rhs
    }
}

impl Element for Ch<'_> {
    fn into_rec(self) -> Rec {
        match self.c {
            Char::Any => String::from("."),
            Char::Digit => String::from(r"\d"),
            Char::Whitespace => String::from(r"\s"),
            Char::Start => String::from("^"),
            Char::End => String::from("$"),
            Char::Newline => String::from(r"\n"),
            Char::NotDigit => String::from(r"\D"),
            Char::NotWhitespace => String::from(r"\S"),
            Char::Union(chars) => format!("[{}{}]", self.negate_sign(), chars.replace("-", r"\-")),
            Char::Class(class) => format!("[[:{}{}:]]", self.negate_sign(), class.id()),
            Char::Range(first, last) => format!("[{}{}-{}]", self.negate_sign(), first, last),
        }
        .into_rec()
    }

    fn unionable_value(&self) -> Option<String> {
        match self.c {
            Char::Union(chars) => Some(String::from(chars)),
            Char::Class(class) => Some(format!("[:{}:]", class.id())),
            Char::Whitespace => Some(String::from(r"\s")),
            _ => None,
        }
    }
}

impl<'a> Not for Ch<'a> {
    type Output = Ch<'a>;

    fn not(self) -> Self::Output {
        let (c, is_negated) = match self.c {
            Char::Any => (Char::Newline, false),
            Char::Newline => (Char::Any, false),
            Char::Digit => (Char::NotDigit, false),
            Char::NotDigit => (Char::Digit, false),
            Char::Whitespace => (Char::NotWhitespace, false),
            Char::NotWhitespace => (Char::Whitespace, false),
            Char::End => (Char::Union("$"), true),
            Char::Start => (Char::Union("^"), true),
            Char::Union(_) | Char::Class(_) | Char::Range(_, _) => (self.c, !self.is_negated),
        };
        Ch { c, is_negated }
    }
}

/// Specifies one or more metacharacters to be matched against.
#[allow(variant_size_differences)] // Cannot be resolved.
#[derive(Debug)]
enum Char<'a> {
    /// Matches any character except newline.
    Any,
    /// Matches any digit.
    Digit,
    /// Matches any whitespace.
    Whitespace,
    /// Matches the start of the text.
    Start,
    /// Matches the end of the text.
    End,
    /// Any of the given characters.
    Union(&'a str),
    /// The new line character.
    Newline,
    /// Matches any character that is not a digit.
    NotDigit,
    /// Matches any character that is not whitespace.
    NotWhitespace,
    Class(CharClass),
    Range(char, char),
}

#[derive(Clone, Copy, Debug)]
enum CharClass {
    Alpha,
    AlphaNum,
    HexDigit,
}

impl CharClass {
    fn id(self) -> &'static str {
        match self {
            CharClass::Alpha => "alpha",
            CharClass::AlphaNum => "alnum",
            CharClass::HexDigit => "xdigit",
        }
    }
}