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
use regex::Regex;

/// Returned by [Pattern] on match.
#[derive(Debug, Clone, PartialEq)]
pub struct Match<'a> {
    /// The string that was searched in
    pub base: &'a str,
    /// Start of the match
    pub start: usize,
    /// End of the match
    pub end: usize,
}

impl<'a> Match<'a> {
    /// Create a match from a base string and start..end range.
    ///
    /// # Panics
    /// When ```rust start >= end``` or ```rust base.len() < end```.
    ///
    /// # Example
    /// ```should_panic
    /// use lexer::pattern::Match;
    ///
    /// let mat = Match::new("don't go to far...", 0, 100000);
    /// ```
    pub fn new(base: &'a str, start: usize, end: usize) -> Self {
        assert!(start < end);
        assert!(base.len() >= end);
        Self { base, start, end }
    }

    /// Convert to to &str.
    ///
    /// # Example
    /// ```rust
    /// use lexer::pattern::Match;
    ///
    /// let mat = Match::new("it's here not here", 5, 9);
    ///
    /// assert_eq!(mat.as_str(), "here");
    /// ```
    pub fn as_str(&self) -> &'a str {
        &self.base[self.start..self.end]
    }
}

/// A string Pattern.
/// The type implementing it can be used as a pattern for ```rust &str```.
///
/// By default it is implemented for the following types:
/// | Pattern type                   | Match condition                         |
/// |--------------------------------|-----------------------------------------|
/// | ```rust char```                | is contained in string                  |
/// | ```rust `&str```               | is substring                            |
/// | ```rust String```              | is substring                            |
/// | ```rust `&[char]```            | any char is contained in string         |
/// | ```rust `&[&str]```            | any &str is substring                   |
/// | ```rust F: Fn(&str) -> bool``` | F returns ```rust true``` for substring |
/// | ```rust Regex```               | ```rust Regex``` match substring        |
pub trait Pattern<'a> {
    /// Find all occurences of the pattern in the given value.
    ///
    /// # Examples
    /// ```rust
    /// use lexer::pattern::{Match, Pattern};
    ///
    /// assert!("ab".find_in("cd").is_empty());
    /// assert_eq!("ab".find_in("cabd"), vec![Match::new("cabd", 1, 3)]);
    /// ```
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>>;

    /// Find all occurences of the pattern in the given value that are prefixes.
    ///
    /// # Examples
    /// ```rust
    /// use lexer::pattern::{Match, Pattern};
    ///
    /// assert!("ab".find_prefix_in("cdab").is_empty());
    /// assert_eq!("ab".find_prefix_in("abcd"), vec![Match::new("abcd", 0, 2)]);
    /// ```
    fn find_prefix_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.find_in(value)
            .into_iter()
            .filter(|mat| mat.start == 0)
            .collect()
    }

    /// Find all occurences of the pattern in the given value that are suffixes.
    ///
    /// # Examples
    /// ```rust
    /// use lexer::pattern::{Match, Pattern};
    ///
    /// assert!("ab".find_suffix_in("abcd").is_empty());
    /// assert_eq!("ab".find_suffix_in("cdab"), vec![Match::new("cdab", 2, 4)]);
    /// ```
    fn find_suffix_in(&self, value: &'a str) -> Vec<Match<'a>> {
        let len = value.len();
        self.find_in(value)
            .into_iter()
            .filter(|mat| mat.end == len)
            .collect()
    }

    /// Find one occurrence of the pattern in the given value.
    ///
    /// # Examples
    /// ```rust
    /// use lexer::pattern::{Match, Pattern};
    ///
    /// assert!("ab".find_one_in("cd").is_none());
    /// assert_eq!("ab".find_one_in("cdab"), Some(Match::new("cdab", 2, 4)));
    /// ```
    fn find_one_in(&self, value: &'a str) -> Option<Match<'a>> {
        self.find_in(value).into_iter().next()
    }

    /// Find one occurrence of the pattern in the given value that is prefix.
    ///
    /// # Examples
    /// ```rust
    /// use lexer::pattern::{Match, Pattern};
    ///
    /// assert!("ab".find_one_prefix_in("cdab").is_none());
    /// assert_eq!("ab".find_one_prefix_in("abcd"), Some(Match::new("abcd", 0, 2)));
    /// ```
    fn find_one_prefix_in(&self, value: &'a str) -> Option<Match<'a>> {
        self.find_prefix_in(value).into_iter().next()
    }

    /// Find one occurrence of the pattern in the given value that is suffix.
    ///
    /// # Examples
    /// ```rust
    /// use lexer::pattern::{Match, Pattern};
    ///
    /// assert!("ab".find_one_suffix_in("abcd").is_none());
    /// assert_eq!("ab".find_one_suffix_in("cdab"), Some(Match::new("cdab", 2, 4)));
    /// ```
    fn find_one_suffix_in(&self, value: &'a str) -> Option<Match<'a>> {
        self.find_suffix_in(value).into_iter().next()
    }
}

impl<'a> Pattern<'a> for char {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        value
            .match_indices(&self.to_string())
            .map(|(i, mat)| Match::new(value, i, i + mat.len()))
            .collect()
    }
}

impl<'a> Pattern<'a> for [char] {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.iter().flat_map(|ch| ch.find_in(value)).collect()
    }
}

impl<'a, const N: usize> Pattern<'a> for [char; N] {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(value)
    }
}

impl<'a, const N: usize> Pattern<'a> for &[char; N] {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(value)
    }
}

impl<'a> Pattern<'a> for String {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        value
            .match_indices(self)
            .map(|(i, mat)| Match::new(value, i, i + mat.len()))
            .collect()
    }
}

impl<'a> Pattern<'a> for &str {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.to_string().find_in(value)
    }
}

impl<'a> Pattern<'a> for [&str] {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.iter().flat_map(|ch| ch.find_in(value)).collect()
    }
}

impl<'a, const N: usize> Pattern<'a> for [&str; N] {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(value)
    }
}

impl<'a, const N: usize> Pattern<'a> for &[&str; N] {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(value)
    }
}

impl<'a: 'b, 'b, F> Pattern<'a> for F
where
    F: Fn(&'b str) -> bool,
{
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        let mut matches = Vec::new();
        let mut cur_1 = 0;
        // The goal is to check from left to right and to take the largest match
        while cur_1 < value.len() {
            let mut cur_2 = value.len();
            while cur_2 > cur_1 {
                let sub = &value[cur_1..cur_2];
                if (self)(sub) {
                    matches.push(Match::new(value, cur_1, cur_2));
                    cur_1 = cur_2;
                }
                cur_2 -= 1
            }
            cur_1 += 1;
        }
        matches
    }
}

impl<'a> Pattern<'a> for Regex {
    fn find_in(&self, value: &'a str) -> Vec<Match<'a>> {
        self.find_iter(value)
            .map(|mat| Match::new(value, mat.start(), mat.end()))
            .collect()
    }
}