Skip to main content

aip_160/
ast.rs

1//! Abstract syntax tree for [AIP-160](https://google.aip.dev/160) filters.
2//!
3//! The types follow the
4//! [AIP-160 EBNF](https://google.aip.dev/assets/misc/ebnf-filtering.txt).
5//! The parser keeps literal values as the text that the caller wrote.
6//! Services decide how to interpret a value, for example as a number, a
7//! boolean, an enum value or a duration, with the helpers on [`Value`].
8
9use std::fmt;
10use std::time::Duration;
11
12/// A parsed filter.
13///
14/// An empty filter is valid in AIP-160 and matches every resource. In that
15/// case [`Filter::expression`] is `None`.
16#[derive(Debug, Clone, PartialEq)]
17pub struct Filter {
18    /// The root expression, or `None` for an empty filter.
19    pub expression: Option<Expression>,
20}
21
22/// A filter expression.
23///
24/// AIP-160 gives `OR` a higher precedence than `AND`, so `a AND b OR c`
25/// is `And([a, Or([b, c])])`.
26#[derive(Debug, Clone, PartialEq)]
27pub enum Expression {
28    /// A conjunction joined by the `AND` keyword: `a AND b AND c`.
29    And(Vec<Expression>),
30    /// Factors separated only by whitespace: `New York Giants`.
31    ///
32    /// Services with exact-match semantics treat a sequence as `AND`.
33    /// Services with fuzzy-match semantics may rank results instead.
34    Sequence(Vec<Expression>),
35    /// A disjunction: `a OR b OR c`.
36    Or(Vec<Expression>),
37    /// A negation written as `NOT a` or `-a`.
38    Not(Box<Expression>),
39    /// A comparison such as `a = b` or `labels:env`.
40    Restriction(Restriction),
41    /// A comparable without a comparator, for example `prod`.
42    ///
43    /// AIP-160 calls this a global restriction. Services usually treat it
44    /// as a free-text search.
45    Global(Comparable),
46}
47
48/// A comparison between a comparable and an argument.
49#[derive(Debug, Clone, PartialEq)]
50pub struct Restriction {
51    /// The left side, usually a field path.
52    pub comparable: Comparable,
53    /// The comparison operator.
54    pub comparator: Comparator,
55    /// The right side.
56    pub arg: Arg,
57}
58
59/// The comparison operators of AIP-160.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub enum Comparator {
62    /// `=`
63    Equal,
64    /// `!=`
65    NotEqual,
66    /// `>`
67    GreaterThan,
68    /// `>=`
69    GreaterThanOrEqual,
70    /// `<`
71    LessThan,
72    /// `<=`
73    LessThanOrEqual,
74    /// `:`, the "has" operator.
75    Has,
76}
77
78/// The left side of a restriction, or a function argument.
79#[derive(Debug, Clone, PartialEq)]
80pub enum Comparable {
81    /// A value or a field path such as `a.b.c`.
82    Member(Member),
83    /// A function call such as `regex(m.key, "^prod")`.
84    Function(Function),
85}
86
87/// A value followed by zero or more `.`-separated fields.
88///
89/// `expr.type_map.1.type` has the value `expr` and the fields `type_map`,
90/// `1` and `type`. A bare literal such as `42` is a member without fields.
91#[derive(Debug, Clone, PartialEq)]
92pub struct Member {
93    /// The first segment.
94    pub value: Value,
95    /// The segments after each `.`.
96    pub fields: Vec<Value>,
97}
98
99/// A function call.
100#[derive(Debug, Clone, PartialEq)]
101pub struct Function {
102    /// The name segments: `math.mem` is `["math", "mem"]`.
103    pub name: Vec<String>,
104    /// The arguments in order.
105    pub args: Vec<Arg>,
106}
107
108/// The right side of a restriction, or a function argument.
109#[derive(Debug, Clone, PartialEq)]
110pub enum Arg {
111    /// A value, field path or function call.
112    Comparable(Comparable),
113    /// A parenthesized expression.
114    Composite(Box<Expression>),
115}
116
117/// A literal segment.
118#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub enum Value {
120    /// Unquoted text such as `ACTIVE`, `42`, `2.5`, `true` or `20s`.
121    Text(String),
122    /// A quoted string with its escape sequences resolved.
123    String(String),
124}
125
126/// How a quoted string matches, based on a leading or trailing `*`.
127///
128/// AIP-160 allows a `*` wildcard at the start or the end of a quoted
129/// string in a restriction.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum StringMatch<'a> {
132    /// No wildcard: `"abc"`.
133    Exact(&'a str),
134    /// A trailing wildcard: `"abc*"`.
135    Prefix(&'a str),
136    /// A leading wildcard: `"*abc"`.
137    Suffix(&'a str),
138    /// Wildcards on both sides: `"*abc*"`.
139    Contains(&'a str),
140}
141
142impl Filter {
143    /// Returns `true` when the filter is empty and matches every resource.
144    pub fn is_empty(&self) -> bool {
145        self.expression.is_none()
146    }
147}
148
149impl Comparable {
150    /// Returns the member when this comparable is not a function call.
151    pub fn as_member(&self) -> Option<&Member> {
152        match self {
153            Comparable::Member(member) => Some(member),
154            Comparable::Function(_) => None,
155        }
156    }
157
158    /// Returns the field path when this comparable is a member whose
159    /// segments are all unquoted, for example `labels.env`.
160    pub fn field_path(&self) -> Option<String> {
161        self.as_member().and_then(Member::field_path)
162    }
163}
164
165impl Member {
166    /// Returns `true` when the member has no `.` fields.
167    pub fn is_simple(&self) -> bool {
168        self.fields.is_empty()
169    }
170
171    /// Returns the `.`-joined path when every segment is unquoted text.
172    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    /// Returns the literal value when the argument is a member without
189    /// fields, such as `42`, `ACTIVE` or `"abc"`.
190    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    /// Returns the text of the value, quoted or not.
202    pub fn as_str(&self) -> &str {
203        match self {
204            Value::Text(text) | Value::String(text) => text,
205        }
206    }
207
208    /// Returns `true` for a quoted string.
209    pub fn is_quoted(&self) -> bool {
210        matches!(self, Value::String(_))
211    }
212
213    /// Interprets unquoted `true` or `false` as a boolean.
214    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    /// Interprets unquoted text as a signed integer.
223    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    /// Interprets unquoted text as an unsigned integer.
231    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    /// Interprets unquoted text as a floating-point number.
239    ///
240    /// Only finite numbers in decimal or exponent notation are accepted, so
241    /// `inf` and `NaN` return `None`.
242    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    /// Returns `true` for unquoted `null`.
252    pub fn is_null(&self) -> bool {
253        matches!(self, Value::Text(text) if text == "null")
254    }
255
256    /// Interprets unquoted text such as `20s` or `1.5s` as a duration.
257    ///
258    /// AIP-160 writes durations as a number of seconds followed by `s`.
259    /// Negative durations return `None`.
260    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    /// Returns how a quoted string matches, based on its `*` wildcards.
272    ///
273    /// Returns `None` for unquoted text. A string that is only `*` or `**`
274    /// matches everything and returns `Contains("")`.
275    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
294/// Returns `true` for `[-]digits[.digits][(e|E)[+|-]digits]`.
295fn 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/// Precedence levels used to decide where `Display` needs parentheses.
394#[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    /// Writes `self` as a child that must bind tighter than `parent`.
413    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    /// Writes the expression in AIP-160 syntax. Parsing the output yields an
439    /// equal expression.
440    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}