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
use crate::engine::all::MatchAllEngine;
use crate::engine::andor::{AndEngine, OrEngine};
use crate::engine::exact::{ExactEngine, ExactMatchingParam};
use crate::engine::fuzzy::{FuzzyAlgorithm, FuzzyEngine};
use crate::engine::regexp::RegexEngine;
use crate::item::RankBuilder;
use crate::{CaseMatching, MatchEngine, MatchEngineFactory};
use regex::Regex;
use std::sync::Arc;

lazy_static! {
    static ref RE_AND: Regex = Regex::new(r"([^ |]+( +\| +[^ |]*)+)|( +)").unwrap();
    static ref RE_OR: Regex = Regex::new(r" +\| +").unwrap();
}
//------------------------------------------------------------------------------
// Exact engine factory
pub struct ExactOrFuzzyEngineFactory {
    exact_mode: bool,
    fuzzy_algorithm: FuzzyAlgorithm,
    rank_builder: Arc<RankBuilder>,
}

impl ExactOrFuzzyEngineFactory {
    pub fn builder() -> Self {
        Self {
            exact_mode: false,
            fuzzy_algorithm: FuzzyAlgorithm::SkimV2,
            rank_builder: Default::default(),
        }
    }

    pub fn exact_mode(mut self, exact_mode: bool) -> Self {
        self.exact_mode = exact_mode;
        self
    }

    pub fn fuzzy_algorithm(mut self, fuzzy_algorithm: FuzzyAlgorithm) -> Self {
        self.fuzzy_algorithm = fuzzy_algorithm;
        self
    }

    pub fn rank_builder(mut self, rank_builder: Arc<RankBuilder>) -> Self {
        self.rank_builder = rank_builder;
        self
    }

    pub fn build(self) -> Self {
        self
    }
}

impl MatchEngineFactory for ExactOrFuzzyEngineFactory {
    fn create_engine_with_case(&self, query: &str, case: CaseMatching) -> Box<dyn MatchEngine> {
        // 'abc => match exact "abc"
        // ^abc => starts with "abc"
        // abc$ => ends with "abc"
        // ^abc$ => match exact "abc"
        // !^abc => items not starting with "abc"
        // !abc$ => items not ending with "abc"
        // !^abc$ => not "abc"

        let mut query = query;
        let mut exact = false;
        let mut param = ExactMatchingParam::default();
        param.case = case;

        if query.starts_with('\'') {
            if self.exact_mode {
                return Box::new(
                    FuzzyEngine::builder()
                        .query(&query[1..])
                        .algorithm(self.fuzzy_algorithm)
                        .case(case)
                        .rank_builder(self.rank_builder.clone())
                        .build(),
                );
            } else {
                exact = true;
                query = &query[1..];
            }
        }

        if query.starts_with('!') {
            query = &query[1..];
            exact = true;
            param.inverse = true;
        }

        if query.is_empty() {
            // if only "!" was provided, will still show all items
            return Box::new(
                MatchAllEngine::builder()
                    .rank_builder(self.rank_builder.clone())
                    .build(),
            );
        }

        if query.starts_with('^') {
            query = &query[1..];
            exact = true;
            param.prefix = true;
        }

        if query.ends_with('$') {
            query = &query[..(query.len() - 1)];
            exact = true;
            param.postfix = true;
        }

        if self.exact_mode {
            exact = true;
        }

        if exact {
            Box::new(
                ExactEngine::builder(query, param)
                    .rank_builder(self.rank_builder.clone())
                    .build(),
            )
        } else {
            Box::new(
                FuzzyEngine::builder()
                    .query(query)
                    .algorithm(self.fuzzy_algorithm)
                    .case(case)
                    .rank_builder(self.rank_builder.clone())
                    .build(),
            )
        }
    }
}

//------------------------------------------------------------------------------
pub struct AndOrEngineFactory {
    inner: Box<dyn MatchEngineFactory>,
}

impl AndOrEngineFactory {
    pub fn new(factory: Box<dyn MatchEngineFactory>) -> Self {
        Self { inner: factory }
    }

    // we want to treat `\ ` as plain white space
    // regex crate doesn't support look around, so I use a lazy workaround
    // that replace `\ ` with `\0` ahead of split and replace it back afterwards
    fn parse_or(&self, query: &str, case: CaseMatching) -> Box<dyn MatchEngine> {
        if query.trim().is_empty() {
            self.inner.create_engine_with_case(query, case)
        } else {
            let engines = RE_OR
                .split(&self.mask_escape_space(query))
                .map(|q| self.parse_and(q, case))
                .collect();
            Box::new(OrEngine::builder().engines(engines).build())
        }
    }

