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
use super::vm::{Regex, N_SLOTS};
use crate::buffer::{GapBuffer, IdxChars};
use std::{
    iter::{Enumerate, Skip},
    rc::Rc,
    str::Chars,
};

/// The match location of a Regex against a given input.
///
/// The sub-match indices are relative to the input used to run the original match.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Match {
    pub(super) sub_matches: [usize; N_SLOTS],
    pub(super) submatch_names: Rc<[String]>,
}

impl Match {
    pub(crate) fn synthetic(from: usize, to: usize) -> Self {
        let mut sub_matches = [0; N_SLOTS];
        sub_matches[0] = from;
        sub_matches[1] = to;
        Self {
            sub_matches,
            submatch_names: Rc::new([]),
        }
    }

    pub(crate) fn apply_offset(&mut self, offset: isize) {
        for i in 0..N_SLOTS {
            if i > 0 && self.sub_matches[i] == 0 {
                continue;
            }
            self.sub_matches[i] = (self.sub_matches[i] as isize + offset) as usize;
        }
    }

    pub fn str_match_text(&self, s: &str) -> String {
        let (a, b) = self.loc();
        s.chars().skip(a).take(b - a).collect()
    }

    /// The start and end of this match in terms of byte offsets
    ///
    /// use loc for character offsets
    #[inline]
    pub fn str_loc_bytes(&self, s: &str) -> (usize, usize) {
        let (a, b) = self.loc();
        let mut it = s.char_indices().skip(a);
        let (first, _) = it.next().unwrap();
        let (last, _) = it.take(b - a - 1).last().unwrap_or((first, ' '));

        (first, last)
    }

    /// The start and end of the nth submatch in terms of byte offsets
    #[inline]
    pub fn str_sub_loc_bytes(&self, n: usize, s: &str) -> Option<(usize, usize)> {
        let (a, b) = self.sub_loc(n)?;
        let mut it = s.char_indices().skip(a);
        let (first, _) = it.next().unwrap();
        let (last, _) = it.take(b - a - 1).last().unwrap_or((first, ' '));

        Some((first, last))
    }

    // FIXME: this is a terrible way to do this but used for testing at the moment
    pub fn named_matches(&self) -> Vec<&str> {
        let mut matches = Vec::new();
        for name in self.submatch_names.iter() {
            if self.sub_loc_by_name(name).is_some() {
                matches.push(name.as_str());
            }
        }

        matches
    }

    /// The start and end of a named submatch in terms of byte offsets
    #[inline]
    pub fn str_sub_loc_bytes_by_name(&self, name: &str, s: &str) -> Option<(usize, usize)> {
        let (a, b) = self.sub_loc_by_name(name)?;
        let mut it = s.char_indices().skip(a);
        let (first, _) = it.next().unwrap();
        let (last, _) = it.take(b - a - 1).last().unwrap_or((first, ' '));

        Some((first, last))
    }

    pub fn str_sub_loc_text_ref_by_name<'a>(&self, name: &str, s: &'a str) -> Option<&'a str> {
        let (first, last) = self.str_sub_loc_bytes_by_name(name, s)?;

        Some(&s[first..=last])
    }

    pub fn str_match_text_ref<'a>(&self, s: &'a str) -> &'a str {
        let (first, last) = self.str_loc_bytes(s);

        &s[first..=last]
    }

    pub(crate) fn str_match_text_ref_with_byte_offsets<'a>(
        &self,
        s: &'a str,
    ) -> (usize, usize, &'a str) {
        let (first, last) = self.str_loc_bytes(s);

        (first, last, &s[first..=last])
    }

    pub fn str_submatch_text(&self, n: usize, s: &str) -> Option<String> {
        let (a, b) = self.sub_loc(n)?;
        Some(s.chars().skip(a).take(b - a).collect())
    }

    /// The start and end of this match in terms of character offsets
    ///
    /// use str_loc_bytes for byte offsets
    pub fn loc(&self) -> (usize, usize) {
        let (start, end) = (self.sub_matches[0], self.sub_matches[1]);

        assert!(
            start <= end,
            "invalid match: {start} > {end}: {:?}",
            self.sub_matches
        );

        (start, end)
    }

    pub fn sub_loc_by_name(&self, name: &str) -> Option<(usize, usize)> {
        let n = self.submatch_names.iter().position(|s| s == name)?;
        self.sub_loc(n + 1)
    }

    pub fn sub_loc(&self, n: usize) -> Option<(usize, usize)> {
        if 2 * n + 1 >= N_SLOTS {
            return None;
        }
        let (start, end) = (self.sub_matches[2 * n], self.sub_matches[2 * n + 1]);
        if n > 0 && start == 0 && end == 0 {
            return None;
        }

        assert!(
            start <= end,
            "invalid match: {start} > {end}: {:?}",
            self.sub_matches
        );

        Some((start, end))
    }
}

pub trait IndexedChars {
    type I: Iterator<Item = (usize, char)>;
    fn iter_from(&self, from: usize) -> Option<Self::I>;
}

impl<'a> IndexedChars for &'a str {
    type I = Skip<Enumerate<Chars<'a>>>;

    fn iter_from(&self, from: usize) -> Option<Self::I> {
        // This is not at all efficient but we only really make use of strings in test cases where
        // the length of the string is small. For the "real" impls using GapBuffers, checking the number
        // of chars in the buffer is O(1) as we cache it.
        if from >= self.chars().count() {
            None
        } else {
            Some(self.chars().enumerate().skip(from))
        }
    }
}

impl<'a> IndexedChars for &'a GapBuffer {
    type I = IdxChars<'a>;

    fn iter_from(&self, from: usize) -> Option<Self::I> {
        if from >= self.len_chars() {
            None
        } else {
            Some(
                self.slice(from, self.len_chars())
                    .indexed_chars(from, false),
            )
        }
    }
}

/// An iterator over sequential, non overlapping matches of a Regex
/// against a given input
pub struct MatchIter<'a, I>
where
    I: IndexedChars,
{
    pub(super) it: I,
    pub(super) r: &'a mut Regex,
    pub(super) from: usize,
}

impl<'a, I> Iterator for MatchIter<'a, I>
where
    I: IndexedChars,
{
    type Item = Match;

    fn next(&mut self) -> Option<Self::Item> {
        let m = self
            .r
            .match_iter(&mut self.it.iter_from(self.from)?, self.from)?;

        let (_, from) = m.loc();
        if from == self.from {
            self.from += 1;
        } else {
            self.from = from;
        }

        Some(m)
    }
}