scanner.rs 13.4 KB
Newer Older
1
use onig::{Regex, SearchOptions};
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
        let mut searchIndexes = vec![];
P
Phodal Huang 已提交
43 44 45 46 47 48 49 50 51
        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 已提交
52

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

P
Phodal Huang 已提交
57 58
            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 已提交
59

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

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

P
Phodal Huang 已提交
69 70 71
            let regex = _regex.unwrap();
            let mut capture_indices = vec![];
            let _captures = regex.captures(after_pos_str.as_str());
72 73
            let zz = regex.search_with_options(&*origin_str.clone(), start_pos as usize, origin_str.clone().len(), SearchOptions::SEARCH_OPTION_NOTBOL, None);
            if let Some(pos) = zz {
P
Phodal Huang 已提交
74 75
                // println!("pos: {:?}", pos);
                searchIndexes.push(pos);
76
            }
P
Phodal Huang 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

            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 已提交
95
                }
P
Phodal Huang 已提交
96 97 98

                all_results.push(IOnigMatch {
                    index,
P
Phodal Huang 已提交
99
                    capture_indices,
P
Phodal Huang 已提交
100
                })
P
Phodal Huang 已提交
101
            }
P
Phodal Huang 已提交
102
        }
P
Phodal Huang 已提交
103

P
Phodal Huang 已提交
104 105 106 107 108 109 110 111 112 113
        // let mut best_index = 0;
        // if searchIndexes.len() > 1 {
        //     for x in searchIndexes {
        //         if best_index > x {
        //             best_index = x;
        //         }
        //     }
        // }

        // println!("{:?} - best_index: {:?}", all_results.clone(), best_index);
P
Phodal Huang 已提交
114
        if all_results.len() > 0 {
P
Phodal Huang 已提交
115
            let mut best_match = all_results[0].clone();
116 117 118 119
            for i in 1..all_results.len().clone() {
                let current = all_results[i].capture_indices[0].clone();
                if current.start <= best_match.capture_indices[0].start {
                    best_match = all_results[i].clone();
P
Phodal Huang 已提交
120 121
                }
            }
122

P
Phodal Huang 已提交
123
            Some(best_match.clone())
P
Phodal Huang 已提交
124
        } else {
P
Phodal Huang 已提交
125
            None
P
Phodal Huang 已提交
126
        }
P
Phodal Huang 已提交
127 128 129
    }
}

P
Phodal Huang 已提交
130
pub fn str_vec_to_string<I, T>(iter: I) -> Vec<String>
131 132 133
    where
        I: IntoIterator<Item=T>,
        T: Into<String>,
P
Phodal Huang 已提交
134 135 136 137
{
    iter.into_iter().map(Into::into).collect()
}

P
Phodal Huang 已提交
138 139
#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
140
    use crate::scanner::scanner::{str_vec_to_string, Scanner};
P
Phodal Huang 已提交
141 142 143 144

    #[test]
    fn should_handle_simple_regex() {
        let regex = vec![String::from("ell"), String::from("wo")];
P
Phodal Huang 已提交
145 146
        let mut scanner = Scanner::new(regex);
        let s = String::from("Hello world!");
P
Phodal Huang 已提交
147
        let result = scanner.find_next_match_sync(s.clone(), 0).unwrap();
P
Phodal Huang 已提交
148 149 150 151
        assert_eq!(result.index, 0);
        assert_eq!(result.capture_indices[0].start, 1);
        assert_eq!(result.capture_indices[0].end, 4);

P
Phodal Huang 已提交
152
        let second_result = scanner.find_next_match_sync(s, 2).unwrap();
P
Phodal Huang 已提交
153 154 155
        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 已提交
156
    }
P
Phodal Huang 已提交
157 158 159 160 161 162

    #[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 已提交
163 164 165 166 167
        if let None = scanner.find_next_match_sync(String::from("x"), 0) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
168

P
Phodal Huang 已提交
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
        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 已提交
198 199 200 201 202 203

        if let None = scanner.find_next_match_sync(String::from("xxaxxbxxc"), 9) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
204
    }
P
Phodal Huang 已提交
205 206 207 208 209 210

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

P
Phodal Huang 已提交
211 212 213 214 215 216
        let result = scanner
            .find_next_match_sync(String::from("ab…cde21"), 5)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
P
Phodal Huang 已提交
217
                "{\"index\":1,\"capture_indices\":[{\"start\":6,\"end\":7,\"length\":1}]}"
P
Phodal Huang 已提交
218 219
            )
        );
P
Phodal Huang 已提交
220 221 222 223 224
    }

    #[test]
    fn should_handle_unicode2() {
        let mut scanner2 = Scanner::new(vec![String::from("\"")]);
P
Phodal Huang 已提交
225 226 227 228 229 230
        let result2 = scanner2
            .find_next_match_sync(String::from("{\"\": 1}"), 1)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
231
                "{\"index\":0,\"capture_indices\":[{\"start\":1,\"end\":2,\"length\":1}]}"
P
Phodal Huang 已提交
232 233
            )
        );
P
Phodal Huang 已提交
234
    }
