Skip to main content

mln_style/
filter.rs

1use std::hash::Hasher;
2use std::sync::{Arc, OnceLock};
3
4use crate::conversion::{Convertible, Error};
5use crate::expression::{
6    Dependency, EvaluationContext, Expr, Functions, ParsingContext, Type, Value as ExpressionValue,
7    feature_property_keys,
8};
9use crate::feature::Value;
10use crate::property::function::{conversion_errors, get, literal, matchable, number, op, owned};
11use crate::wire::optional_expression;
12
13#[derive(Clone, Debug, Default, mln_wire::Wire)]
14pub struct Filter {
15    #[wire(with = "optional_expression")]
16    pub expression: Option<Arc<Expr>>,
17    legacy_filter: Option<Value>,
18    /// [`Filter::property_keys`], found on first use.
19    #[wire(skip)]
20    property_keys: OnceLock<Option<Box<[String]>>>,
21    /// [`Filter::expression_hash`], found on first use.
22    #[wire(skip)]
23    expression_hash: OnceLock<u64>,
24    /// The hash of [`Filter::equality`]'s operand, found on first use.
25    #[wire(skip)]
26    operand_hash: OnceLock<Option<u64>>,
27}
28
29/// A filter that holds where an operand equals a literal
30/// ([`Filter::equality`]).
31pub struct Equality<'a> {
32    pub operand: &'a Expr,
33    pub value: &'a ExpressionValue,
34    /// A hash of the operand's structure, alike for equal operands.
35    pub operand_hash: u64,
36}
37
38impl Filter {
39    #[must_use]
40    pub fn new(expression: Option<Arc<Expr>>, legacy_filter: Option<Value>) -> Self {
41        Filter {
42            expression,
43            legacy_filter,
44            property_keys: OnceLock::new(),
45            expression_hash: OnceLock::new(),
46            operand_hash: OnceLock::new(),
47        }
48    }
49
50    pub(crate) fn is_set(&self) -> bool {
51        self.expression.is_some() || self.legacy_filter.is_some()
52    }
53
54    pub fn evaluate(&self, context: &EvaluationContext<'_>) -> bool {
55        let Some(expression) = &self.expression else {
56            return true;
57        };
58
59        expression.eval_bool(context).unwrap_or(false)
60    }
61
62    /// The property keys the filter reads, sorted, if they and
63    /// the geometry type are all it reads of a feature
64    /// ([`feature_property_keys`]). The filter then selects features with
65    /// the same geometry type and the same values under those keys alike.
66    /// `None` without an expression.
67    pub fn property_keys(&self) -> Option<&[String]> {
68        let keys = self.property_keys.get_or_init(|| {
69            let expression = self.expression.as_ref()?;
70            feature_property_keys(expression).map(Vec::into_boxed_slice)
71        });
72        keys.as_deref()
73    }
74
75    /// A hash of the expression's structure
76    /// ([`Expr::hash_structure`]), so that filters whose expressions
77    /// are equal hash alike, whether or not they share them.
78    pub fn expression_hash(&self) -> u64 {
79        *self.expression_hash.get_or_init(|| {
80            let mut state = std::hash::DefaultHasher::new();
81            if let Some(expression) = &self.expression {
82                expression.hash_structure(&mut state);
83            }
84            state.finish()
85        })
86    }
87
88    /// The operand and literal of a filter `["==", operand,
89    /// literal]`, which selects the features whose operand evaluates to a
90    /// value equal to the literal. Filters over one source layer that
91    /// compare the same operand can then share its value for each feature.
92    pub fn equality(&self) -> Option<Equality<'_>> {
93        let (operand, value) = self.expression.as_ref()?.as_equality()?;
94        let operand_hash = (*self.operand_hash.get_or_init(|| {
95            let mut state = std::hash::DefaultHasher::new();
96            operand.hash_structure(&mut state);
97            Some(state.finish())
98        }))?;
99        Some(Equality { operand, value, operand_hash })
100    }
101
102    pub(crate) fn serialize(&self) -> Value {
103        if let Some(legacy_filter) = &self.legacy_filter {
104            legacy_filter.clone()
105        } else if let Some(expression) = &self.expression {
106            Expr::serialize(expression)
107        } else {
108            Value::Null
109        }
110    }
111}
112
113impl PartialEq for Filter {
114    /// Two filters are equal when their expressions are, whether or not
115    /// they share them.
116    fn eq(&self, other: &Self) -> bool {
117        match (&self.expression, &other.expression) {
118            (Some(a), Some(b)) => Arc::ptr_eq(a, b) || **a == **b,
119            (None, None) => true,
120            _ => false,
121        }
122    }
123}
124
125/// Converts a filter: an expression, which parses against `functions`, or a
126/// legacy filter, which becomes the expression it stands for.
127pub fn convert_filter(value: &Convertible<'_>, functions: &Arc<Functions>, error: &mut Error) -> Option<Filter> {
128    let legacy = if is_expression(value) { None } else { Some(legacy_filter_expression(value, error)?) };
129    let mut parsing_context = ParsingContext::with_expected(functions, Type::Boolean);
130    let parsed = match &legacy {
131        Some(legacy) => parsing_context.parse_expression(&Convertible::from(legacy), None),
132        None => parsing_context.parse_expression(value, None),
133    };
134    let Some(parsed) = parsed else {
135        error.message =
136            if legacy.is_some() { conversion_errors(&parsing_context) } else { parsing_context.combined_errors() };
137        return None;
138    };
139    if parsed.has(Dependency::CAMERA) {
140        error.message = "camera expressions not supported in filters".to_owned();
141        return None;
142    }
143    let legacy_filter = legacy.is_some().then(|| owned(value)).filter(|_| !value.is_undefined());
144    Some(Filter::new(Some(Arc::new(parsed)), legacy_filter))
145}
146
147/// Which of the two filter syntaxes a filter belongs to, as the style
148/// specification classifies them.
149#[derive(Clone, Copy, PartialEq, Eq)]
150enum Syntax {
151    /// Valid only as an expression, such as `["==", ["get", "x"], 1]`.
152    Expression,
153    /// Valid only as a legacy filter, such as `["!in", "x", 1]`.
154    Legacy,
155    /// Valid as both with the same meaning, such as `true` or
156    /// `["has", "x"]`, so no evidence of either.
157    Neutral,
158}
159
160fn is_expression(filter: &Convertible<'_>) -> bool {
161    classify(filter) != Syntax::Legacy
162}
163
164fn classify(filter: &Convertible<'_>) -> Syntax {
165    if filter.to_bool().is_some() {
166        return Syntax::Neutral;
167    }
168    if !filter.is_array() || filter.array_length() == 0 {
169        return Syntax::Legacy;
170    }
171    let Some(op) = filter.array_member(0).to_string() else {
172        return Syntax::Expression;
173    };
174    let expression_if = |is_expression: bool| if is_expression { Syntax::Expression } else { Syntax::Legacy };
175    match op.as_str() {
176        "has" => match filter.array_member(1).to_string().as_deref() {
177            _ if filter.array_length() < 2 => Syntax::Legacy,
178            Some("$id" | "$type") => Syntax::Legacy,
179            _ if filter.array_length() == 2 => Syntax::Neutral,
180            _ => Syntax::Expression,
181        },
182        // Legacy `in` tests a property against a set of values, the `in`
183        // expression for a substring, so the scalar form stays legacy.
184        "in" => expression_if(
185            filter.array_length() >= 3
186                && (filter.array_member(1).to_string().is_none() || filter.array_member(2).is_array()),
187        ),
188        "!in" | "!has" | "none" => Syntax::Legacy,
189        "==" | "!=" | ">" | ">=" | "<" | "<=" => expression_if(
190            filter.array_length() != 3 || filter.array_member(1).is_array() || filter.array_member(2).is_array(),
191        ),
192        // One expression child makes the whole tree an expression.
193        "any" | "all" => {
194            let mut syntax = Syntax::Neutral;
195            for i in 1..filter.array_length() {
196                match classify(&filter.array_member(i)) {
197                    Syntax::Expression => return Syntax::Expression,
198                    Syntax::Legacy => syntax = Syntax::Legacy,
199                    Syntax::Neutral => {}
200                }
201            }
202            syntax
203        }
204        _ => Syntax::Expression,
205    }
206}
207
208fn fail(error: &mut Error, message: &str) -> Option<Value> {
209    error.message = message.to_owned();
210    None
211}
212
213/// What a legacy filter compares: the feature's geometry type, its id or
214/// one of its properties.
215fn operand(property: &str) -> Value {
216    match property {
217        "$type" => op("geometry-type", []),
218        "$id" => op("id", []),
219        key => get(key),
220    }
221}
222
223/// Whether the feature's `property` equals `value`. A property equals null
224/// only where the feature has it.
225fn equals(property: &str, value: Value) -> Value {
226    if value == Value::Null && property != "$id" && property != "$type" {
227        return op("all", [op("has", [property.into()]), op("==", [get(property), Value::Null])]);
228    }
229    op("==", [operand(property), literal(value)])
230}
231
232/// `["==", key, value]` and the other comparisons. An ordering holds only
233/// between two numbers or two strings, where an expression would fail.
234fn comparison(name: &str, filter: &Convertible<'_>, error: &mut Error) -> Option<Value> {
235    let Some(property) = filter.array_member(1).to_string() else {
236        return fail(error, "filter property must be a string");
237    };
238    if filter.array_length() != 3 {
239        return fail(error, "filter must compare a property with one value");
240    }
241    let value = owned(&filter.array_member(2));
242    match name {
243        "==" => Some(equals(&property, value)),
244        "!=" => Some(op("!", [equals(&property, value)])),
245        _ if property == "$type" => fail(error, "a geometry type can only be compared for equality"),
246        _ => {
247            let ty = match value {
248                Value::String(_) => "string",
249                _ if number(&value).is_some() => "number",
250                _ => return Some(false.into()),
251            };
252            let operand = operand(&property);
253            let is_type = op("==", [op("typeof", [operand.clone()]), ty.into()]);
254            Some(op("case", [is_type, op(name, [operand, value]), false.into()]))
255        }
256    }
257}
258
259fn has(filter: &Convertible<'_>, error: &mut Error) -> Option<Value> {
260    match filter.array_member(1).to_string().as_deref() {
261        None => fail(error, "filter property must be a string"),
262        Some("$type") => Some(true.into()),
263        Some("$id") => Some(op("!=", [op("id", []), Value::Null])),
264        Some(key) => Some(op("has", [key.into()])),
265    }
266}
267
268fn in_(filter: &Convertible<'_>, error: &mut Error) -> Option<Value> {
269    let Some(property) = filter.array_member(1).to_string() else {
270        return fail(error, "filter property must be a string");
271    };
272    let mut values: Vec<Value> = Vec::new();
273    for i in 2..filter.array_length() {
274        let value = owned(&filter.array_member(i));
275        let value = number(&value).map_or(value, Value::Double);
276        if !values.contains(&value) {
277            values.push(value);
278        }
279    }
280    if values.is_empty() {
281        return Some(false.into());
282    }
283    if matchable(&values) {
284        return Some(op("match", [operand(&property), Value::Array(values), true.into(), false.into()]));
285    }
286    Some(op("any", values.into_iter().map(|value| equals(&property, value))))
287}
288
289/// A legacy filter, as the expression the style specification defines it
290/// by.
291fn legacy_filter_expression(filter: &Convertible<'_>, error: &mut Error) -> Option<Value> {
292    if filter.is_undefined() {
293        return Some(true.into());
294    }
295    // A boolean means itself in either syntax.
296    if let Some(value) = filter.to_bool() {
297        return Some(value.into());
298    }
299    if !filter.is_array() || filter.array_length() == 0 {
300        return fail(error, "filter value must be a non empty array");
301    }
302    let Some(name) = filter.array_member(0).to_string() else {
303        return fail(error, "filter operator must be a string");
304    };
305    if filter.array_length() <= 1 {
306        return Some((name != "any").into());
307    }
308    let children = |error: &mut Error| -> Option<Vec<Value>> {
309        (1..filter.array_length()).map(|i| legacy_filter_expression(&filter.array_member(i), error)).collect()
310    };
311    match name.as_str() {
312        "within" => Some(owned(filter)),
313        "==" | "!=" | "<" | ">" | "<=" | ">=" => comparison(&name, filter, error),
314        "any" | "all" => Some(op(&name, children(error)?)),
315        "none" => Some(op("!", [op("any", children(error)?)])),
316        "in" => in_(filter, error),
317        "!in" => Some(op("!", [in_(filter, error)?])),
318        "has" => has(filter, error),
319        "!has" => Some(op("!", [has(filter, error)?])),
320        _ => Some(true.into()),
321    }
322}
323
324#[cfg(test)]
325#[path = "filter_test.rs"]
326mod tests;