tantivy_query_grammar/
lib.rs1#![allow(clippy::derive_partial_eq_without_eq)]
2
3use serde::Serialize;
4
5mod infallible;
6mod occur;
7mod query_grammar;
8mod user_input_ast;
9
10pub use crate::infallible::LenientError;
11pub use crate::occur::Occur;
12use crate::query_grammar::{parse_to_ast, parse_to_ast_lenient};
13pub use crate::user_input_ast::{
14 Delimiter, UserInputAst, UserInputBound, UserInputLeaf, UserInputLiteral,
15};
16
17#[derive(Debug, Serialize)]
18#[serde(rename_all = "snake_case")]
19pub struct Error;
20
21pub fn parse_query(query: &str) -> Result<UserInputAst, Error> {
23 let (_remaining, user_input_ast) = parse_to_ast(query).map_err(|_| Error)?;
24 Ok(user_input_ast)
25}
26
27pub fn parse_query_lenient(query: &str) -> (UserInputAst, Vec<LenientError>) {
29 parse_to_ast_lenient(query)
30}
31
32#[cfg(test)]
33mod tests {
34 use crate::{UserInputAst, parse_query, parse_query_lenient};
35
36 #[test]
37 fn test_deduplication() {
38 let ast: UserInputAst = parse_query("a a").unwrap();
39 let json = serde_json::to_string(&ast).unwrap();
40 assert_eq!(
41 json,
42 r#"{"type":"bool","clauses":[[null,{"type":"literal","field_name":null,"phrase":"a","delimiter":"none","slop":0,"prefix":false}]]}"#
43 );
44 }
45
46 #[test]
47 fn test_parse_query_serialization() {
48 let ast = parse_query("title:hello OR title:x").unwrap();
49 let json = serde_json::to_string(&ast).unwrap();
50 assert_eq!(
51 json,
52 r#"{"type":"bool","clauses":[["should",{"type":"literal","field_name":"title","phrase":"hello","delimiter":"none","slop":0,"prefix":false}],["should",{"type":"literal","field_name":"title","phrase":"x","delimiter":"none","slop":0,"prefix":false}]]}"#
53 );
54 }
55
56 #[test]
57 fn test_parse_query_wrong_query() {
58 assert!(parse_query("title:").is_err());
59 }
60
61 #[test]
62 fn test_parse_query_lenient_wrong_query() {
63 let (_, errors) = parse_query_lenient("title:");
64 assert!(errors.len() == 1);
65 let json = serde_json::to_string(&errors).unwrap();
66 assert_eq!(json, r#"[{"pos":6,"message":"expected word"}]"#);
67 }
68}