scanner.rs 12.2 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

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

P
Phodal Huang 已提交
98
        if all_results.len() > 0 {
P
Phodal Huang 已提交
99 100 101
            let mut best_match = all_results[0].clone();
            for x in all_results {
                // todo: maybe have multiple captures
102
                if x.capture_indices[0].start <= best_match.capture_indices[0].start {
P
Phodal Huang 已提交
103 104 105 106
                    best_match = x;
                }
            }
            Some(best_match.clone())
P
Phodal Huang 已提交
107
        } else {
P
Phodal Huang 已提交
108
            None
P
Phodal Huang 已提交
109
        }
P
Phodal Huang 已提交
110 111 112
    }
}

P
Phodal Huang 已提交
113
pub fn str_vec_to_string<I, T>(iter: I) -> Vec<String>
114 115 116
    where
        I: IntoIterator<Item=T>,
        T: Into<String>,
P
Phodal Huang 已提交
117 118 119 120
{
    iter.into_iter().map(Into::into).collect()
}

P
Phodal Huang 已提交
121 122
#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
123
    use crate::scanner::scanner::{str_vec_to_string, Scanner};
P
Phodal Huang 已提交
124 125 126 127

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

P
Phodal Huang 已提交
135
        let second_result = scanner.find_next_match_sync(s, 2).unwrap();
P
Phodal Huang 已提交
136 137 138
        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 已提交
139
    }
P
Phodal Huang 已提交
140 141 142 143 144 145

    #[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 已提交
146 147 148 149 150
        if let None = scanner.find_next_match_sync(String::from("x"), 0) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
151

P
Phodal Huang 已提交
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
        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 已提交
181 182 183 184 185 186

        if let None = scanner.find_next_match_sync(String::from("xxaxxbxxc"), 9) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
187
    }
P
Phodal Huang 已提交
188 189 190 191 192 193

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

P
Phodal Huang 已提交
194 195 196 197 198 199
        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 已提交
200
                "{\"index\":1,\"capture_indices\":[{\"start\":6,\"end\":7,\"length\":1}]}"
P
Phodal Huang 已提交
201 202
            )
        );
P
Phodal Huang 已提交
203 204 205 206 207
    }

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

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

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

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

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

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

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

287 288 289 290 291 292 293 294
        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);
295
        assert_eq!(format!("{:?}", result), "None");
296

P
Phodal Huang 已提交
297 298 299 300 301 302 303 304 305
        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}]}"
            )
        );
306
    }
P
Phodal Huang 已提交
307 308 309 310

    #[test]
    fn should_match_makefile_scan_regex() {
        let origin = vec![
311
            "(^[ \\t]+)?(?=#)",
P
Phodal Huang 已提交
312 313 314 315 316 317 318 319 320
            "(^[ ]*|\\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 已提交
321
            "^(ifeq|ifneq)(?=\\s)]",
P
Phodal Huang 已提交
322
        ];
P
Phodal Huang 已提交
323
        let _rules = vec![2, 7, 28, 45, 48, 51, 61, 64, 66, 69, 77];
P
Phodal Huang 已提交
324 325 326
        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);
327
        assert_eq!(3, result.unwrap().capture_indices.len());
P
Phodal Huang 已提交
328
    }
P
Phodal Huang 已提交
329 330 331

    #[test]
    fn should_match_makefile_special_char() {
P
Phodal Huang 已提交
332
        let origin = vec!["(?=\\s|$)", "(\\$?\\$)[@%<?^+*]", "\\$?\\$\\(", "%"];
P
Phodal Huang 已提交
333
        let _rules = vec![-1, 12, 14, 33];
P
Phodal Huang 已提交
334 335 336 337
        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 已提交
338 339 340
        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 已提交
341
    }
P
Phodal Huang 已提交
342 343 344 345

    #[test]
    fn should_match_for_scope_target() {
        let origin = vec!["^(?!\\t)", "\\G", "^\\t"];
P
Phodal Huang 已提交
346
        let _rules = vec![-1, 36, 39];
P
Phodal Huang 已提交
347 348
        let debug_regex = str_vec_to_string(origin);
        let mut scanner = Scanner::new(debug_regex);
P
Phodal Huang 已提交
349 350 351 352 353 354 355
        let result = scanner.find_next_match_sync(
            String::from(
                "%.o: %.c $(DEPS)
",
            ),
            4,
        );
P
Phodal Huang 已提交
356
        let onig_match = result.unwrap();
357 358 359
        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 已提交
360
    }
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

    #[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);
    }
P
Phodal Huang 已提交
380
}