syntax_parser_generator/lex/
regex.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
use crate::automata::nfa::{Nfa, NfaState};
use crate::handles::Handle;
use crate::handles::specials::AutomaticallyHandled;

/// A regular-expression pattern over raw bytes.
///
/// In practice, you won't need to create instances of this type directly. Check out the [Regex]
/// API and the high-level factory methods it offers.
#[derive(Clone)]
pub enum Regex {
    /// Only matches a single hardcoded byte.
    SingleCharacter {
        /// The matching byte.
        value: u8,
    },

    /// Matches each one of the specified patterns.
    Union {
        /// The possible matching patterns.
        options: Vec<Regex>,
    },

    /// Matches a concatenation of the specified patterns.
    Concat {
        /// The concatenated patterns.
        parts: Vec<Regex>,
    },

    /// Matches a concatenation of zero or more repetitions of the specified pattern.
    Star {
        /// The repeated pattern.
        repeated_pattern: Box<Regex>,
    },
}

impl Regex {
    /// Creates a pattern that only matches the specified character.
    ///
    /// # Panics
    ///
    /// If the character is not ASCII (cannot be represented by a single byte).
    pub fn single_char(value: char) -> Regex {
        Regex::SingleCharacter {
            value: value.try_into().unwrap_or_else(|_| panic!(
                "Cannot create a single-character regex from {:?}, as it's not 1-byte long", value
            ))
        }
    }

    /// Creates a pattern that matches each of the specified patterns.
    pub fn union(options: Vec<Regex>) -> Regex {
        Regex::Union { options }
    }

    /// Creates a pattern that matches a concatenation of the specified patterns.
    pub fn concat(parts: Vec<Regex>) -> Regex {
        Regex::Concat { parts }
    }

    /// Creates a pattern that matches zero or more repetitions of the specified pattern.
    pub fn star_from(repeated_pattern: Regex) -> Regex {
        Regex::Star { repeated_pattern: Box::new(repeated_pattern) }
    }

    /// Creates a pattern that matches one or more repetitions of the specified pattern.
    pub fn plus_from(repeated_pattern: Regex) -> Regex {
        let star_pattern = Regex::star_from(repeated_pattern.clone());
        Regex::concat(vec![
            repeated_pattern,
            star_pattern,
        ])
    }

    /// Creates a pattern that matches a single white-space character.
    pub fn white_space() -> Regex {
        let white_space_characters = vec![' ', '\t', '\n', '\r', '\x0B', '\x0C'];
        Regex::union(
            white_space_characters
                .into_iter()
                .map(Regex::single_char)
                .collect()
        )
    }

    /// Creates a pattern that matches a hard-coded sequence of characters.
    pub fn constant_string(string: &str) -> Regex {
        Regex::concat(
            string
                .chars()
                .map(Regex::single_char)
                .collect()
        )
    }

    /// Creates a pattern that matches any single character between the specified couple of
    /// characters (inclusive).
    pub fn character_range(start: char, end: char) -> Regex {
        Regex::union(
            (start..=end)
                .map(Regex::single_char)
                .collect()
        )
    }

    /// Creates a pattern that matches the specified pattern, and an empty sequence of bytes.
    pub fn optional(option: Regex) -> Regex {
        Regex::union(vec![
            option,
            Regex::epsilon(),
        ])
    }

    /// Creates a pattern that only matches an empty sequence of characters.
    pub fn epsilon() -> Regex {
        Regex::concat(vec![])
    }

