kalosm_sample/structured_parser/
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
use std::{collections::HashMap, sync::RwLock};

use crate::{CreateParserState, Parser};
use regex_automata::{
    dfa::{dense, Automaton},
    util::primitives::StateID,
};

/// A parser that uses a regex pattern to parse input.
pub struct RegexParser {
    dfa: dense::DFA<Vec<u32>>,
    config: regex_automata::util::start::Config,
    // A cache for the required next bytes for each state
    jump_table: RwLock<HashMap<StateID, String>>,
}

impl RegexParser {
    /// Create a new `RegexParser` from a regex pattern.
    #[allow(clippy::result_large_err)]
    pub fn new(regex: &str) -> std::result::Result<Self, regex_automata::dfa::dense::BuildError> {
        let dfa = dense::DFA::new(regex)?;

        let config =
            regex_automata::util::start::Config::new().anchored(regex_automata::Anchored::Yes);

        Ok(Self {
            dfa,
            config,
            jump_table: Default::default(),
        })
    }
}

impl CreateParserState for RegexParser {
    fn create_parser_state(&self) -> <Self as Parser>::PartialState {
        let start_state = self.dfa.start_state(&self.config).unwrap();
        RegexParserState {
            state: start_state,
            value: Vec::new(),
        }
    }
}

impl Parser for RegexParser {
    type Output = String;
    type PartialState = RegexParserState;

    fn parse<'a>(
        &self,
        state: &Self::PartialState,
        input: &'a [u8],
    ) -> crate::ParseResult<crate::ParseStatus<'a, Self::PartialState, Self::Output>> {
        let mut state = state.clone();
        let mut iter = input.iter();
        while let Some(&b) = iter.next() {
            state.state = self.dfa.next_state(state.state, b);
            state.value.push(b);
            // If this is a match state, accept it only if it matches the whole regex
            let finish_state = self.dfa.next_eoi_state(state.state);
            if self.dfa.is_match_state(finish_state) {
                return Ok(crate::ParseStatus::Finished {
                    result: String::from_utf8_lossy(&state.value).to_string(),
                    remaining: iter.as_slice(),
                });
            } else if self.dfa.is_dead_state(state.state) || self.dfa.is_quit_state(state.state) {
                crate::bail!(regex_automata::MatchError::quit(b, 0));
            }
        }

        let mut required_next = String::new();
        let mut required_next_state = state.state;
        let jump_table_read = self.jump_table.read().unwrap();

        if let Some(string) = jump_table_read.get(&required_next_state) {
            required_next.push_str(string);
        } else {
            'required_next: loop {
                let mut one_valid_byte = None;

                if let Some(string) = jump_table_read.get(&required_next_state) {
                    required_next.push_str(string);
                    break;
                }

                for byte in 0..=255 {
                    let next_state = self.dfa.next_state(required_next_state, byte);
                    if self.dfa.is_dead_state(next_state) || self.dfa.is_quit_state(next_state) {
                        continue;
                    }
                    if one_valid_byte.is_some() {
                        break 'required_next;
                    }
                    one_valid_byte = Some((byte, next_state));
                }

                if let Some((byte, new_state)) = one_valid_byte {
                    required_next.push(byte.into());
                    required_next_state = new_state;
                } else {
                    break;
                }
            }

            if !required_next.is_empty() {
                drop(jump_table_read);
                self.jump_table
                    .write()
                    .unwrap()
                    .insert(state.state, required_next.clone());
            }
        }

        Ok(crate::ParseStatus::Incomplete {
            new_state: state,
            required_next: required_next.into(),
        })
    }
}

/// The state of a regex parser.
#[derive(Default, Debug, PartialEq, Eq, Clone)]
pub struct RegexParserState {
    state: StateID,
    value: Vec<u8>,
}

#[test]
fn parse_regex() {
    use crate::ParseStatus;

    let regex = r#"\"\w+\""#;
    let parser = RegexParser::new(regex).unwrap();
    let state = parser.create_parser_state();
    let result = parser.parse(&state, b"\"hello\"world").unwrap();
    assert_eq!(
        result,
        ParseStatus::Finished {
            result: "\"hello\"".to_string(),
            remaining: b"world"
        }
    );

    let result = parser.parse(&state, b"\"hello world\"");
    assert!(result.is_err(),);

    let result = parser.parse(&state, b"\"hel").unwrap();
    match result {
        ParseStatus::Incomplete {
            new_state,
            required_next,
        } => {
            assert_eq!(new_state.value, b"\"hel");
            assert!(required_next.is_empty());
        }
        _ => panic!("unexpected result to be incomplete: {result:?}"),
    }
}

#[test]
fn required_next_regex() {
    use crate::ParseStatus;

    let regex = r#"\{ name: "\w+", description: "[\w ]+" \}"#;
    let parser = RegexParser::new(regex).unwrap();
    let start_state = parser
        .dfa
        .start_state(
            &regex_automata::util::start::Config::new().anchored(regex_automata::Anchored::Yes),
        )
        .unwrap();
    let state = parser.create_parser_state();
    let result = parser.parse(&state, b"").unwrap();
    assert_eq!(
        result,
        ParseStatus::Incomplete {
            new_state: RegexParserState {
                state: start_state,
                value: b"".to_vec(),
            },
            required_next: "{ name: \"".into(),
        }
    );

    let result = parser.parse(&state, b"{ name: \"hello\"").unwrap();

    match result {
        ParseStatus::Incomplete {
            new_state,
            required_next,
        } => {
            assert_eq!(new_state.value, b"{ name: \"hello\"");
            assert_eq!(required_next, ", description: \"");
        }
        _ => panic!("unexpected result to be incomplete: {result:?}"),
    }
}