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