P
Phodal Huang 已提交
235

236 237 238 239
    #[test]
    fn should_handle_unicode3() {
        let regex = vec![String::from("Y"), String::from("X")];
        let mut scanner = Scanner::new(regex);
P
Phodal Huang 已提交
240 241 242 243 244 245
        let result = scanner
            .find_next_match_sync(String::from("a💻bYX"), 0)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
246
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
247 248 249 250 251 252 253 254 255
            )
        );

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

        let result2 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 2)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
266
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
267 268 269 270 271 272 273 274 275
            )
        );

        let result3 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 3)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result3).unwrap(),
            String::from(
276
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
277 278 279 280 281 282 283 284 285
            )
        );

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

291 292 293
    #[test]
    fn should_out_of_bounds() {
        let mut scanner = Scanner::new(vec![String::from("X")]);
P
Phodal Huang 已提交
294 295 296 297 298 299
        let result = scanner
            .find_next_match_sync(String::from("X💻X"), -10000)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
300
                "{\"index\":0,\"capture_indices\":[{\"start\":0,\"end\":1,\"length\":1}]}"
P
Phodal Huang 已提交
301 302
            )
        );
303

304
        let result2 = scanner.find_next_match_sync(String::from("X💻X"), 10000);
305
        assert!(result2.is_none());
306 307 308 309 310 311
    }

    #[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);
312
        assert_eq!(format!("{:?}", result), "None");
313

P
Phodal Huang 已提交
314 315 316 317 318 319 320 321 322
        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}]}"
            )
        );
323
    }
P
Phodal Huang 已提交
324 325 326 327

    #[test]
    fn should_match_makefile_scan_regex() {
        let origin = vec![
328
            "(^[ \\t]+)?(?=#)",
P
Phodal Huang 已提交
329 330 331 332 333 334 335 336 337
            "(^[ ]*|\\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 已提交
338
            "^(ifeq|ifneq)(?=\\s)]",
P
Phodal Huang 已提交
339
        ];
P
Phodal Huang 已提交
340
        let _rules = vec![2, 7, 28, 45, 48, 51, 61, 64, 66, 69, 77];
P
Phodal Huang 已提交
341 342 343
        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);
344
        assert_eq!(3, result.unwrap().capture_indices.len());
P
Phodal Huang 已提交
345
    }
P
Phodal Huang 已提交
346 347 348

    #[test]
    fn should_match_makefile_special_char() {
P
Phodal Huang 已提交
349
        let origin = vec!["(?=\\s|$)", "(\\$?\\$)[@%<?^+*]", "\\$?\\$\\(", "%"];
P
Phodal Huang 已提交
350
        let _rules = vec![-1, 12, 14, 33];
P
Phodal Huang 已提交
351 352 353 354
        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 已提交
355 356 357
        assert_eq!(3, onig_match.index);
        assert_eq!(0, onig_match.clone().capture_indices[0].start);
        assert_eq!(1, onig_match.clone().capture_indices[0].end);
P
Phodal Huang 已提交
358
    }
P
Phodal Huang 已提交
359 360 361 362

    #[test]
    fn should_match_for_scope_target() {
        let origin = vec!["^(?!\\t)", "\\G", "^\\t"];
P
Phodal Huang 已提交
363
        let _rules = vec![-1, 36, 39];
P
Phodal Huang 已提交
364 365
        let debug_regex = str_vec_to_string(origin);
        let mut scanner = Scanner::new(debug_regex);
P
Phodal Huang 已提交
366 367 368 369 370 371 372
        let result = scanner.find_next_match_sync(
            String::from(
                "%.o: %.c $(DEPS)
",
            ),
            4,
        );
P
Phodal Huang 已提交
373
        let onig_match = result.unwrap();
374 375 376
        assert_eq!(1, onig_match.index);
        assert_eq!(4, onig_match.capture_indices[0].start);
        assert_eq!(4, onig_match.capture_indices[0].end);
P
Phodal Huang 已提交
377
    }
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396

    #[test]
    fn should_return_correct_index_when_for_markdown() {
        let origin = vec!["^", "\\\n", "%|\\*", "(^[ \t]+)?(?=#)", "(\\$?\\$)[@%<?^+*]", "\\$?\\$\\("];
        let _rules = vec![-1, 37, 38, 2, 12, 14];
        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)
",
            ),
            4,
        );
        let onig_match = result.unwrap();
        assert_eq!(2, onig_match.index);
        assert_eq!(5, onig_match.capture_indices[0].start);
        assert_eq!(6, onig_match.capture_indices[0].end);
    }
397 398 399 400 401 402 403 404 405 406 407 408 409

    #[test]
    fn should_return_null_when_out_size() {
        let origin = vec!["^", "\\\n", "%|\\*", "(^[ \t]+)?(?=#)", "(\\$?\\$)[@%<?^+*]", "\\$?\\$\\("];
        let _rules = vec![-1, 37, 38, 2, 12, 14];
        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)"),
            16,
        );
        assert!(result.is_none());
    }
P
Phodal Huang 已提交
410
}