1use std::fmt;
10use std::time::Duration;
11
12#[derive(Debug, Clone, PartialEq)]
17pub struct Filter {
18 pub expression: Option<Expression>,
20}
21
22#[derive(Debug, Clone, PartialEq)]
27pub enum Expression {
28 And(Vec<Expression>),
30 Sequence(Vec<Expression>),
35 Or(Vec<Expression>),
37 Not(Box<Expression>),
39 Restriction(Restriction),
41 Global(Comparable),
46}
47
48#[derive(Debug, Clone, PartialEq)]
50pub struct Restriction {
51 pub comparable: Comparable,
53 pub comparator: Comparator,
55 pub arg: Arg,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub enum Comparator {
62 Equal,
64 NotEqual,
66 GreaterThan,
68 GreaterThanOrEqual,
70 LessThan,
72 LessThanOrEqual,
74 Has,
76}
77
78#[derive(Debug, Clone, PartialEq)]
80pub enum Comparable {
81 Member(Member),
83 Function(Function),
85}
86
87#[derive(Debug, Clone, PartialEq)]
92pub struct Member {
93 pub value: Value,
95 pub fields: Vec<Value>,
97}
98
99#[derive(Debug, Clone, PartialEq)]
101pub struct Function {
102 pub name: Vec<String>,
104 pub args: Vec<Arg>,
106}
107
108#[derive(Debug, Clone, PartialEq)]
110pub enum Arg {
111 Comparable(Comparable),
113 Composite(Box<Expression>),
115}
116
117#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub enum Value {
120 Text(String),
122 String(String),
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum StringMatch<'a> {
132 Exact(&'a str),
134 Prefix(&'a str),
136 Suffix(&'a str),
138 Contains(&'a str),
140}
141
142impl Filter {
143 pub fn is_empty(&self) -> bool {
145 self.expression.is_none()
146 }
147}
148
149impl Comparable {
150 pub fn as_member(&self) -> Option<&Member> {
152 match self {
153 Comparable::Member(member) => Some(member),
154 Comparable::Function(_) => None,
155 }
156 }
157
158 pub fn field_path(&self) -> Option<String> {
161 self.as_member().and_then(Member::field_path)
162 }
163}
164
165impl Member {
166 pub fn is_simple(&self) -> bool {
168 self.fields.is_empty()
169 }
170
171 pub fn field_path(&self) -> Option<String> {
173 let mut path = String::new();
174 for (index, segment) in std::iter::once(&self.value).chain(&self.fields).enumerate() {
175 let Value::Text(text) = segment else {
176 return None;
177 };
178 if index > 0 {
179 path.push('.');
180 }
181 path.push_str(text);
182 }
183 Some(path)
184 }
185}
186
187impl Arg {
188 pub fn as_value(&self) -> Option<&Value> {
191 match self {
192 Arg::Comparable(Comparable::Member(member)) if member.is_simple() => {
193 Some(&member.value)
194 }
195 _ => None,
196 }
197 }
198}
199
200impl Value {
201 pub fn as_str(&self) -> &str {
203 match self {
204 Value::Text(text) | Value::String(text) => text,
205 }
206 }
207
208 pub fn is_quoted(&self) -> bool {
210 matches!(self, Value::String(_))
211 }
212
213 pub fn as_bool(&self) -> Option<bool> {
215 match self {
216 Value::Text(text) if text == "true" => Some(true),
217 Value::Text(text) if text == "false" => Some(false),
218 _ => None,
219 }
220 }
221
222 pub fn as_i64(&self) -> Option<i64> {
224 match self {
225 Value::Text(text) => text.parse().ok(),
226 Value::String(_) => None,
227 }
228 }
229
230 pub fn as_u64(&self) -> Option<u64> {
232 match self {
233 Value::Text(text) => text.parse().ok(),
234 Value::String(_) => None,
235 }
236 }
237
238 pub fn as_f64(&self) -> Option<f64> {
243 match self {
244 Value::Text(text) if is_decimal_number(text) => {
245 text.parse().ok().filter(|n: &f64| n.is_finite())
246 }
247 _ => None,
248 }
249 }
250
251 pub fn is_null(&self) -> bool {
253 matches!(self, Value::Text(text) if text == "null")
254 }
255
256 pub fn as_duration(&self) -> Option<Duration> {
261 let Value::Text(text) = self else {
262 return None;
263 };
264 let seconds = text.strip_suffix('s')?;
265 if !is_decimal_number(seconds) || seconds.starts_with('-') {
266 return None;
267 }
268 Duration::try_from_secs_f64(seconds.parse().ok()?).ok()
269 }
270
271 pub fn string_match(&self) -> Option<StringMatch<'_>> {
276 let Value::String(text) = self else {
277 return None;
278 };
279 let leading = text.starts_with('*');
280 let trailing = text.len() > usize::from(leading) && text.ends_with('*');
281 let start = usize::from(leading);
282 let end = text.len() - usize::from(trailing);
283 let core = &text[start..end.max(start)];
284 Some(match (leading, trailing) {
285 (false, false) => StringMatch::Exact(core),
286 (false, true) => StringMatch::Prefix(core),
287 (true, false) if core.is_empty() => StringMatch::Contains(core),
288 (true, false) => StringMatch::Suffix(core),
289 (true, true) => StringMatch::Contains(core),
290 })
291 }
292}
293
294fn is_decimal_number(text: &str) -> bool {
296 let unsigned = text.strip_prefix('-').unwrap_or(text);
297 let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
298 Some(index) => (&unsigned[..index], Some(&unsigned[index + 1..])),
299 None => (unsigned, None),
300 };
301 let (integer, fraction) = match mantissa.split_once('.') {
302 Some((integer, fraction)) => (integer, Some(fraction)),
303 None => (mantissa, None),
304 };
305 let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
306 let exponent_ok = exponent.is_none_or(|e| digits(e.strip_prefix(['+', '-']).unwrap_or(e)));
307 digits(integer) && fraction.is_none_or(digits) && exponent_ok
308}
309
310impl fmt::Display for Comparator {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 f.write_str(match self {
313 Comparator::Equal => "=",
314 Comparator::NotEqual => "!=",
315 Comparator::GreaterThan => ">",
316 Comparator::GreaterThanOrEqual => ">=",
317 Comparator::LessThan => "<",
318 Comparator::LessThanOrEqual => "<=",
319 Comparator::Has => ":",
320 })
321 }
322}
323
324impl fmt::Display for Value {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 match self {
327 Value::Text(text) => f.write_str(text),
328 Value::String(text) => {
329 f.write_str("\"")?;
330 for c in text.chars() {
331 match c {
332 '"' => f.write_str("\\\"")?,
333 '\\' => f.write_str("\\\\")?,
334 '\n' => f.write_str("\\n")?,
335 '\r' => f.write_str("\\r")?,
336 '\t' => f.write_str("\\t")?,
337 c => write!(f, "{c}")?,
338 }
339 }
340 f.write_str("\"")
341 }
342 }
343 }
344}
345
346impl fmt::Display for Member {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 write!(f, "{}", self.value)?;
349 for field in &self.fields {
350 write!(f, ".{field}")?;
351 }
352 Ok(())
353 }
354}
355
356impl fmt::Display for Function {
357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358 write!(f, "{}(", self.name.join("."))?;
359 for (index, arg) in self.args.iter().enumerate() {
360 if index > 0 {
361 f.write_str(", ")?;
362 }
363 write!(f, "{arg}")?;
364 }
365 f.write_str(")")
366 }
367}
368
369impl fmt::Display for Comparable {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 match self {
372 Comparable::Member(member) => write!(f, "{member}"),
373 Comparable::Function(function) => write!(f, "{function}"),
374 }
375 }
376}
377
378impl fmt::Display for Arg {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 match self {
381 Arg::Comparable(comparable) => write!(f, "{comparable}"),
382 Arg::Composite(expression) => write!(f, "({expression})"),
383 }
384 }
385}
386
387impl fmt::Display for Restriction {
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 write!(f, "{} {} {}", self.comparable, self.comparator, self.arg)
390 }
391}
392
393#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
395enum Level {
396 And,
397 Sequence,
398 Or,
399 Term,
400}
401
402impl Expression {
403 fn level(&self) -> Level {
404 match self {
405 Expression::And(_) => Level::And,
406 Expression::Sequence(_) => Level::Sequence,
407 Expression::Or(_) => Level::Or,
408 Expression::Not(_) | Expression::Restriction(_) | Expression::Global(_) => Level::Term,
409 }
410 }
411
412 fn fmt_child(&self, f: &mut fmt::Formatter<'_>, parent: Level) -> fmt::Result {
414 if self.level() > parent {
415 write!(f, "{self}")
416 } else {
417 write!(f, "({self})")
418 }
419 }
420
421 fn fmt_joined(
422 f: &mut fmt::Formatter<'_>,
423 children: &[Expression],
424 separator: &str,
425 level: Level,
426 ) -> fmt::Result {
427 for (index, child) in children.iter().enumerate() {
428 if index > 0 {
429 f.write_str(separator)?;
430 }
431 child.fmt_child(f, level)?;
432 }
433 Ok(())
434 }
435}
436
437impl fmt::Display for Expression {
438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 match self {
442 Expression::And(children) => Self::fmt_joined(f, children, " AND ", Level::And),
443 Expression::Sequence(children) => Self::fmt_joined(f, children, " ", Level::Sequence),
444 Expression::Or(children) => Self::fmt_joined(f, children, " OR ", Level::Or),
445 Expression::Not(inner) => match inner.as_ref() {
446 Expression::Restriction(_) | Expression::Global(_) => write!(f, "NOT {inner}"),
447 _ => write!(f, "NOT ({inner})"),
448 },
449 Expression::Restriction(restriction) => write!(f, "{restriction}"),
450 Expression::Global(comparable) => write!(f, "{comparable}"),
451 }
452 }
453}
454
455impl fmt::Display for Filter {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 match &self.expression {
458 Some(expression) => write!(f, "{expression}"),
459 None => Ok(()),
460 }
461 }
462}