aqp3 0.1.0

Congress.gov legislation text query syntax parser.
Documentation
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use crate::parser::query;
use itertools::Itertools;
use std::fmt;
use winnow::{Parser, Result};

/// Represents a query in the legislation text search syntax
/// documented on the [Congress.gov Search Tools page](https://www.congress.gov/help/search-tools-overview)
/// under "Search Operators for Legislation Text." A query is represented as a
/// list of terms.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Query<'src>(pub Vec<Term<'src>>);

/// Represents a term in query.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Term<'src> {
    /// A simple term with no operator applied.
    Bare(&'src str),
    /// A term followed by `*`, representing a wildcard term.
    Wildcard(&'src str),
    /// A phrase, i.e., a string surrounded by double quotes.
    Phrase(&'src str),
    /// A literal phrase, i.e., a string surrounded by single quotes.
    Literal(&'src str),
    /// A negated term, i.e., a bare, wildcard, phrase, or literal term
    /// preceded by `!`
    Not(Box<Term<'src>>),
    /// A "SHOULD" term. Can be a single bare, wildcard, phrase, or literal term
    /// or a group of terms delimited by parentheses preceded by `~`.
    Should(Vec<Term<'src>>),
    /// A "MUST" term. Can be a single bare, wildcard, phrase, or literal term
    /// or a group of terms delimited by parentheses preceded by `+`.
    Must(Vec<Term<'src>>),
    /// A proximity query of the form `n/x(a b)` where `x` is a number and
    /// `a` and `b` are terms. This represents an unordered proximity query.
    Near(u8, Vec<Term<'src>>),
    /// A proximity query of the form `w/x(a b)` where `x` is a number and
    /// `a` and `b` are terms. This represents an ordered proximity query.
    Within(u8, Vec<Term<'src>>),
    /// One or more terms surrounded by parentheses.
    Grouped(Vec<Term<'src>>),
}

impl<'src> Query<'src> {
    /// Parse a query.
    ///
    /// # Example usage
    ///
    /// ```rust
    /// use aqp3::Query;
    ///
    /// let mut query = "N/10(~(pizz* past*) ~(tomat* mozzarell* arancin* crust))";
    /// let result = Query::parse(&mut query);
    /// ```
    ///
    /// The above results in:
    /// ```rust
    /// use aqp3::{Query, Term};
    ///
    /// let expected = Query(vec![Term::Near(
    ///     10,
    ///     vec![
    ///         Term::Should(vec![Term::Wildcard("pizz"), Term::Wildcard("past")]),
    ///         Term::Should(vec![
    ///             Term::Wildcard("tomat"),
    ///             Term::Wildcard("mozzarell"),
    ///             Term::Wildcard("arancin"),
    ///             Term::Bare("crust"),
    ///         ]),
    ///     ],
    /// )]);
    /// ```
    ///
    /// # Errors
    ///
    /// Will result in an error on invalid syntax, i.e., syntax that does not
    /// conform to the query language's grammar.
    pub fn parse(input: &mut &'src str) -> Result<Query<'src>> {
        query.parse_next(input)
    }

    #[must_use]
    /// Simplifies a query.
    ///
    /// [Congress.gov](https://www.congress.gov)'s legislation text search form
    /// uses `and` as its default operator, so the "MUST" operator (`+`) is not
    /// needed in a query. This method removes it from a query.
    ///
    /// In a top level query, i.e., a query outside of parentheses, the "SHOULD"
    /// operator is distributive, i.e., `~a ~b == ~(a b)`. This method converts
    /// a list of consecutive single-term SHOULDs to a grouped SHOULD.
    ///
    /// Extraneous parentheses are automatically removed when a query is parsed,
    ///
    /// Calling this method removes redundant terms.
    pub fn simplify(&self) -> Query<'src> {
        let terms = self.0.clone();
        if terms.iter().all(|t| matches!(t, Term::Should(_))) {
            if terms.len() == 1 {
                if let Term::Should(ts) = &terms[0]
                    && ts.len() == 1
                {
                    return Query(ts.clone());
                }
                return self.to_owned();
            }
            return Query(vec![Term::Should(
                terms
                    .iter()
                    .map(Term::lift)
                    .map(Term::simplify)
                    .unique()
                    .collect(),
            )]);
        }
        let simplified: Vec<_> = terms.into_iter().map(Term::simplify).unique().collect();
        if simplified.len() == 1 {
            return match &simplified[0] {
                Term::Grouped(ts) => Query(ts.iter().cloned().unique().collect()).simplify(),
                Term::Should(_) => Query(simplified).simplify(),
                _ => Query(simplified),
            };
        }

        Query(simplified)
    }
}

impl<'src> Term<'src> {
    fn simplify(self) -> Term<'src> {
        match self {
            Term::Must(ts) | Term::Grouped(ts) => {
                if ts.len() == 1 {
                    ts[0].clone().simplify()
                } else {
                    Term::Grouped(ts.into_iter().map(Term::simplify).collect())
                }
            }
            _ => self.clone(),
        }
    }

    fn lift(&self) -> Term<'src> {
        match self {
            Term::Should(ts) | Term::Must(ts) => {
                Term::Grouped(ts.iter().cloned().unique().collect())
            }
            _ => self.to_owned(),
        }
    }
}

impl fmt::Display for Query<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let output = self
            .0
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<String>>()
            .join(" ");

        write!(f, "{output}")
    }
}

impl fmt::Display for Term<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let query_list = |qs: &Vec<Term>| {
            qs.iter()
                .map(ToString::to_string)
                .collect::<Vec<String>>()
                .join(" ")
        };

        let format_boolean = |op: char, queries: &Vec<Term>| {
            if queries.len() == 1 {
                format!("{op}{}", queries[0])
            } else {
                format!("{op}({})", query_list(queries))
            }
        };

        let output = match self {
            Self::Bare(s) => (*s).to_string(),
            Self::Wildcard(s) => format!("{s}*"),
            Self::Literal(s) => format!("'{s}'"),
            Self::Phrase(s) => format!("\"{s}\""),
            Self::Not(q) => format!("!{q}"),
            Self::Should(queries) => format_boolean('~', queries),
            Self::Must(queries) => format_boolean('+', queries),
            Self::Near(slop, queries) => {
                format!("n/{slop}({})", query_list(queries))
            }
            Self::Within(slop, queries) => {
                format!("w/{slop}({})", query_list(queries))
            }
            Self::Grouped(queries) => format!("({})", query_list(queries)),
        };
        write!(f, "{output}")
    }
}

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

    #[test]
    fn bare_to_string() {
        let q = Query(vec![Term::Bare("hello")]);
        let result = q.to_string();
        assert_eq!(result, "hello");
    }

    #[test]
    fn wildcard_to_string() {
        let q = Query(vec![Term::Wildcard("hello")]);
        let result = q.to_string();
        assert_eq!(result, "hello*");
    }

    #[test]
    fn phrase_to_string() {
        let q = Query(vec![Term::Phrase("hello world")]);
        let result = q.to_string();
        assert_eq!(result, "\"hello world\"");
    }

    #[test]
    fn literal_to_string() {
        let q = Query(vec![Term::Literal("hello world")]);
        let result = q.to_string();
        assert_eq!(result, "'hello world'");
    }

    #[test]
    fn not_to_string() {
        let q = Query(vec![Term::Not(Box::new(Term::Bare("pizza")))]);
        let result = q.to_string();
        assert_eq!(result, "!pizza");
    }

    #[test]
    fn not_phrase_to_string() {
        let q = Query(vec![Term::Not(Box::new(Term::Phrase("pizza time")))]);
        let result = q.to_string();
        assert_eq!(result, "!\"pizza time\"");
    }

    #[test]
    fn nested_to_string() {
        let query = Query(vec![Term::Should(vec![
            Term::Near(
                20,
                vec![
                    Term::Phrase("dogs and cats"),
                    Term::Should(vec![Term::Phrase("rats"), Term::Phrase("mice")]),
                ],
            ),
            Term::Near(
                20,
                vec![
                    Term::Phrase("dogs and cats"),
                    Term::Should(vec![Term::Phrase("rats"), Term::Phrase("mice")]),
                ],
            ),
        ])]);

        let result = query.to_string();
        let expected =
            r#"~(n/20("dogs and cats" ~("rats" "mice")) n/20("dogs and cats" ~("rats" "mice")))"#;

        assert_eq!(result, expected);
    }

    #[test]
    fn multi_mixed_proximity_phrase_extraneous_parens() {
        let mut input = r#"~((n/20("dogs and cats" ~("rats" "mice"))) (n/20("dogs and cats" ~("rats" "mice"))))"#;
        let query = Query::parse(&mut input).unwrap();
        let result = query.to_string();
        let expected =
            r#"~(n/20("dogs and cats" ~("rats" "mice")) n/20("dogs and cats" ~("rats" "mice")))"#;

        assert_eq!(result, expected);
    }

    #[test]
    fn bare_terms() {
        let mut input = "elementary secondary";
        let query = Query::parse(&mut input).unwrap();
        let result = query.to_string();
        let expected = "elementary secondary";

        assert_eq!(result, expected);
    }

    #[test]
    fn must_list() {
        let mut input = "+elementary +secondary";
        let query = Query::parse(&mut input).unwrap();
        let result = query.to_string();
        let expected = "+elementary +secondary";

        assert_eq!(result, expected);
    }

    #[test]
    fn must_group() {
        let mut input = "+(elementary secondary)";
        let query = Query::parse(&mut input).unwrap();
        let result = query.to_string();
        let expected = "+(elementary secondary)";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_single_top_level_must() {
        let mut input = "+elementary";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "elementary";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_top_level_must_list() {
        let mut input = "+elementary +secondary";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "elementary secondary";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_top_level_must_group() {
        let mut input = "+(elementary secondary)";
        let query = Query::parse(&mut input).unwrap().simplify();
        let result = query.simplify().to_string();
        let expected = "elementary secondary";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_top_level_should_list() {
        let mut input = "~elementary ~secondary";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "~(elementary secondary)";

        assert_eq!(result, expected);
    }

    #[test]
    fn remove_redundant_term() {
        let mut input = "a b a";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "a b";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_redundant_term_with_should() {
        let mut input = "a ~b a";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "a ~b";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_redundant_term_with_leading_should() {
        let mut input = "~b a a";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "~b a";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_removes_redundant_shoulds() {
        let mut input = "~b a ~b";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "~b a";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_removes_and_simplifies_redundant_musts() {
        let mut input = "+b a +b";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "b a";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_removes_extraneous_should() {
        let mut input = "~a";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "a";

        assert_eq!(result, expected);
    }

    #[test]
    fn should_with_nested_parens_to_string() {
        let mut input = "~((dogs cats))";
        let query = Query::parse(&mut input).unwrap();
        let result = query.to_string();

        assert_eq!(result, "~(dogs cats)");
    }

    #[test]
    fn simplify_should_with_nested_parens_to_string() {
        let mut input = "~((dogs cats))";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();

        assert_eq!(result, "~(dogs cats)");
    }

    #[test]
    fn should_with_multi_nested_parens_to_string() {
        let mut input = "~((dogs cats) (rats mice))";
        let query = Query::parse(&mut input).unwrap();
        let result = query.to_string();

        assert_eq!(result, "~(dogs cats rats mice)");
    }

    #[test]
    fn simplify_should_with_multi_nested_parens_to_string() {
        let mut input = "~((dogs cats) (rats mice))";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();

        assert_eq!(result, "~(dogs cats rats mice)");
    }

    #[test]
    fn simplify_removes_extraneous_should_with_parens() {
        let mut input = "~(a)";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "a";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_removes_extraneous_parens_with_should() {
        let mut input = "(~a)";
        let query = Query::parse(&mut input).unwrap();
        let result = query.simplify().to_string();
        let expected = "a";

        assert_eq!(result, expected);
    }

    #[test]
    fn simplify_extraneous_parens_with_should() {
        let mut input = "(~a)";
        let result = Query::parse(&mut input).unwrap().simplify();
        let expected = Query(vec![Term::Bare("a")]);

        assert_eq!(result, expected);
    }
}