caio.co/de/cantine


Add support for parsing +mandatory queries 💬 by Caio 4 years ago (log)
And rename `negated` to `prohibited`

Blob tique/src/queryparser/parser.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
use nom::{
    self,
    branch::alt,
    bytes::complete::take_while1,
    character::complete::{char as is_char, multispace0},
    combinator::{map, map_res},
    multi::many0,
    sequence::{delimited, preceded, separated_pair},
    IResult,
};

#[derive(Debug, PartialEq)]
pub struct RawQuery<'a> {
    pub input: &'a str,
    pub is_phrase: bool,
    pub field_name: Option<&'a str>,
    pub modifier: Option<Modifier>,
}

#[derive(Debug, PartialEq)]
pub enum Modifier {
    Mandatory,
    Prohibited,
}

const FIELD_SEP: char = ':';

impl<'a> RawQuery<'a> {
    pub fn new(input: &'a str) -> Self {
        Self {
            input,
            is_phrase: false,
            field_name: None,
            modifier: None,
        }
    }

    pub fn prohibited(mut self) -> Self {
        debug_assert!(self.modifier.is_none());
        self.modifier.replace(Modifier::Prohibited);
        self
    }

    pub fn mandatory(mut self) -> Self {
        debug_assert!(self.modifier.is_none());
        self.modifier.replace(Modifier::Mandatory);
        self
    }

    pub fn phrase(mut self) -> Self {
        debug_assert!(!self.is_phrase);
        self.is_phrase = true;
        self
    }

    pub fn with_field(mut self, name: &'a str) -> Self {
        debug_assert_eq!(None, self.field_name);
        self.field_name = Some(name);
        self
    }
}

pub trait FieldNameValidator {
    fn check(&self, field_name: &str) -> bool;
}

impl<T> FieldNameValidator for Vec<T>
where
    T: for<'a> PartialEq<&'a str>,
{
    fn check(&self, field_name: &str) -> bool {
        self.iter().any(|item| item == &field_name)
    }
}

impl FieldNameValidator for bool {
    fn check(&self, _field_name: &str) -> bool {
        *self
    }
}

pub fn parse_query<'a, C: FieldNameValidator>(
    input: &'a str,
    validator: &'a C,
) -> IResult<&'a str, Vec<RawQuery<'a>>> {
    many0(delimited(
        multispace0,
        alt((
            |input| prohibited_query(input, validator),
            |input| mandatory_query(input, validator),
            |input| field_prefixed_query(input, validator),
            any_field_query,
        )),
        multispace0,
    ))(input)
}

fn prohibited_query<'a, C: FieldNameValidator>(
    input: &'a str,
    validator: &'a C,
) -> IResult<&'a str, RawQuery<'a>> {
    map(
        preceded(
            is_char('-'),
            alt((
                |input| field_prefixed_query(input, validator),
                any_field_query,
            )),
        ),
        |query| query.prohibited(),
    )(input)
}

fn mandatory_query<'a, C: FieldNameValidator>(
    input: &'a str,
    validator: &'a C,
) -> IResult<&'a str, RawQuery<'a>> {
    map(
        preceded(
            is_char('+'),
            alt((
                |input| field_prefixed_query(input, validator),
                any_field_query,
            )),
        ),
        |query| query.mandatory(),
    )(input)
}

fn field_prefixed_query<'a, C: FieldNameValidator>(
    input: &'a str,
    validator: &'a C,
) -> IResult<&'a str, RawQuery<'a>> {
    map_res(
        separated_pair(
            take_while1(|c| c != FIELD_SEP && is_term_char(c)),
            is_char(FIELD_SEP),
            any_field_query,
        ),
        |(name, term)| {
            if validator.check(name) {
                Ok(term.with_field(name))
            } else {
                Err("Invalid field")
            }
        },
    )(input)
}

fn any_field_query(input: &str) -> IResult<&str, RawQuery> {
    alt((parse_phrase, parse_term))(input)
}

fn parse_phrase(input: &str) -> IResult<&str, RawQuery> {
    map(
        delimited(is_char('"'), take_while1(|c| c != '"'), is_char('"')),
        |s| RawQuery::new(s).phrase(),
    )(input)
}

