1use std::cmp::Ordering;
2
3use feature::Value as MbglValue;
4use mln_conversion::Convertible;
5
6use crate::assertion::Assertion;
7use crate::collator::Collator;
8use crate::expression::{EvalResult, EvaluationContext, EvaluationError, Expr, Node};
9use crate::parsing_context::{ParseResult, ParsingContext};
10use crate::type_::{self, Type};
11use crate::value::{Value, type_of};
12
13fn is_comparable_type(op: &str, t: &Type) -> bool {
14 if op == "==" || op == "!=" {
15 *t == Type::String || *t == Type::Number || *t == Type::Boolean || *t == Type::Null || *t == Type::Value
16 } else {
17 *t == Type::String || *t == Type::Number || *t == Type::Value
18 }
19}
20
21#[derive(Clone, Copy, PartialEq, Eq, Debug, mln_wire::Wire)]
23pub(crate) enum CmpOp {
24 Eq,
25 Ne,
26 Lt,
27 Gt,
28 Le,
29 Ge,
30}
31
32impl CmpOp {
33 fn parse(op: &str) -> CmpOp {
34 match op {
35 "==" => CmpOp::Eq,
36 "!=" => CmpOp::Ne,
37 "<" => CmpOp::Lt,
38 ">" => CmpOp::Gt,
39 "<=" => CmpOp::Le,
40 ">=" => CmpOp::Ge,
41 _ => unreachable!("unknown comparison {op}"),
42 }
43 }
44
45 pub(crate) fn as_str(self) -> &'static str {
46 match self {
47 CmpOp::Eq => "==",
48 CmpOp::Ne => "!=",
49 CmpOp::Lt => "<",
50 CmpOp::Gt => ">",
51 CmpOp::Le => "<=",
52 CmpOp::Ge => ">=",
53 }
54 }
55
56 fn holds(self, ordering: Option<Ordering>) -> bool {
59 match ordering {
60 None => self == CmpOp::Ne,
61 Some(o) => match self {
62 CmpOp::Eq => o.is_eq(),
63 CmpOp::Ne => o.is_ne(),
64 CmpOp::Lt => o.is_lt(),
65 CmpOp::Gt => o.is_gt(),
66 CmpOp::Le => o.is_le(),
67 CmpOp::Ge => o.is_ge(),
68 },
69 }
70 }
71}
72
73#[derive(Clone, Copy, PartialEq, Eq, Debug, mln_wire::Wire)]
75enum Operands {
76 Numbers,
77 Strings,
78 Booleans,
79 Values,
82 Collated,
84}
85
86#[derive(Clone, PartialEq, mln_wire::Wire)]
88pub(crate) struct Comparison {
89 op: CmpOp,
90 operands: Operands,
91 lhs: Expr,
92 rhs: Expr,
93 collator: Option<Expr>,
94}
95
96impl Comparison {
97 pub(crate) fn new_expr(op: &str, lhs: Expr, rhs: Expr, collator: Option<Expr>) -> Expr {
98 let (lhs_type, rhs_type) = (lhs.get_type(), rhs.get_type());
99 debug_assert!(is_comparable_type(op, &lhs_type) && is_comparable_type(op, &rhs_type));
100 let operands = match (&lhs_type, &rhs_type) {
101 _ if collator.is_some() => Operands::Collated,
102 (Type::Number, Type::Number) => Operands::Numbers,
103 (Type::String, Type::String) => Operands::Strings,
104 (Type::Boolean, Type::Boolean) => Operands::Booleans,
105 _ => Operands::Values,
106 };
107 Expr::new(Node::Comparison(Box::new(Comparison { op: CmpOp::parse(op), operands, lhs, rhs, collator })))
108 }
109
110 pub(crate) fn as_equality(&self) -> Option<(&Expr, &Value)> {
113 if self.op != CmpOp::Eq || self.collator.is_some() {
114 return None;
115 }
116 match (self.lhs.literal_value(), self.rhs.literal_value()) {
117 (None, Some(value)) => Some((&self.lhs, value)),
118 (Some(value), None) => Some((&self.rhs, value)),
119 _ => None,
120 }
121 }
122
123 pub(crate) fn get_operator(&self) -> &'static str {
124 self.op.as_str()
125 }
126
127 pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
128 visit(&self.lhs);
129 visit(&self.rhs);
130 if let Some(collator) = &self.collator {
131 visit(collator);
132 }
133 }
134
135 pub(crate) fn serialize(&self) -> MbglValue {
136 let mut serialized =
137 vec![MbglValue::String(self.get_operator().to_owned()), self.lhs.serialize(), self.rhs.serialize()];
138 if let Some(collator) = &self.collator {
139 serialized.push(collator.serialize());
140 }
141 MbglValue::Array(serialized)
142 }
143
144 pub(crate) fn eval_bool(&self, params: &EvaluationContext<'_>) -> EvalResult<bool> {
145 match self.operands {
146 Operands::Numbers => {
147 let (a, b) = (self.lhs.eval_num(params)?, self.rhs.eval_num(params)?);
148 Ok(self.op.holds(a.partial_cmp(&b)))
149 }
150 Operands::Strings => {
151 let a = self.lhs.eval_str(params)?;
152 let b = self.rhs.eval_str(params)?;
153 Ok(self.op.holds(Some(a.cmp(&b))))
154 }
155 Operands::Booleans => {
156 let (a, b) = (self.lhs.eval_bool(params)?, self.rhs.eval_bool(params)?);
157 Ok(self.op.holds(Some(a.cmp(&b))))
158 }
159 Operands::Values => {
160 let a = self.lhs.evaluate_ref(params)?;
161 let b = self.rhs.evaluate_ref(params)?;
162 self.compare_values(&a, &b)
163 }
164 Operands::Collated => {
165 let a = self.lhs.evaluate_ref(params)?;
166 let b = self.rhs.evaluate_ref(params)?;
167 let (Value::String(a), Value::String(b)) = (&*a, &*b) else {
168 return self.compare_values(&a, &b);
171 };
172 let Some(collator) = &self.collator else {
173 return Ok(self.op.holds(Some(a.cmp(b))));
174 };
175 let collator = collator.evaluate_ref(params)?;
176 let Value::Collator(collator_value) = &*collator else {
177 return Err(EvaluationError::type_mismatch(&Type::Collator, &collator));
178 };
179 Ok(self.op.holds(Some(Collator::compare(collator_value, a, b))))
180 }
181 }
182 }
183
184 fn compare_values(&self, a: &Value, b: &Value) -> EvalResult<bool> {
185 match self.op {
186 CmpOp::Eq => Ok(a == b),
187 CmpOp::Ne => Ok(a != b),
188 _ => match (a, b) {
189 (Value::Number(a), Value::Number(b)) => Ok(self.op.holds(a.partial_cmp(b))),
190 (Value::String(a), Value::String(b)) => Ok(self.op.holds(Some(a.cmp(b)))),
191 _ => Err(EvaluationError::new(format!(
192 r#"Expected arguments for "{}" to be (string, string) or (number, number), but found ({}, {}) instead."#,
193 self.op.as_str(),
194 type_::to_string(&type_of(a)),
195 type_::to_string(&type_of(b))
196 ))),
197 },
198 }
199 }
200}
201
202pub(crate) fn parse_comparison(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
203 let length = value.array_length();
204
205 if length != 3 && length != 4 {
206 ctx.error("Expected two or three arguments.".to_owned());
207 return None;
208 }
209
210 let Some(op) = value.array_member(0).to_string() else {
211 ctx.error("Expected the comparison operator to be a string.".to_owned());
212 return None;
213 };
214
215 let mut lhs = ctx.parse(&value.array_member(1), 1, Some(Type::Value), None)?;
216 let lhs_type = lhs.get_type();
217 if !is_comparable_type(&op, &lhs_type) {
218 ctx.error_at(
219 format!(r#""{}" comparisons are not supported for type '{}'."#, op, type_::to_string(&lhs_type)),
220 1,
221 );
222 return None;
223 }
224
225 let mut rhs = ctx.parse(&value.array_member(2), 2, Some(Type::Value), None)?;
226 let rhs_type = rhs.get_type();
227 if !is_comparable_type(&op, &rhs_type) {
228 ctx.error_at(
229 format!(r#""{}" comparisons are not supported for type '{}'."#, op, type_::to_string(&rhs_type)),
230 2,
231 );
232 return None;
233 }
234
235 if lhs_type != rhs_type && lhs_type != Type::Value && rhs_type != Type::Value {
236 ctx.error(format!(
237 "Cannot compare types '{}' and '{}'.",
238 type_::to_string(&lhs_type),
239 type_::to_string(&rhs_type)
240 ));
241 return None;
242 }
243
244 if op != "==" && op != "!=" {
245 if lhs_type == Type::Value && rhs_type != Type::Value {
247 lhs = Assertion::new_expr(rhs_type.clone(), vec![lhs]);
249 } else if lhs_type != Type::Value && rhs_type == Type::Value {
250 rhs = Assertion::new_expr(lhs_type.clone(), vec![rhs]);
252 }
253 }
254
255 if length == 4 {
256 if lhs_type != Type::String && rhs_type != Type::String && lhs_type != Type::Value && rhs_type != Type::Value {
257 ctx.error("Cannot use collator to compare non-string types.".to_owned());
258 return None;
259 }
260 let collator_parse_result = ctx.parse(&value.array_member(3), 3, Some(Type::Collator), None)?;
261 return Some(Comparison::new_expr(&op, lhs, rhs, Some(collator_parse_result)));
262 }
263
264 Some(Comparison::new_expr(&op, lhs, rhs, None))
265}