gix_glob/
wildmatch.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use bitflags::bitflags;
bitflags! {
    /// The match mode employed in [`Pattern::matches()`][crate::Pattern::matches()].
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
    pub struct Mode: u8 {
        /// Let globs like `*` and `?` not match the slash `/` literal, which is useful when matching paths.
        const NO_MATCH_SLASH_LITERAL = 1 << 0;
        /// Match case insensitively for ascii characters only.
        const IGNORE_CASE = 1 << 1;
    }
}

pub(crate) mod function {
    use bstr::{BStr, ByteSlice};

    use crate::wildmatch::Mode;

    #[derive(Eq, PartialEq)]
    enum Result {
        Match,
        NoMatch,
        AbortAll,
        AbortToStarStar,
        RecursionLimitReached,
    }

    const STAR: u8 = b'*';
    const BACKSLASH: u8 = b'\\';
    const SLASH: u8 = b'/';
    const BRACKET_OPEN: u8 = b'[';
    const BRACKET_CLOSE: u8 = b']';
    const COLON: u8 = b':';

    const NEGATE_CLASS: u8 = b'!';
    /// Setting this limit to something reasonable means less compute time spent on unnecessarily complex patterns, or malicious ones.
    const RECURSION_LIMIT: usize = 64;

    fn match_recursive(pattern: &BStr, text: &BStr, mode: Mode, depth: usize) -> Result {
        if depth == RECURSION_LIMIT {
            return RecursionLimitReached;
        }
        use self::Result::*;
        let possibly_lowercase = |c: &u8| {
            if mode.contains(Mode::IGNORE_CASE) {
                c.to_ascii_lowercase()
            } else {
                *c
            }
        };
        let mut p = pattern.iter().map(possibly_lowercase).enumerate().peekable();
        let mut t = text.iter().map(possibly_lowercase).enumerate();

        while let Some((mut p_idx, mut p_ch)) = p.next() {
            let (mut t_idx, mut t_ch) = match t.next() {
                Some(c) => c,
                None if p_ch != STAR => return AbortAll,
                None => (text.len(), 0),
            };

            if p_ch == BACKSLASH {
                match p.next() {
                    Some((_p_idx, p_ch)) => {
                        if p_ch != t_ch {
                            return NoMatch;
                        } else {
                            continue;
                        }
                    }
                    None => return NoMatch,
                };
            }
            match p_ch {
                b'?' => {
                    if mode.contains(Mode::NO_MATCH_SLASH_LITERAL) && t_ch == SLASH {
                        return NoMatch;
                    } else {
                        continue;
                    }
                }
                STAR => {
                    let mut match_slash = !mode.contains(Mode::NO_MATCH_SLASH_LITERAL);
                    match p.next() {
                        Some((next_p_idx, next_p_ch)) => {
                            let next;
                            if next_p_ch == STAR {
                                let leading_slash_idx = p_idx.checked_sub(1);
                                while p.next_if(|(_, c)| *c == STAR).is_some() {}
                                next = p.next();
                                if !mode.contains(Mode::NO_MATCH_SLASH_LITERAL) {
                                    match_slash = true;
                                } else if leading_slash_idx.map_or(true, |idx| pattern[idx] == SLASH)
                                    && next.map_or(true, |(_, c)| {
                                        c == SLASH || (c == BACKSLASH && p.peek().map(|t| t.1) == Some(SLASH))
                                    })
                                {
                                    if next.map_or(NoMatch, |(idx, _)| {
                                        match_recursive(
                                            pattern[idx + 1..].as_bstr(),
                                            text[t_idx..].as_bstr(),
                                            mode,
                                            depth + 1,
                                        )
                                    }) == Match
                                    {
                                        return Match;
                                    }
                                    match_slash = true;
                                } else {
                                    match_slash = false;
                                }
                            } else {
                                next = Some((next_p_idx, next_p_ch));
                            }

                            match next {
                                None => {
                                    return if !match_slash && text[t_idx..].contains(&SLASH) {
                                        NoMatch
                                    } else {
                                        Match
                                    };
                                }
                                Some((next_p_idx, next_p_ch)) => {
                                    p_idx = next_p_idx;
                                    p_ch = next_p_ch;
                                    if !match_slash && p_ch == SLASH {
                                        match text[t_idx..].find_byte(SLASH) {
                                            Some(distance_to_slash) => {
                                                for _ in t.by_ref().take(distance_to_slash) {}
                                                continue;
                                            }
                                            None => return NoMatch,
                                        }
                                    }
                                }
                            }
                        }
                        None => {
                            return if !match_slash && text[t_idx..].contains(&SLASH) {
                                NoMatch
                            } else {
                                Match
                            }
                        }
                    }

                    return loop {
                        if !crate::parse::GLOB_CHARACTERS.contains(&p_ch) {
                            loop {
                                if (!match_slash && t_ch == SLASH) || t_ch == p_ch {
                                    break;
                                }
                                match t.next() {
                                    Some(t) => {
                                        t_idx = t.0;
                                        t_ch = t.1;
                                    }
                                    None => break,
                                };
                            }
                            if t_ch != p_ch {
                                return NoMatch;
                            }
                        }
                        let res = match_recursive(pattern[p_idx..].as_bstr(), text[t_idx..].as_bstr(), mode, depth + 1);
                        if res != NoMatch {
                            if !match_slash || res != AbortToStarStar {
                                return res;
                            }
                        } else if !match_slash && t_ch == SLASH {
                            return AbortToStarStar;
                        }
                        match t.next() {
                            Some(t) => {
                                t_idx = t.0;
                                t_ch = t.1;
                            }
                            None => break AbortAll,
                        };
                    };
                }
                BRACKET_OPEN => {
                    match p.next() {
                        Some(t) => {
                            p_idx = t.0;
                            p_ch = t.1;
                        }
                        None => return AbortAll,
                    };

                    if p_ch == b'^' {
                        p_ch = NEGATE_CLASS;
                    }
                    let negated = p_ch == NEGATE_CLASS;
                    let mut next = if negated { p.next() } else { Some((p_idx, p_ch)) };
                    let mut prev_p_ch = 0;
                    let mut matched = false;
                    let mut p_idx_ofs = 0;
                    loop {
                        let Some((mut p_idx, mut p_ch)) = next else {
                            return AbortAll;
                        };
                        p_idx += p_idx_ofs;
                        match p_ch {
                            BACKSLASH => match p.next() {
                                Some((_, p_ch)) => {
                                    if p_ch == t_ch {
                                        matched = true;
                                    } else {
                                        prev_p_ch = p_ch;
                                    }
                                }
                                None => return AbortAll,
                            },
                            b'-' if prev_p_ch != 0
                                && p.peek().is_some()
                                && p.peek().map(|t| t.1) != Some(BRACKET_CLOSE) =>
                            {
                                p_ch = p.next().expect("peeked").1;
                                if p_ch == BACKSLASH {
                                    p_ch = match p.next() {
                                        Some(t) => t.1,
                                        None => return AbortAll,
                                    };
                                }
                                if t_ch <= p_ch && t_ch >= prev_p_ch {
                                    matched = true;
                                } else if mode.contains(Mode::IGNORE_CASE) && t_ch.is_ascii_lowercase() {
                                    let t_ch_upper = t_ch.to_ascii_uppercase();
                                    if (t_ch_upper <= p_ch.to_ascii_uppercase()
                                        && t_ch_upper >= prev_p_ch.to_ascii_uppercase())
                                        || (t_ch_upper <= prev_p_ch.to_ascii_uppercase()
                                            && t_ch_upper >= p_ch.to_ascii_uppercase())
                                    {
                                        matched = true;
                                    }
                                }
                                prev_p_ch = 0;
                            }
                            BRACKET_OPEN if matches!(p.peek(), Some((_, COLON))) => {
                                p.next();
                                while p.peek().map_or(false, |t| t.1 != BRACKET_CLOSE) {
                                    p.next();
                                }
                                let closing_bracket_idx = match p.next() {
                                    Some((idx, _)) => idx,
                                    None => return AbortAll,
                                };
                                const BRACKET__COLON__BRACKET: usize = 3;
                                if closing_bracket_idx.saturating_sub(p_idx) < BRACKET__COLON__BRACKET
                                    || pattern[closing_bracket_idx - 1] != COLON
                                {
                                    if t_ch == BRACKET_OPEN {
                                        matched = true;
                                    }
                                    if p_idx > pattern.len() {
                                        return AbortAll;
                                    }
                                    p = pattern[p_idx..].iter().map(possibly_lowercase).enumerate().peekable();
                                    p_idx_ofs += p_idx;
                                } else {
                                    let class = &pattern.as_bytes()[p_idx + 2..closing_bracket_idx - 1];
                                    match class {
                                        b"alnum" => {
                                            if t_ch.is_ascii_alphanumeric() {
                                                matched = true;
                                            }
                                        }
                                        b"alpha" => {
                                            if t_ch.is_ascii_alphabetic() {
                                                matched = true;
                                            }
                                        }
                                        b"blank" => {
                                            if t_ch.is_ascii_whitespace() {
                                                matched = true;
                                            }
                                        }
                                        b"cntrl" => {
                                            if t_ch.is_ascii_control() {
                                                matched = true;
                                            }
                                        }
                                        b"digit" => {
                                            if t_ch.is_ascii_digit() {
                                                matched = true;
                                            }
                                        }

                                        b"graph" => {
                                            if t_ch.is_ascii_graphic() {
                                                matched = true;
                                            }
                                        }
                                        b"lower" => {
                                            if t_ch.is_ascii_lowercase() {
                                                matched = true;
                                            }
                                        }
                                        b"print" => {
                                            if (0x20u8..=0x7e).contains(&t_ch) {
                                                matched = true;
                                            }
                                        }
                                        b"punct" => {
                                            if t_ch.is_ascii_punctuation() {
                                                matched = true;
                                            }
                                        }
                                        b"space" => {
                                            if t_ch == b' ' {
                                                matched = true;
                                            }
                                        }
                                        b"upper" => {
                                            if t_ch.is_ascii_uppercase()
                                                || mode.contains(Mode::IGNORE_CASE) && t_ch.is_ascii_lowercase()
                                            {
                                                matched = true;
                                            }
                                        }
                                        b"xdigit" => {
                                            if t_ch.is_ascii_hexdigit() {
                                                matched = true;
                                            }
                                        }
                                        _ => return AbortAll,
                                    };
                                    prev_p_ch = 0;
                                }
                            }
                            _ => {
                                prev_p_ch = p_ch;
                                if p_ch == t_ch {
                                    matched = true;
                                }
                            }
                        };
                        next = p.next();
                        if let Some((_, BRACKET_CLOSE)) = next {
                            break;
                        }
                    }
                    if matched == negated || mode.contains(Mode::NO_MATCH_SLASH_LITERAL) && t_ch == SLASH {
                        return NoMatch;
                    }
                    continue;
                }
                non_glob_ch => {
                    if non_glob_ch != t_ch {
                        return NoMatch;
                    } else {
                        continue;
                    }
                }
            }
        }
        t.next().map_or(Match, |_| NoMatch)
    }

    /// Employ pattern matching to see if `value` matches `pattern`.
    ///
    /// `mode` can be used to adjust the way the matching is performed.
    pub fn wildmatch(pattern: &BStr, value: &BStr, mode: Mode) -> bool {
        let res = match_recursive(pattern, value, mode, 0);
        if res == Result::RecursionLimitReached {
            gix_features::trace::error!("Recursion limit of {} reached for pattern '{pattern}'", RECURSION_LIMIT);
        }
        res == Result::Match
    }
}