scanner.rs 10.8 KB
Newer Older
P
Phodal Huang 已提交
1
use onig::{Regex};
P
Phodal Huang 已提交
2
use unicode_segmentation::UnicodeSegmentation;
P
Phodal Huang 已提交
3

P
Phodal Huang 已提交
4
#[derive(Debug, Clone, Serialize)]
P
Phodal Huang 已提交
5
pub struct IOnigCaptureIndex {
P
Phodal Huang 已提交
6 7 8
    pub start: usize,
    pub end: usize,
    pub length: usize,
P
Phodal Huang 已提交
9 10
}

P
Phodal Huang 已提交
11
#[derive(Debug, Clone, Serialize)]
P
Phodal Huang 已提交
12
pub struct IOnigMatch {
P
Phodal Huang 已提交
13
    pub index: usize,
P
Phodal Huang 已提交
14 15 16
    pub capture_indices: Vec<IOnigCaptureIndex>,
}

P
Phodal Huang 已提交
17
#[derive(Debug, Clone, Serialize)]
P
Phodal Huang 已提交
18
pub struct Scanner {
P
Phodal Huang 已提交
19
    pub index: usize,
P
Phodal Huang 已提交
20 21 22 23 24
    pub patterns: Vec<String>,
}

impl Scanner {
    pub fn new(patterns: Vec<String>) -> Self {
P
Phodal Huang 已提交
25
        Scanner { index: 0, patterns }
P
Phodal Huang 已提交
26 27
    }

P
Phodal Huang 已提交
28 29 30 31
    pub fn dispose(&mut self) {
        self.index = 0
    }

P
Phodal Huang 已提交
32 33 34 35 36
    pub fn find_next_match_sync(
        &mut self,
        origin_str: String,
        start_position: i32,
    ) -> Option<IOnigMatch> {
P
Phodal Huang 已提交
37
        if self.index >= self.patterns.clone().len() {
P
Phodal Huang 已提交
38
            self.index = 0;
39 40 41
            return None;
        }

P
Phodal Huang 已提交
42 43 44 45 46 47 48 49 50
        let mut all_results: Vec<IOnigMatch> = vec![];
        for (index, pattern) in self.patterns.iter().enumerate() {
            let mut after_pos_str = String::from("");
            let mut start_pos = start_position;
            let string_vec = origin_str.graphemes(true).collect::<Vec<&str>>();

            if start_pos >= string_vec.len() as i32 {
                return None;
            }
P
Phodal Huang 已提交
51

P
Phodal Huang 已提交
52 53 54
            if start_pos < 0 {
                start_pos = 0
            }
P
Phodal Huang 已提交
55

P
Phodal Huang 已提交
56 57
            let before_vec = string_vec[..start_pos as usize].to_owned();
            let after_vec = string_vec[start_pos as usize..].to_owned();
P
Phodal Huang 已提交
58

P
Phodal Huang 已提交
59 60 61
            for x in after_vec {
                after_pos_str = after_pos_str + x
            }
P
Phodal Huang 已提交
62

P
Phodal Huang 已提交
63 64 65 66
            let _regex = Regex::new(pattern.as_str());
            if let Err(_err) = _regex {
                return None;
            }
67

P
Phodal Huang 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
            let regex = _regex.unwrap();
            let mut capture_indices = vec![];
            let _captures = regex.captures(after_pos_str.as_str());

            if let Some(captures) = _captures {
                for (_, pos) in captures.iter_pos().enumerate() {
                    if let Some((start, end)) = pos {
                        let length = end - start;
                        let x1 = after_pos_str.split_at(end).0;
                        let utf8_end =
                            before_vec.len() + x1.graphemes(true).collect::<Vec<&str>>().len();
                        let utf8_start = utf8_end - length;

                        let capture = IOnigCaptureIndex {
                            start: utf8_start,
                            end: utf8_end,
                            length,
                        };

                        capture_indices.push(capture);
                    }
P
Phodal Huang 已提交
89
                }
P
Phodal Huang 已提交
90 91 92 93 94

                all_results.push(IOnigMatch {
                    index,
                    capture_indices
                })
P
Phodal Huang 已提交
95
            }
P
Phodal Huang 已提交
96
        }
P
Phodal Huang 已提交
97

P
Phodal Huang 已提交
98 99 100

        if all_results.len() > 0 {
            Some(all_results[0].clone())
P
Phodal Huang 已提交
101
        } else {
P
Phodal Huang 已提交
102
            None
P
Phodal Huang 已提交
103
        }
P
Phodal Huang 已提交
104 105 106
    }
}

