Skip to main content

mln_expression/
comparison.rs

1// Ports include/mln/style/expression/comparison.hpp and
2// src/mln/style/expression/comparison.cpp.
3
4use crate::assertion::Assertion;
5use crate::collator::Collator;
6use crate::expression::{
7    EvaluationContext, EvaluationError, EvaluationResult, Expression, ExpressionBase, Kind,
8    downcast,
9};
10use crate::parsing_context::{ParseResult, ParsingContext};
11use crate::type_::{self, Type};
12use crate::value::{Value, type_of};
13use mln_conversion::Convertible;
14
15fn is_comparable_type(op: &str, t: &Type) -> bool {
16    if op == "==" || op == "!=" {
17        *t == Type::String || *t == Type::Number || *t == Type::Boolean || *t == Type::Null || *t == Type::Value
18    } else {
19        *t == Type::String || *t == Type::Number || *t == Type::Value
20    }
21}
22
23type CompareFunctionType = fn(&Value, &Value) -> bool;
24type CollatorCompareFunctionType = fn(&str, &str, &Collator) -> bool;
25
26fn eq(a: &Value, b: &Value) -> bool {
27    a == b
28}
29fn neq(a: &Value, b: &Value) -> bool {
30    a != b
31}
32
33/// `lhs.match([&](const std::string& a) {...}, [&](double a) {...})` for the
34/// ordering operators.
35fn ordered(lhs: &Value, rhs: &Value, s: fn(&str, &str) -> bool, d: fn(f64, f64) -> bool) -> bool {
36    match lhs {
37        Value::String(a) => s(a, rhs.as_str().expect("string operand")),
38        Value::Number(a) => d(*a, rhs.as_number().expect("number operand")),
39        _ => {
40            debug_assert!(false);
41            false
42        }
43    }
44}
45
46fn lt(lhs: &Value, rhs: &Value) -> bool {
47    ordered(lhs, rhs, |a, b| a < b, |a, b| a < b)
48}
49fn gt(lhs: &Value, rhs: &Value) -> bool {
50    ordered(lhs, rhs, |a, b| a > b, |a, b| a > b)
51}
52fn lteq(lhs: &Value, rhs: &Value) -> bool {
53    ordered(lhs, rhs, |a, b| a <= b, |a, b| a <= b)
54}
55fn gteq(lhs: &Value, rhs: &Value) -> bool {
56    ordered(lhs, rhs, |a, b| a >= b, |a, b| a >= b)
57}
58
59fn eq_collate(a: &str, b: &str, c: &Collator) -> bool {
60    c.compare(a, b) == 0
61}
62fn neq_collate(a: &str, b: &str, c: &Collator) -> bool {
63    !eq_collate(a, b, c)
64}
65fn lt_collate(a: &str, b: &str, c: &Collator) -> bool {
66    c.compare(a, b) < 0
67}
68fn gt_collate(a: &str, b: &str, c: &Collator) -> bool {
69    c.compare(a, b) > 0
70}
71fn lteq_collate(a: &str, b: &str, c: &Collator) -> bool {
72    c.compare(a, b) <= 0
73}
74fn gteq_collate(a: &str, b: &str, c: &Collator) -> bool {
75    c.compare(a, b) >= 0
76}
77
78fn get_basic_compare_function(op: &str) -> CompareFunctionType {
79    match op {
80        "==" => eq,
81        "!=" => neq,
82        ">" => gt,
83        "<" => lt,
84        ">=" => gteq,
85        "<=" => lteq,
86        _ => unreachable!("unknown comparison {op}"),
87    }
88}
89
90fn get_collator_comparison_function(op: &str) -> CollatorCompareFunctionType {
91    match op {
92        "==" => eq_collate,
93        "!=" => neq_collate,
94        ">" => gt_collate,
95        "<" => lt_collate,
96        ">=" => gteq_collate,
97        "<=" => lteq_collate,
98        _ => unreachable!("unknown comparison {op}"),
99    }
100}
101
102pub struct BasicComparison {
103    base: ExpressionBase,
104    op: String,
105    compare: CompareFunctionType,
106    lhs: Box<dyn Expression>,
107    rhs: Box<dyn Expression>,
108    needs_runtime_type_check: bool,
109}
110
111impl BasicComparison {
112    pub fn new(op: String, lhs: Box<dyn Expression>, rhs: Box<dyn Expression>) -> Self {
113        debug_assert!(is_comparable_type(&op, lhs.get_type()) && is_comparable_type(&op, rhs.get_type()));
114        debug_assert!(
115            lhs.get_type() == rhs.get_type()
116                || *lhs.get_type() == Type::Value
117                || *rhs.get_type() == Type::Value
118        );
119
120        let needs_runtime_type_check = (op != "==" && op != "!=")
121            && (*lhs.get_type() == Type::Value || *rhs.get_type() == Type::Value);
122        BasicComparison {
123            base: ExpressionBase::new(
124                Kind::Comparison,
125                Type::Boolean,
126                lhs.dependencies() | rhs.dependencies(),
127            ),
128            compare: get_basic_compare_function(&op),
129            op,
130            lhs,
131            rhs,
132            needs_runtime_type_check,
133        }
134    }
135}
136
137impl Expression for BasicComparison {
138    fn base(&self) -> &ExpressionBase {
139        &self.base
140    }
141
142    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
143        let lhs_result = self.lhs.evaluate(params)?;
144        let rhs_result = self.rhs.evaluate(params)?;
145
146        if self.needs_runtime_type_check {
147            let lhs_type = type_of(&lhs_result);
148            let rhs_type = type_of(&rhs_result);
149            // check that type is string or number, and equal
150            if lhs_type != rhs_type || !(lhs_type == Type::String || lhs_type == Type::Number) {
151                return Err(EvaluationError::new(format!(
152                    r#"Expected arguments for "{}" to be (string, string) or (number, number), but found ({}, {}) instead."#,
153                    self.op,
154                    type_::to_string(&lhs_type),
155                    type_::to_string(&rhs_type)
156                )));
157            }
158        }
159
160        Ok(Value::Bool((self.compare)(&lhs_result, &rhs_result)))
161    }
162
163    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
164        visit(&*self.lhs);
165        visit(&*self.rhs);
166    }
167
168    fn equals(&self, e: &dyn Expression) -> bool {
169        // C++ static_casts any Kind::Comparison to BasicComparison.
170        if e.get_kind() == Kind::Comparison {
171            if let Some(comp) = downcast::<BasicComparison>(e) {
172                return comp.op == self.op && comp.lhs.equals(&*self.lhs) && comp.rhs.equals(&*self.rhs);
173            }
174        }
175        false
176    }
177
178    fn possible_outputs(&self) -> Vec<Option<Value>> {
179        vec![Some(Value::Bool(true)), Some(Value::Bool(false))]
180    }
181
182    fn get_operator(&self) -> String {
183        self.op.clone()
184    }
185}
186
187pub struct CollatorComparison {
188    base: ExpressionBase,
189    op: String,
190    compare: CollatorCompareFunctionType,
191    lhs: Box<dyn Expression>,
192    rhs: Box<dyn Expression>,
193    collator: Box<dyn Expression>,
194    needs_runtime_type_check: bool,
195}
196
197impl CollatorComparison {
198    pub fn new(
199        op: String,
200        lhs: Box<dyn Expression>,
201        rhs: Box<dyn Expression>,
202        collator: Box<dyn Expression>,
203    ) -> Self {
204        debug_assert!(is_comparable_type(&op, lhs.get_type()) && is_comparable_type(&op, rhs.get_type()));
205        let needs_runtime_type_check = (op == "==" || op == "!=")
206            && (*lhs.get_type() == Type::Value || *rhs.get_type() == Type::Value);
207        CollatorComparison {
208            base: ExpressionBase::new(
209                Kind::Comparison,
210                Type::Boolean,
211                lhs.dependencies() | rhs.dependencies() | collator.dependencies(),
212            ),
213            compare: get_collator_comparison_function(&op),
214            op,
215            lhs,
216            rhs,
217            collator,
218            needs_runtime_type_check,
219        }
220    }
221}
222
223impl Expression for CollatorComparison {
224    fn base(&self) -> &ExpressionBase {
225        &self.base
226    }
227
228    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
229        let lhs_result = self.lhs.evaluate(params);
230        let Ok(lhs_value) = &lhs_result else {
231            return lhs_result;
232        };
233
234        let rhs_result = self.rhs.evaluate(params);
235        let Ok(rhs_value) = &rhs_result else {
236            // Quirk kept from the C++: returns the (successful) lhs result.
237            return lhs_result;
238        };
239
240        if self.needs_runtime_type_check
241            && (type_of(lhs_value) != Type::String || type_of(rhs_value) != Type::String)
242        {
243            return Ok(Value::Bool(get_basic_compare_function(&self.op)(lhs_value, rhs_value)));
244        }
245
246        let collator_result = self.collator.evaluate(params)?;
247
248        let Value::Collator(c) = &collator_result else {
249            panic!("collator operand")
250        };
251        // TODO(port): util::LocaleException from the platform collator.
252        Ok(Value::Bool((self.compare)(
253            lhs_value.as_str().expect("string operand"),
254            rhs_value.as_str().expect("string operand"),
255            c,
256        )))
257    }
258
259    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
260        visit(&*self.lhs);
261        visit(&*self.rhs);
262        visit(&*self.collator);
263    }
264
265    fn equals(&self, e: &dyn Expression) -> bool {
266        if e.get_kind() == Kind::Comparison {
267            if let Some(comp) = downcast::<CollatorComparison>(e) {
268                return comp.op == self.op
269                    && comp.collator.equals(&*self.collator)
270                    && comp.lhs.equals(&*self.lhs)
271                    && comp.rhs.equals(&*self.rhs);
272            }
273        }
274        false
275    }
276
277    fn possible_outputs(&self) -> Vec<Option<Value>> {
278        vec![Some(Value::Bool(true)), Some(Value::Bool(false))]
279    }
280
281    fn get_operator(&self) -> String {
282        self.op.clone()
283    }
284}
285
286pub fn parse_comparison(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
287    let length = value.array_length();
288
289    if length != 3 && length != 4 {
290        ctx.error("Expected two or three arguments.".to_owned());
291        return None;
292    }
293
294    let op = value.array_member(0).to_string().expect("operator name");
295
296    let mut lhs = ctx.parse(&value.array_member(1), 1, Some(Type::Value), None)?;
297    let lhs_type = lhs.get_type().clone();
298    if !is_comparable_type(&op, &lhs_type) {
299        ctx.error_at(
300            format!(
301                r#""{}" comparisons are not supported for type '{}'."#,
302                op,
303                type_::to_string(&lhs_type)
304            ),
305            1,
306        );
307        return None;
308    }
309
310    let mut rhs = ctx.parse(&value.array_member(2), 2, Some(Type::Value), None)?;
311    let rhs_type = rhs.get_type().clone();
312    if !is_comparable_type(&op, &rhs_type) {
313        ctx.error_at(
314            format!(
315                r#""{}" comparisons are not supported for type '{}'."#,
316                op,
317                type_::to_string(&rhs_type)
318            ),
319            2,
320        );
321        return None;
322    }
323
324    if lhs_type != rhs_type && lhs_type != Type::Value && rhs_type != Type::Value {
325        ctx.error(format!(
326            "Cannot compare types '{}' and '{}'.",
327            type_::to_string(&lhs_type),
328            type_::to_string(&rhs_type)
329        ));
330        return None;
331    }
332
333    if op != "==" && op != "!=" {
334        // typing rules specific to less/greater than operators
335        if lhs_type == Type::Value && rhs_type != Type::Value {
336            // (value, T)
337            lhs = Box::new(Assertion::new(rhs_type.clone(), vec![lhs]));
338        } else if lhs_type != Type::Value && rhs_type == Type::Value {
339            // (T, value)
340            rhs = Box::new(Assertion::new(lhs_type.clone(), vec![rhs]));
341        }
342    }
343
344    if length == 4 {
345        if lhs_type != Type::String
346            && rhs_type != Type::String
347            && lhs_type != Type::Value
348            && rhs_type != Type::Value
349        {
350            ctx.error("Cannot use collator to compare non-string types.".to_owned());
351            return None;
352        }
353        let collator_parse_result = ctx.parse(&value.array_member(3), 3, Some(Type::Collator), None)?;
354        return Some(Box::new(CollatorComparison::new(op, lhs, rhs, collator_parse_result)));
355    }
356
357    Some(Box::new(BasicComparison::new(op, lhs, rhs)))
358}