1use logicaffeine_base::numeric;
4use logicaffeine_base::{BigInt, Rational};
5
6use crate::ast::stmt::BinaryOpKind;
7use crate::interpreter::RuntimeValue;
8
9pub fn equality(left: &RuntimeValue, right: &RuntimeValue, negate: bool) -> Result<RuntimeValue, String> {
28 let rel = if negate { super::exact::Rel::NotEq } else { super::exact::Rel::Eq };
29 if let Some(r) = super::exact::relation(rel, left, right, &exact_relation_recurse) {
30 return r;
31 }
32 Ok(RuntimeValue::Bool(values_equal(left, right) != negate))
33}
34
35fn exact_relation_recurse(
37 rel: super::exact::Rel,
38 a: RuntimeValue,
39 b: RuntimeValue,
40) -> Result<RuntimeValue, String> {
41 use super::exact::Rel;
42 match rel {
43 Rel::Eq => equality(&a, &b, false),
44 Rel::NotEq => equality(&a, &b, true),
45 Rel::Lt => compare(BinaryOpKind::Lt, &a, &b),
46 Rel::Gt => compare(BinaryOpKind::Gt, &a, &b),
47 Rel::LtEq => compare(BinaryOpKind::LtEq, &a, &b),
48 Rel::GtEq => compare(BinaryOpKind::GtEq, &a, &b),
49 }
50}
51
52pub fn values_equal(left: &RuntimeValue, right: &RuntimeValue) -> bool {
53 values_equal_depth(left, right, 0)
54}
55
56const EQ_MAX_DEPTH: usize = 256;
59
60fn counter_as_int(v: &RuntimeValue) -> Option<RuntimeValue> {
64 match v {
65 RuntimeValue::Crdt(c) => c.borrow().counter_value().map(RuntimeValue::Int),
66 _ => None,
67 }
68}
69
70fn values_equal_depth(left: &RuntimeValue, right: &RuntimeValue, depth: usize) -> bool {
71 if depth > EQ_MAX_DEPTH {
72 return false;
73 }
74 if let Some(same) = super::exact::structurally_equal(left, right) {
75 return same;
76 }
77 let (lc, rc) = (counter_as_int(left), counter_as_int(right));
78 let (left, right) = (lc.as_ref().unwrap_or(left), rc.as_ref().unwrap_or(right));
79 match (left, right) {
80 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => a == b,
81 (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => a == b,
84 (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => a == b,
87 (RuntimeValue::Decimal(a), RuntimeValue::Decimal(b)) => a == b,
90 (RuntimeValue::Complex(a), RuntimeValue::Complex(b)) => a == b,
93 (RuntimeValue::ComplexF(a), RuntimeValue::ComplexF(b)) => a == b,
96 (RuntimeValue::Modular(a), RuntimeValue::Modular(b)) => a == b,
99 (RuntimeValue::Float(a), RuntimeValue::Float(b)) => a == b,
101 (RuntimeValue::Int(a), RuntimeValue::Float(b))
103 | (RuntimeValue::Float(b), RuntimeValue::Int(a)) => {
104 numeric::cmp_i64_f64_exact(*a, *b) == Some(std::cmp::Ordering::Equal)
105 }
106 (RuntimeValue::BigInt(a), RuntimeValue::Float(b))
107 | (RuntimeValue::Float(b), RuntimeValue::BigInt(a)) => {
108 numeric::cmp_bigint_f64_exact(a, *b) == Some(std::cmp::Ordering::Equal)
109 }
110 (RuntimeValue::Rational(a), RuntimeValue::Float(b))
111 | (RuntimeValue::Float(b), RuntimeValue::Rational(a)) => {
112 numeric::cmp_rational_f64_exact(a, *b) == Some(std::cmp::Ordering::Equal)
113 }
114 (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => a == b,
115 (RuntimeValue::Text(a), RuntimeValue::Text(b)) => **a == **b,
116 (RuntimeValue::Char(a), RuntimeValue::Char(b)) => a == b,
117 (RuntimeValue::Nothing, RuntimeValue::Nothing) => true,
118 (RuntimeValue::Nothing, RuntimeValue::Inductive(i))
126 | (RuntimeValue::Inductive(i), RuntimeValue::Nothing) => {
127 i.inductive_type == "Option" && i.constructor == "None"
128 }
129 (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => a == b,
130 (RuntimeValue::Date(a), RuntimeValue::Date(b)) => a == b,
131 (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => a == b,
132 (
133 RuntimeValue::Span {
134 months: m1,
135 days: d1,
136 },
137 RuntimeValue::Span {
138 months: m2,
139 days: d2,
140 },
141 ) => m1 == m2 && d1 == d2,
142 (RuntimeValue::Time(a), RuntimeValue::Time(b)) => a == b,
143 (RuntimeValue::Word(a), RuntimeValue::Word(b)) => a == b,
145 (RuntimeValue::Money(a), RuntimeValue::Money(b)) => a == b,
148 (RuntimeValue::Quantity(a), RuntimeValue::Quantity(b)) => a.q == b.q,
149 (RuntimeValue::Uuid(a), RuntimeValue::Uuid(b)) => a == b,
150 (RuntimeValue::Inductive(a), RuntimeValue::Inductive(b)) => {
151 a.inductive_type == b.inductive_type
152 && a.constructor == b.constructor
153 && a.args.len() == b.args.len()
154 && a.args
155 .iter()
156 .zip(b.args.iter())
157 .all(|(x, y)| values_equal_depth(x, y, depth + 1))
158 }
159 (RuntimeValue::List(a), RuntimeValue::List(b)) => {
161 if std::rc::Rc::ptr_eq(a, b) {
162 return true;
163 }
164 let (a, b) = (a.borrow(), b.borrow());
165 a.len() == b.len()
166 && (0..a.len()).all(|i| match (a.get(i), b.get(i)) {
167 (Some(x), Some(y)) => values_equal_depth(&x, &y, depth + 1),
168 _ => false,
169 })
170 }
171 (RuntimeValue::Tuple(a), RuntimeValue::Tuple(b)) => {
172 a.len() == b.len()
173 && a.iter()
174 .zip(b.iter())
175 .all(|(x, y)| values_equal_depth(x, y, depth + 1))
176 }
177 (RuntimeValue::Set(a), RuntimeValue::Set(b)) => {
180 if std::rc::Rc::ptr_eq(a, b) {
181 return true;
182 }
183 let (a, b) = (a.borrow(), b.borrow());
184 a.len() == b.len()
185 && a.iter()
186 .all(|x| b.iter().any(|y| values_equal_depth(x, y, depth + 1)))
187 }
188 (RuntimeValue::Map(a), RuntimeValue::Map(b)) => {
190 if std::rc::Rc::ptr_eq(a, b) {
191 return true;
192 }
193 let (a, b) = (a.borrow(), b.borrow());
194 a.len() == b.len()
195 && a.iter().all(|(k, va)| {
196 b.get(k)
197 .is_some_and(|vb| values_equal_depth(va, vb, depth + 1))
198 })
199 }
200 (RuntimeValue::Struct(a), RuntimeValue::Struct(b)) => {
201 a.type_name == b.type_name
202 && a.fields.len() == b.fields.len()
203 && a.fields.iter().all(|(name, va)| {
204 b.fields
205 .get(name)
206 .is_some_and(|vb| values_equal_depth(va, vb, depth + 1))
207 })
208 }
209 (RuntimeValue::Chan(a), RuntimeValue::Chan(b)) => a == b,
212 (RuntimeValue::TaskHandle(a), RuntimeValue::TaskHandle(b)) => a == b,
213 (RuntimeValue::Peer(a), RuntimeValue::Peer(b)) => **a == **b,
214 (RuntimeValue::Function(a), RuntimeValue::Function(b)) => a.body_index == b.body_index,
215 (RuntimeValue::Crdt(a), RuntimeValue::Crdt(b)) => {
218 crate::semantics::crdt::crdt_values_equal(&a.borrow(), &b.borrow())
219 }
220 (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) => a == b,
222 _ => false,
223 }
224}
225
226pub fn compare(
234 op: BinaryOpKind,
235 left: &RuntimeValue,
236 right: &RuntimeValue,
237) -> Result<RuntimeValue, String> {
238 use std::cmp::Ordering;
239
240 let rel = match op {
241 BinaryOpKind::Lt => Some(super::exact::Rel::Lt),
242 BinaryOpKind::Gt => Some(super::exact::Rel::Gt),
243 BinaryOpKind::LtEq => Some(super::exact::Rel::LtEq),
244 BinaryOpKind::GtEq => Some(super::exact::Rel::GtEq),
245 _ => None,
246 };
247 if let Some(rel) = rel {
248 if let Some(r) = super::exact::relation(rel, left, right, &exact_relation_recurse) {
249 return r;
250 }
251 }
252
253 let (lc, rc) = (counter_as_int(left), counter_as_int(right));
255 let (left, right) = (lc.as_ref().unwrap_or(left), rc.as_ref().unwrap_or(right));
256
257 let rel = |ord: Option<Ordering>| -> bool {
259 match ord {
260 None => false,
261 Some(o) => match op {
262 BinaryOpKind::Lt => o == Ordering::Less,
263 BinaryOpKind::Gt => o == Ordering::Greater,
264 BinaryOpKind::LtEq => o != Ordering::Greater,
265 BinaryOpKind::GtEq => o != Ordering::Less,
266 _ => false,
267 },
268 }
269 };
270 let int_rel = |a: i64, b: i64| rel(Some(a.cmp(&b)));
271
272 match (left, right) {
273 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(int_rel(*a, *b))),
274 (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
276 Ok(RuntimeValue::Bool(rel(Some((**a).cmp(b)))))
277 }
278 (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(rel(Some(
279 (**a).cmp(&BigInt::from_i64(*b)),
280 )))),
281 (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
282 Ok(RuntimeValue::Bool(rel(Some(BigInt::from_i64(*a).cmp(b)))))
283 }
284 (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Bool(rel(
287 numeric::cmp_bigint_f64_exact(a, *b),
288 ))),
289 (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::Bool(rel(
290 numeric::cmp_bigint_f64_exact(b, *a).map(std::cmp::Ordering::reverse),
291 ))),
292 (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
295 Ok(RuntimeValue::Bool(rel(Some((**a).cmp(b)))))
296 }
297 (RuntimeValue::Rational(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(rel(Some(
298 (**a).cmp(&Rational::from_i64(*b)),
299 )))),
300 (RuntimeValue::Int(a), RuntimeValue::Rational(b)) => {
301 Ok(RuntimeValue::Bool(rel(Some(Rational::from_i64(*a).cmp(b)))))
302 }
303 (RuntimeValue::Rational(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::Bool(rel(Some(
304 (**a).cmp(&Rational::from_bigint((**b).clone())),
305 )))),
306 (RuntimeValue::BigInt(a), RuntimeValue::Rational(b)) => Ok(RuntimeValue::Bool(rel(Some(
307 Rational::from_bigint((**a).clone()).cmp(b),
308 )))),
309 (RuntimeValue::Rational(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Bool(rel(
310 numeric::cmp_rational_f64_exact(a, *b),
311 ))),
312 (RuntimeValue::Float(a), RuntimeValue::Rational(b)) => Ok(RuntimeValue::Bool(rel(
313 numeric::cmp_rational_f64_exact(b, *a).map(std::cmp::Ordering::reverse),
314 ))),
315 (RuntimeValue::Float(a), RuntimeValue::Float(b)) => {
316 Ok(RuntimeValue::Bool(rel(a.partial_cmp(b))))
317 }
318 (RuntimeValue::Int(a), RuntimeValue::Float(b)) => {
319 Ok(RuntimeValue::Bool(rel(numeric::cmp_i64_f64_exact(*a, *b))))
320 }
321 (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(rel(
322 numeric::cmp_i64_f64_exact(*b, *a).map(std::cmp::Ordering::reverse),
323 ))),
324 (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => {
325 Ok(RuntimeValue::Bool(int_rel(*a, *b)))
326 }
327 (RuntimeValue::Date(a), RuntimeValue::Date(b)) => {
328 Ok(RuntimeValue::Bool(int_rel(*a as i64, *b as i64)))
329 }
330 (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => {
331 Ok(RuntimeValue::Bool(int_rel(*a, *b)))
332 }
333 (RuntimeValue::Time(a), RuntimeValue::Time(b)) => Ok(RuntimeValue::Bool(int_rel(*a, *b))),
334 (RuntimeValue::Moment(m), RuntimeValue::Time(t)) => {
338 let nanos_per_day = 86_400_000_000_000i64;
339 Ok(RuntimeValue::Bool(int_rel(m.rem_euclid(nanos_per_day), *t)))
340 }
341 (RuntimeValue::Time(t), RuntimeValue::Moment(m)) => {
342 let nanos_per_day = 86_400_000_000_000i64;
343 Ok(RuntimeValue::Bool(int_rel(*t, m.rem_euclid(nanos_per_day))))
344 }
345 (RuntimeValue::Quantity(a), RuntimeValue::Quantity(b)) => {
349 if a.q.dimension() != b.q.dimension() {
350 return Err(logicaffeine_data::failure::quantities_uncomparable(
351 a.q.dimension(),
352 b.q.dimension(),
353 ));
354 }
355 Ok(RuntimeValue::Bool(rel(Some(
356 a.q.magnitude_si().cmp(b.q.magnitude_si()),
357 ))))
358 }
359 (RuntimeValue::Money(a), RuntimeValue::Money(b)) => {
362 if a.currency != b.currency {
363 return Err(logicaffeine_data::failure::currencies_differ(
364 "compare",
365 a.currency.code,
366 b.currency.code,
367 ));
368 }
369 Ok(RuntimeValue::Bool(rel(Some(
370 a.amount.to_rational().cmp(&b.amount.to_rational()),
371 ))))
372 }
373 (RuntimeValue::Uuid(a), RuntimeValue::Uuid(b)) => {
375 Ok(RuntimeValue::Bool(rel(Some(a.cmp(b)))))
376 }
377 (RuntimeValue::Word(a), RuntimeValue::Word(b)) => {
381 if a.width() != b.width() {
382 return Err(format!(
383 "cannot compare Word{} and Word{} — width mismatch",
384 a.width(),
385 b.width()
386 ));
387 }
388 Ok(RuntimeValue::Bool(rel(Some(a.to_u64().cmp(&b.to_u64())))))
389 }
390 (l, r)
393 if matches!(l, RuntimeValue::Decimal(_)) || matches!(r, RuntimeValue::Decimal(_)) =>
394 {
395 let rat_view = |v: &RuntimeValue| -> Option<Rational> {
396 match v {
397 RuntimeValue::Int(n) => Some(Rational::from_i64(*n)),
398 RuntimeValue::BigInt(b) => Some(Rational::from_bigint((**b).clone())),
399 RuntimeValue::Rational(r) => Some((**r).clone()),
400 RuntimeValue::Decimal(d) => Some(d.to_rational()),
401 _ => None,
402 }
403 };
404 if let (Some(a), Some(b)) = (rat_view(l), rat_view(r)) {
405 Ok(RuntimeValue::Bool(rel(Some(a.cmp(&b)))))
406 } else {
407 let f64_view = |v: &RuntimeValue| -> Option<f64> {
408 match v {
409 RuntimeValue::Float(f) => Some(*f),
410 other => rat_view(other).map(|x| x.to_f64()),
411 }
412 };
413 match (f64_view(l), f64_view(r)) {
414 (Some(a), Some(b)) => Ok(RuntimeValue::Bool(rel(a.partial_cmp(&b)))),
415 _ => Err(format!(
416 "Cannot compare {} and {}",
417 l.type_name(),
418 r.type_name()
419 )),
420 }
421 }
422 }
423 _ => Err(format!(
424 "Cannot compare {} and {}",
425 left.type_name(),
426 right.type_name()
427 )),
428 }
429}
430
431#[cfg(test)]
432#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/compare/tests.rs"]
433mod tests;