fn parse_term(input: &str) -> IResult<&str, RawQuery> {
    map(take_while1(is_term_char), RawQuery::new)(input)
}

fn is_term_char(c: char) -> bool {
    !(c == ' ' || c == '\t' || c == '\r' || c == '\n')
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_no_fields(input: &str) -> IResult<&str, Vec<RawQuery>> {
        parse_query(input, &false)
    }

    #[test]
    fn term_extraction() {
        assert_eq!(
            parse_no_fields("gula"),
            Ok(("", vec![RawQuery::new("gula")]))
        );
    }

    #[test]
    fn prohibited_term_extraction() {
        assert_eq!(
            parse_no_fields("-ads"),
            Ok(("", vec![RawQuery::new("ads").prohibited()]))
        )
    }

    #[test]
    fn mandatory_term_extraction() {
        assert_eq!(
            parse_no_fields("+love"),
            Ok(("", vec![RawQuery::new("love").mandatory()]))
        )
    }

    #[test]
    fn phrase_extraction() {
        assert_eq!(
            parse_no_fields("\"gula recipes\""),
            Ok(("", vec![RawQuery::new("gula recipes").phrase()]))
        );
    }

    #[test]
    fn prohibited_phrase_extraction() {
        assert_eq!(
            parse_no_fields("-\"ads and tracking\""),
            Ok((
                "",
                vec![RawQuery::new("ads and tracking").prohibited().phrase()]
            ))
        );
    }

    #[test]
    fn mandatory_phrase_extraction() {
        assert_eq!(
            parse_no_fields("+\"great food\""),
            Ok(("", vec![RawQuery::new("great food").mandatory().phrase()]))
        );
    }

    #[test]
    fn parse_query_works() {
        assert_eq!(
            parse_no_fields(" +peanut -\"peanut butter\" -sugar roast"),
            Ok((
                "",
                vec![
                    RawQuery::new("peanut").mandatory(),
                    RawQuery::new("peanut butter").phrase().prohibited(),
                    RawQuery::new("sugar").prohibited(),
                    RawQuery::new("roast")
                ]
            ))
        );
    }

    #[test]
    fn check_field_behavior() {
        let input = "title:banana ingredient:sugar";

        // No field support: fields end up in the term
        assert_eq!(
            parse_query(input, &false),
            Ok((
                "",
                vec![
                    RawQuery::new("title:banana"),
                    RawQuery::new("ingredient:sugar"),
                ]
            ))
        );

        // Any field support: field names are not valitdated at all
        assert_eq!(
            parse_query(input, &true),
            Ok((
                "",
                vec![
                    RawQuery::new("banana").with_field("title"),
                    RawQuery::new("sugar").with_field("ingredient"),
                ]
            ))
        );

        // Strict field support: known fields are identified, unknown
        // ones are part of the term
        assert_eq!(
            parse_query(input, &vec!["ingredient"]),
            Ok((
                "",
                vec![
                    RawQuery::new("title:banana"),
                    RawQuery::new("sugar").with_field("ingredient"),
                ]
            ))
        );
    }

    #[test]
    fn garbage_handling() {
        assert_eq!(
            parse_query("- -field: -\"\" body:\"\"", &true),
            Ok((
                "",
                vec![
                    RawQuery::new("-"),
                    RawQuery::new("field:").prohibited(),
                    RawQuery::new("\"\"").prohibited(),
                    RawQuery::new("\"\"").with_field("body"),
                ]
            ))
        );
    }

    #[test]
    fn parse_term_with_field() {
        assert_eq!(
            parse_query("title:potato:queen +instructions:mash -body:\"how to fail\" ingredient:\"golden peeler\"", &true),
            Ok((
                "",
                vec![
                    RawQuery::new("potato:queen").with_field("title"),
                    RawQuery::new("mash").with_field("instructions").mandatory(),
                    RawQuery::new("how to fail").with_field("body").prohibited().phrase(),
                    RawQuery::new("golden peeler").with_field("ingredient").phrase()
                ]
            ))
        );
    }
}