P
Phodal Huang 已提交
107
pub fn str_vec_to_string<I, T>(iter: I) -> Vec<String>
P
Phodal Huang 已提交
108 109 110
where
    I: IntoIterator<Item = T>,
    T: Into<String>,
P
Phodal Huang 已提交
111 112 113 114
{
    iter.into_iter().map(Into::into).collect()
}

P
Phodal Huang 已提交
115 116
#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
117
    use crate::scanner::scanner::{str_vec_to_string, Scanner, IOnigMatch};
P
Phodal Huang 已提交
118 119 120 121

    #[test]
    fn should_handle_simple_regex() {
        let regex = vec![String::from("ell"), String::from("wo")];
P
Phodal Huang 已提交
122 123
        let mut scanner = Scanner::new(regex);
        let s = String::from("Hello world!");
P
Phodal Huang 已提交
124
        let result = scanner.find_next_match_sync(s.clone(), 0).unwrap();
P
Phodal Huang 已提交
125 126 127 128
        assert_eq!(result.index, 0);
        assert_eq!(result.capture_indices[0].start, 1);
        assert_eq!(result.capture_indices[0].end, 4);

P
Phodal Huang 已提交
129
        let second_result = scanner.find_next_match_sync(s, 2).unwrap();
P
Phodal Huang 已提交
130 131 132
        assert_eq!(second_result.index, 1);
        assert_eq!(second_result.capture_indices[0].start, 6);
        assert_eq!(second_result.capture_indices[0].end, 8);
P
Phodal Huang 已提交
133
    }
P
Phodal Huang 已提交
134 135 136 137 138 139

    #[test]
    fn should_handle_simple2() {
        let regex = vec![String::from("a"), String::from("b"), String::from("c")];
        let mut scanner = Scanner::new(regex);

P
Phodal Huang 已提交
140 141 142 143 144
        if let None = scanner.find_next_match_sync(String::from("x"), 0) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
145

P
Phodal Huang 已提交
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
        let result = scanner
            .find_next_match_sync(String::from("xxaxxbxxc"), 0)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
                "{\"index\":0,\"capture_indices\":[{\"start\":2,\"end\":3,\"length\":1}]}"
            )
        );

        let result2 = scanner
            .find_next_match_sync(String::from("xxaxxbxxc"), 4)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
                "{\"index\":1,\"capture_indices\":[{\"start\":5,\"end\":6,\"length\":1}]}"
            )
        );

        let result3 = scanner
            .find_next_match_sync(String::from("xxaxxbxxc"), 7)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result3).unwrap(),
            String::from(
                "{\"index\":2,\"capture_indices\":[{\"start\":8,\"end\":9,\"length\":1}]}"
            )
        );
P
Phodal Huang 已提交
175 176 177 178 179 180

        if let None = scanner.find_next_match_sync(String::from("xxaxxbxxc"), 9) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
181
    }
P
Phodal Huang 已提交
182 183 184 185 186 187

    #[test]
    fn should_handle_unicode1() {
        let regex = vec![String::from("1"), String::from("2")];
        let mut scanner = Scanner::new(regex);

P
Phodal Huang 已提交
188 189 190 191 192 193
        let result = scanner
            .find_next_match_sync(String::from("ab…cde21"), 5)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
194
                "{\"index\":0,\"capture_indices\":[{\"start\":7,\"end\":8,\"length\":1}]}"
P
Phodal Huang 已提交
195 196
            )
        );
P
Phodal Huang 已提交
197 198 199 200 201
    }

    #[test]
    fn should_handle_unicode2() {
        let mut scanner2 = Scanner::new(vec![String::from("\"")]);
P
Phodal Huang 已提交
202 203 204 205 206 207
        let result2 = scanner2
            .find_next_match_sync(String::from("{\"\": 1}"), 1)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
208
                "{\"index\":0,\"capture_indices\":[{\"start\":1,\"end\":2,\"length\":1}]}"
P
Phodal Huang 已提交
209 210
            )
        );
P
Phodal Huang 已提交
211
    }
P
Phodal Huang 已提交
212

213 214 215 216
    #[test]
    fn should_handle_unicode3() {
        let regex = vec![String::from("Y"), String::from("X")];
        let mut scanner = Scanner::new(regex);
P
Phodal Huang 已提交
217 218 219 220 221 222
        let result = scanner
            .find_next_match_sync(String::from("a💻bYX"), 0)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
223
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
224 225 226 227 228 229 230 231 232
            )
        );

        let result1 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 1)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result1).unwrap(),
            String::from(
233
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
234 235 236 237 238 239 240 241 242
            )
        );

        let result2 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 2)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
