| 1 | use std::collections::VecDeque; |
| 2 | |
| 3 | use crate::{ |
| 4 | collection::processes::ProcessHarvest, |
| 5 | widgets::query::{ |
| 6 | COMPARISON_LIST, Or, Prefix, QueryOptions, QueryProcessor, QueryResult, error::QueryError, |
| 7 | }, |
| 8 | }; |
| 9 | |
| 10 | /// A node where both the left hand side or the right hand side are considered. |
| 11 | /// Note that the right hand side is optional, as that's how I implemented it a |
| 12 | /// long time ago. |
| 13 | #[derive(Debug)] |
| 14 | pub(super) struct And { |
| 15 | pub(super) lhs: Prefix, |
| 16 | // TODO: Maybe don't need to box rhs? |
| 17 | pub(super) rhs: Option<Box<Prefix>>, |
| 18 | } |
| 19 | |
| 20 | impl And { |
| 21 | pub(super) fn check(&self, process: &ProcessHarvest, is_using_command: bool) -> bool { |
| 22 | if let Some(rhs) = &self.rhs { |
| 23 | self.lhs.check(process, is_using_command) && rhs.check(process, is_using_command) |
| 24 | } else { |
| 25 | self.lhs.check(process, is_using_command) |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | impl QueryProcessor for And { |
| 31 | fn process(query: &mut VecDeque<String>, options: &QueryOptions) -> QueryResult<Self> |
| 32 | where |
| 33 | Self: Sized, |
| 34 | { |
| 35 | const AND_LIST: [&str; 2] = ["and", "&&"]; |
| 36 | |
| 37 | let mut lhs = Prefix::process(query, options)?; |
| 38 | let mut rhs: Option<Box<Prefix>> = None; |
| 39 | |
| 40 | while let Some(queue_top) = query.front() { |
| 41 | let current_lowercase = queue_top.to_lowercase(); |
| 42 | if AND_LIST.contains(¤t_lowercase.as_str()) { |
| 43 | query.pop_front(); |
| 44 | |
| 45 | rhs = Some(Box::new(Prefix::process(query, options)?)); |
| 46 | |
| 47 | if let Some(next_queue_top) = query.front() { |
| 48 | if AND_LIST.contains(&next_queue_top.to_lowercase().as_str()) { |
| 49 | // Must merge LHS and RHS |
| 50 | lhs = Prefix::Or(Box::new(Or { |
| 51 | lhs: And { lhs, rhs }, |
| 52 | rhs: None, |
| 53 | })); |
| 54 | rhs = None; |
| 55 | } else { |
| 56 | break; |
| 57 | } |
| 58 | } else { |
| 59 | break; |
| 60 | } |
| 61 | } else if COMPARISON_LIST.contains(¤t_lowercase.as_str()) { |
| 62 | return Err(QueryError::new("Comparison not valid here")); |
| 63 | } else { |
| 64 | break; |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | Ok(And { lhs, rhs }) |
| 69 | } |
| 70 | } |