    pub(crate) fn build_into_nfa<Label>(
        &self, nfa: &mut Nfa<u8, Label>,
    ) -> (Handle<NfaState<u8, Label>>, Handle<NfaState<u8, Label>>)
    where
    {
        match self {
            Regex::SingleCharacter { value } => {
                let start = nfa.new_state();
                let end = nfa.new_state();
                nfa.link(start, end, Some(value.handle()));
                (start, end)
            }
            Regex::Union { options } => {
                let start = nfa.new_state();
                let end = nfa.new_state();
                for option in options {
                    let (option_start, option_end) =
                        option.build_into_nfa(nfa);
                    nfa.link(start, option_start, None);
                    nfa.link(option_end, end, None);
                }
                (start, end)
            }
            Regex::Concat { parts } => {
                let start = nfa.new_state();
                let end = nfa.new_state();
                let mut curr = start;
                for part in parts {
                    let (part_start, part_end) =
                        part.build_into_nfa(nfa);
                    nfa.link(curr, part_start, None);
                    curr = part_end;
                }
                nfa.link(curr, end, None);
                (start, end)
            }
            Regex::Star { repeated_pattern } => {
                let start = nfa.new_state();
                let end = nfa.new_state();
                let (repeated_pattern_start, repeated_pattern_end) =
                    repeated_pattern.build_into_nfa(nfa);

                nfa.link(start, repeated_pattern_start, None);
                nfa.link(start, end, None);
                nfa.link(repeated_pattern_end, end, None);
                nfa.link(repeated_pattern_end, repeated_pattern_start, None);

                (start, end)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::automata::dfa::Dfa;

    use super::*;

    fn create_dfa_for_regex(pattern: Regex) -> Dfa<u8, ()> {
        let mut nfa = Nfa::new();
        let (start, end) = pattern.build_into_nfa(&mut nfa);
        nfa.label(end, Some(()));
        nfa.set_initial_state(start);

        let dfa = nfa
            .compile_to_dfa(|labels| {
                if labels.is_empty() {
                    None
                } else {
                    Some(())
                }
            })
            .minimize();

        return dfa;
    }

    fn is_string_in(dfa: &Dfa<u8, ()>, data: &str) -> bool {
        match dfa.scan(String::from(data).into_bytes().into_iter().map(|x| x.handle())) {
            None => false,
            Some(end_state) => {
                !dfa.get_label(end_state).is_none()
            }
        }
    }
    #[test]
    fn test_single_char() {
        let pattern = Regex::single_char('a');
        let dfa = create_dfa_for_regex(pattern);

        assert_eq!(is_string_in(&dfa, "a"), true);
        assert_eq!(is_string_in(&dfa, ""), false);
        assert_eq!(is_string_in(&dfa, "aa"), false);
    }

    #[test]
    fn test_union() {
        let pattern = Regex::union(vec![
            Regex::single_char('a'),
            Regex::single_char('b'),
            Regex::single_char('c'),
        ]);
        let dfa = create_dfa_for_regex(pattern);

        assert_eq!(is_string_in(&dfa, "a"), true);
        assert_eq!(is_string_in(&dfa, "b"), true);
        assert_eq!(is_string_in(&dfa, "c"), true);
        assert_eq!(is_string_in(&dfa, ""), false);
        assert_eq!(is_string_in(&dfa, "aa"), false);
        assert_eq!(is_string_in(&dfa, "d"), false);
    }

    #[test]
    fn test_concat() {
        let pattern = Regex::concat(vec![
            Regex::single_char('a'),
            Regex::single_char('b'),
            Regex::single_char('c'),
        ]);
        let dfa = create_dfa_for_regex(pattern);


        assert_eq!(is_string_in(&dfa, "abc"), true);
        assert_eq!(is_string_in(&dfa, ""), false);
        assert_eq!(is_string_in(&dfa, "a"), false);
        assert_eq!(is_string_in(&dfa, "bc"), false);
    }

    //noinspection ALL
    #[test]
    fn test_star() {
        let pattern = Regex::star_from(
            Regex::single_char('a'),
        );
        let dfa = create_dfa_for_regex(pattern);

        assert_eq!(is_string_in(&dfa, ""), true);
        assert_eq!(is_string_in(&dfa, "a"), true);
        assert_eq!(is_string_in(&dfa, "aa"), true);
        assert_eq!(is_string_in(&dfa, "aaaaaaa"), true);
        assert_eq!(is_string_in(&dfa, "b"), false);
        assert_eq!(is_string_in(&dfa, "ab"), false);
    }

    #[test]
    fn test_plus() {
        let pattern = Regex::plus_from(
            Regex::single_char('a'),
        );
        let dfa = create_dfa_for_regex(pattern);

        assert_eq!(is_string_in(&dfa, ""), false);
        assert_eq!(is_string_in(&dfa, "a"), true);
        assert_eq!(is_string_in(&dfa, "aa"), true);
        assert_eq!(is_string_in(&dfa, "aaaaaaa"), true);
        assert_eq!(is_string_in(&dfa, "b"), false);
        assert_eq!(is_string_in(&dfa, "ab"), false);
    }

    #[test]
    fn test_complex() {
        let pattern = Regex::concat(vec![
            Regex::union(vec![
                Regex::character_range('a', 'z'),
                Regex::character_range('A', 'Z'),
                Regex::single_char('_'),
            ]),
            Regex::star_from(
                Regex::union(vec![
                    Regex::character_range('a', 'z'),
                    Regex::character_range('A', 'Z'),
                    Regex::character_range('0', '9'),
                    Regex::single_char('_'),
                ]),
            ),
        ]);
        let dfa = create_dfa_for_regex(pattern);

        assert_eq!(is_string_in(&dfa, "MyThing"), true);
        assert_eq!(is_string_in(&dfa, "our_thing_12"), true);
        assert_eq!(is_string_in(&dfa, "i"), true);
        assert_eq!(is_string_in(&dfa, "a1jh2b45"), true);
        assert_eq!(is_string_in(&dfa, ""), false);
        assert_eq!(is_string_in(&dfa, "mine()"), false);
        assert_eq!(is_string_in(&dfa, "12"), false);
        assert_eq!(is_string_in(&dfa, "1ours"), false);
    }
}