243
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
244 245 246 247 248 249 250 251 252
            )
        );

        let result3 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 3)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result3).unwrap(),
            String::from(
253
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
254 255 256 257 258 259 260 261 262
            )
        );

        let result4 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 4)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result4).unwrap(),
            String::from(
263
                "{\"index\":1,\"capture_indices\":[{\"start\":4,\"end\":5,\"length\":1}]}"
P
Phodal Huang 已提交
264 265
            )
        );
266 267
    }

268 269 270
    #[test]
    fn should_out_of_bounds() {
        let mut scanner = Scanner::new(vec![String::from("X")]);
P
Phodal Huang 已提交
271 272 273 274 275 276
        let result = scanner
            .find_next_match_sync(String::from("X💻X"), -10000)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
277
                "{\"index\":0,\"capture_indices\":[{\"start\":0,\"end\":1,\"length\":1}]}"
P
Phodal Huang 已提交
278 279
            )
        );
280

281 282 283 284 285 286 287 288
        let result2 = scanner.find_next_match_sync(String::from("X💻X"), 10000);
        assert_eq!(format!("{:?}", result2), "None");
    }

    #[test]
    fn should_handle_regex_g() {
        let mut scanner = Scanner::new(vec![String::from("\\G-and")]);
        let result = scanner.find_next_match_sync(String::from("first-and-second"), 0);
289
        assert_eq!(format!("{:?}", result), "None");
290

P
Phodal Huang 已提交
291 292 293 294 295 296 297 298 299
        let result2 = scanner
            .find_next_match_sync(String::from("first-and-second"), 5)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
                "{\"index\":0,\"capture_indices\":[{\"start\":5,\"end\":9,\"length\":4}]}"
            )
        );
300
    }
P
Phodal Huang 已提交
301 302 303 304

    #[test]
    fn should_match_makefile_scan_regex() {
        let origin = vec![
305
            "(^[ \\t]+)?(?=#)",
P
Phodal Huang 已提交
306 307 308 309 310 311 312 313 314
            "(^[ ]*|\\G\\s*)([^\\s]+)\\s*(=|\\?=|:=|\\+=)",
            "^(?!\\t)([^:]*)(:)(?!\\=)",
            "^[ ]*([s\\-]?include)\\b",
            "^[ ]*(vpath)\\b",
            "^(?:(override)\\s*)?(define)\\s*([^\\s]+)\\s*(=|\\?=|:=|\\+=)?(?=\\s)",
            "^[ ]*(export)\\b",
            "^[ ]*(override|private)\\b",
            "^[ ]*(unexport|undefine)\\b",
            "^(ifdef|ifndef)\\s*([^\\s]+)(?=\\s)",
P
Phodal Huang 已提交
315
            "^(ifeq|ifneq)(?=\\s)]",
P
Phodal Huang 已提交
316 317 318 319 320
        ];
        let rules = vec![2, 7, 28, 45, 48, 51, 61, 64, 66, 69, 77];
        let debug_regex = str_vec_to_string(origin);
        let mut scanner = Scanner::new(debug_regex);
        let result = scanner.find_next_match_sync(String::from("%.o: %.c $(DEPS)"), 0);
321
        assert_eq!(3, result.unwrap().capture_indices.len());
P
Phodal Huang 已提交
322
    }
P
Phodal Huang 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336

    #[test]
    fn should_match_makefile_special_char() {
        let origin = vec![
            "(?=\\s|$)",
            "(\\$?\\$)[@%<?^+*]",
            "\\$?\\$\\(",
            "%",
        ];
        let rules = vec![-1, 12, 14, 33];
        let debug_regex = str_vec_to_string(origin);
        let mut scanner = Scanner::new(debug_regex);
        let result = scanner.find_next_match_sync(String::from("%.o"), 0);
        let onig_match = result.unwrap();
P
Phodal Huang 已提交
337 338 339 340
        // println!("{:?}", onig_match.clone());
        // assert_eq!(3, onig_match.index);
        // println!(0, onig_match.clone().capture_indices[0].start);
        // println!(1, onig_match.clone().capture_indices[0].end);
P
Phodal Huang 已提交
341
    }
P
Phodal Huang 已提交
342
}