    fn parse_and(&self, query: &str, case: CaseMatching) -> Box<dyn MatchEngine> {
        let query_trim = query.trim_matches(|c| c == ' ' || c == '|');
        let mut engines = vec![];
        let mut last = 0;
        for mat in RE_AND.find_iter(query_trim) {
            let (start, end) = (mat.start(), mat.end());
            let term = query_trim[last..start].trim_matches(|c| c == ' ' || c == '|');
            let term = self.unmask_escape_space(term);
            if !term.is_empty() {
                engines.push(self.inner.create_engine_with_case(&term, case));
            }

            if !mat.as_str().trim().is_empty() {
                engines.push(self.parse_or(mat.as_str().trim(), case));
            }
            last = end;
        }

        let term = query_trim[last..].trim_matches(|c| c == ' ' || c == '|');
        let term = self.unmask_escape_space(term);
        if !term.is_empty() {
            engines.push(self.inner.create_engine_with_case(&term, case));
        }
        Box::new(AndEngine::builder().engines(engines).build())
    }

    fn mask_escape_space(&self, string: &str) -> String {
        string.replace("\\ ", "\0")
    }

    fn unmask_escape_space(&self, string: &str) -> String {
        string.replace('\0', " ")
    }
}

impl MatchEngineFactory for AndOrEngineFactory {
    fn create_engine_with_case(&self, query: &str, case: CaseMatching) -> Box<dyn MatchEngine> {
        self.parse_or(query, case)
    }
}

//------------------------------------------------------------------------------
pub struct RegexEngineFactory {
    rank_builder: Arc<RankBuilder>,
}

impl RegexEngineFactory {
    pub fn builder() -> Self {
        Self {
            rank_builder: Default::default(),
        }
    }

    pub fn rank_builder(mut self, rank_builder: Arc<RankBuilder>) -> Self {
        self.rank_builder = rank_builder;
        self
    }

    pub fn build(self) -> Self {
        self
    }
}

impl MatchEngineFactory for RegexEngineFactory {
    fn create_engine_with_case(&self, query: &str, case: CaseMatching) -> Box<dyn MatchEngine> {
        Box::new(
            RegexEngine::builder(query, case)
                .rank_builder(self.rank_builder.clone())
                .build(),
        )
    }
}

mod test {
    #[test]
    fn test_engine_factory() {
        use super::*;
        let exact_or_fuzzy = ExactOrFuzzyEngineFactory::builder().build();
        let x = exact_or_fuzzy.create_engine("'abc");
        assert_eq!(format!("{}", x), "(Exact|(?i)abc)");

        let x = exact_or_fuzzy.create_engine("^abc");
        assert_eq!(format!("{}", x), "(Exact|(?i)^abc)");

        let x = exact_or_fuzzy.create_engine("abc$");
        assert_eq!(format!("{}", x), "(Exact|(?i)abc$)");

        let x = exact_or_fuzzy.create_engine("^abc$");
        assert_eq!(format!("{}", x), "(Exact|(?i)^abc$)");

        let x = exact_or_fuzzy.create_engine("!abc");
        assert_eq!(format!("{}", x), "(Exact|!(?i)abc)");

        let x = exact_or_fuzzy.create_engine("!^abc");
        assert_eq!(format!("{}", x), "(Exact|!(?i)^abc)");

        let x = exact_or_fuzzy.create_engine("!abc$");
        assert_eq!(format!("{}", x), "(Exact|!(?i)abc$)");

        let x = exact_or_fuzzy.create_engine("!^abc$");
        assert_eq!(format!("{}", x), "(Exact|!(?i)^abc$)");

        let regex_factory = RegexEngineFactory::builder();
        let and_or_factory = AndOrEngineFactory::new(Box::new(exact_or_fuzzy));

        let x = and_or_factory.create_engine("'abc | def ^gh ij | kl mn");
        assert_eq!(
            format!("{}", x),
            "(Or: (And: (Exact|(?i)abc)), (And: (Fuzzy: def), (Exact|(?i)^gh), (Fuzzy: ij)), (And: (Fuzzy: kl), (Fuzzy: mn)))"
        );

        let x = regex_factory.create_engine("'abc | def ^gh ij | kl mn");
        assert_eq!(format!("{}", x), "(Regex: 'abc | def ^gh ij | kl mn)");
    }
}