Skip to main content

doge_runtime/ops/
compare.rs

1use std::cmp::Ordering;
2use std::rc::Rc;
3
4use bigdecimal::{BigDecimal, ToPrimitive};
5
6use crate::error::{DogeError, DogeResult};
7use crate::value::Value;
8
9/// Whether `v` is one of the three numeric types (`Int`/`Float`/`Decimal`), which
10/// compare across each other rather than by exact type.
11fn is_numeric(v: &Value) -> bool {
12    matches!(v, Value::Int(_) | Value::Float(_) | Value::Decimal(_))
13}
14
15/// A numeric value as `f64`, for any comparison that pairs a `Float` with an
16/// `Int`/`Decimal`. `None` only for a non-number or a `Float` NaN.
17fn numeric_f64(v: &Value) -> Option<f64> {
18    match v {
19        Value::Int(n) => n.to_f64(),
20        Value::Float(f) => Some(*f),
21        Value::Decimal(d) => d.to_f64(),
22        _ => None,
23    }
24}
25
26/// Ordering between two numeric values, comparing exactly where both are exact
27/// (Int/Decimal) and via `f64` once a `Float` is involved. `None` when a NaN is
28/// involved (no ordering). Both operands must be numeric.
29fn numeric_cmp(a: &Value, b: &Value) -> Option<Ordering> {
30    match (a, b) {
31        (Value::Int(x), Value::Int(y)) => Some(x.cmp(y)),
32        (Value::Decimal(x), Value::Decimal(y)) => Some(x.cmp(y)),
33        (Value::Int(x), Value::Decimal(y)) => Some(BigDecimal::from(x.clone()).cmp(y)),
34        (Value::Decimal(x), Value::Int(y)) => Some(x.cmp(&BigDecimal::from(y.clone()))),
35        _ => numeric_f64(a)?.partial_cmp(&numeric_f64(b)?),
36    }
37}
38
39/// Numeric equality when both operands are numbers (`Some`), else `None` so the
40/// caller falls through to structural/type comparison. Uses value ordering, so
41/// `dec("0.10") == dec("0.1")` and `1 == 1.0` both hold.
42fn numeric_equal(a: &Value, b: &Value) -> Option<bool> {
43    if is_numeric(a) && is_numeric(b) {
44        Some(numeric_cmp(a, b) == Some(Ordering::Equal))
45    } else {
46        None
47    }
48}
49
50/// Structural, Python-style equality: `1 == 1.0`, deep list/dict comparison,
51/// everything else across types is unequal.
52pub fn values_equal(a: &Value, b: &Value) -> bool {
53    if let Some(numeric) = numeric_equal(a, b) {
54        return numeric;
55    }
56    match (a, b) {
57        (Value::Str(x), Value::Str(y)) => x == y,
58        (Value::Bytes(x), Value::Bytes(y)) => x == y,
59        (Value::Bool(x), Value::Bool(y)) => x == y,
60        (Value::None, Value::None) => true,
61        (Value::List(x), Value::List(y)) => {
62            let (xb, yb) = (x.borrow(), y.borrow());
63            xb.len() == yb.len() && xb.iter().zip(yb.iter()).all(|(p, q)| values_equal(p, q))
64        }
65        (Value::Dict(x), Value::Dict(y)) => {
66            let (xb, yb) = (x.borrow(), y.borrow());
67            xb.len() == yb.len()
68                && xb
69                    .iter()
70                    .all(|(k, v)| yb.get(k).is_some_and(|w| values_equal(v, w)))
71        }
72        // Objects are equal only when they are the very same instance.
73        (Value::Object(x), Value::Object(y)) => Rc::ptr_eq(x, y),
74        // Function equality includes captured-cell identity, not just its definition.
75        (Value::Function(x), Value::Function(y)) => {
76            x.fn_id == y.fn_id
77                && x.captures.len() == y.captures.len()
78                && x.captures
79                    .iter()
80                    .zip(y.captures.iter())
81                    .all(|(p, q)| Rc::ptr_eq(p, q))
82        }
83        // Classes have no captures, so constructor identity is sufficient.
84        (Value::Class(x), Value::Class(y)) => x.fn_id == y.fn_id,
85        // Bound methods include receiver identity.
86        (Value::BoundMethod(x), Value::BoundMethod(y)) => {
87            x.method == y.method && values_equal(&x.receiver, &y.receiver)
88        }
89        // Errors are equal when their type, message, and raise site all match.
90        (Value::Error(x), Value::Error(y)) => {
91            x.kind == y.kind && x.message == y.message && x.file == y.file && x.line == y.line
92        }
93        // Sockets are equal only when they are the very same handle.
94        (Value::Socket(x), Value::Socket(y)) => Rc::ptr_eq(x, y),
95        // Pups and bowls, like sockets, are equal only to the very same handle.
96        (Value::Pup(x), Value::Pup(y)) => Rc::ptr_eq(x, y),
97        (Value::Bowl(x), Value::Bowl(y)) => Rc::ptr_eq(x, y),
98        // Explicit variants make a new same-type equality case mandatory.
99        (Value::Int(_), _)
100        | (Value::Float(_), _)
101        | (Value::Decimal(_), _)
102        | (Value::Str(_), _)
103        | (Value::Bytes(_), _)
104        | (Value::Bool(_), _)
105        | (Value::None, _)
106        | (Value::List(_), _)
107        | (Value::Dict(_), _)
108        | (Value::Object(_), _)
109        | (Value::Function(_), _)
110        | (Value::Class(_), _)
111        | (Value::BoundMethod(_), _)
112        | (Value::Error(_), _)
113        | (Value::Socket(_), _)
114        | (Value::Pup(_), _)
115        | (Value::Bowl(_), _) => false,
116    }
117}
118
119/// `==`.
120pub fn eq(a: Value, b: Value) -> DogeResult {
121    Ok(Value::Bool(values_equal(&a, &b)))
122}
123
124/// `!=`.
125pub fn ne(a: Value, b: Value) -> DogeResult {
126    Ok(Value::Bool(!values_equal(&a, &b)))
127}
128
129/// Whether `target` is structurally equal to some element of `items`. Shared by
130/// the `in` operator and `List.contains` so their membership rule is identical.
131pub(crate) fn slice_contains(items: &[Value], target: &Value) -> bool {
132    items.iter().any(|element| values_equal(element, target))
133}
134
135/// `needle in container`. Python-style: a List tests element membership, a Dict
136/// tests key membership, a Str tests substring. Every other container type is a
137/// catchable type error. Matched by container variant (not a wildcard) so a new
138/// `Value` variant forces its own decision here.
139pub fn in_(needle: Value, container: Value) -> DogeResult {
140    let found = match &container {
141        Value::List(items) => slice_contains(&items.borrow(), &needle),
142        // A non-Str cannot be a Dict key, so it is absent rather than an error.
143        Value::Dict(entries) => match &needle {
144            Value::Str(k) => entries.borrow().contains_key(k.as_ref()),
145            _ => false,
146        },
147        Value::Str(haystack) => match &needle {
148            Value::Str(sub) => haystack.contains(sub.as_ref()),
149            _ => {
150                return Err(DogeError::type_error(format!(
151                    "can only check if a Str is in a Str, not {}",
152                    needle.describe()
153                )));
154            }
155        },
156        // Int tests byte membership; Bytes tests a contiguous sub-slice.
157        Value::Bytes(haystack) => match &needle {
158            Value::Int(n) => n.to_u8().is_some_and(|b| haystack.contains(&b)),
159            Value::Bytes(sub) => {
160                sub.is_empty() || haystack.windows(sub.len()).any(|w| w == &sub[..])
161            }
162            _ => {
163                return Err(DogeError::type_error(format!(
164                    "can only check if an Int or Bytes is in a Bytes, not {}",
165                    needle.describe()
166                )));
167            }
168        },
169        Value::Int(_)
170        | Value::Float(_)
171        | Value::Decimal(_)
172        | Value::Bool(_)
173        | Value::None
174        | Value::Object(_)
175        | Value::Function(_)
176        | Value::Class(_)
177        | Value::BoundMethod(_)
178        | Value::Error(_)
179        | Value::Socket(_)
180        | Value::Pup(_)
181        | Value::Bowl(_) => {
182            return Err(DogeError::type_error(format!(
183                "in wants a List, Dict, Str, or Bytes on the right, not {}",
184                container.describe()
185            )));
186        }
187    };
188    Ok(Value::Bool(found))
189}
190
191/// `needle not in container` — the negation of [`in_`], sharing its type rules so
192/// `x not in xs` and `not (x in xs)` always agree.
193pub fn not_in(needle: Value, container: Value) -> DogeResult {
194    match in_(needle, container)? {
195        Value::Bool(found) => Ok(Value::Bool(!found)),
196        _ => unreachable!("in_ always yields a Bool"),
197    }
198}
199
200/// Ordering for `< <= > >=`: numbers compare across Int/Float, Str compares
201/// lexicographically, anything else is a type error. The list `sort` method
202/// reuses this so its ordering matches the comparison operators exactly.
203pub(crate) fn order(a: &Value, b: &Value) -> DogeResult<Ordering> {
204    if is_numeric(a) && is_numeric(b) {
205        return numeric_cmp(a, b).ok_or_else(|| {
206            DogeError::type_error(format!(
207                "cannot compare {} and {}",
208                a.describe(),
209                b.describe()
210            ))
211        });
212    }
213    if let (Value::Str(x), Value::Str(y)) = (a, b) {
214        return Ok(x.as_ref().cmp(y.as_ref()));
215    }
216    if let (Value::Bytes(x), Value::Bytes(y)) = (a, b) {
217        return Ok(x.as_ref().cmp(y.as_ref()));
218    }
219    Err(DogeError::type_error(format!(
220        "cannot compare {} and {}",
221        a.describe(),
222        b.describe()
223    )))
224}
225
226/// `<`.
227pub fn lt(a: Value, b: Value) -> DogeResult {
228    Ok(Value::Bool(order(&a, &b)? == Ordering::Less))
229}
230
231/// `<=`.
232pub fn le(a: Value, b: Value) -> DogeResult {
233    Ok(Value::Bool(matches!(
234        order(&a, &b)?,
235        Ordering::Less | Ordering::Equal
236    )))
237}
238
239/// `>`.
240pub fn gt(a: Value, b: Value) -> DogeResult {
241    Ok(Value::Bool(order(&a, &b)? == Ordering::Greater))
242}
243
244/// `>=`.
245pub fn ge(a: Value, b: Value) -> DogeResult {
246    Ok(Value::Bool(matches!(
247        order(&a, &b)?,
248        Ordering::Greater | Ordering::Equal
249    )))
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn bytes_membership_subslice_and_ordering() {
258        let hay = Value::bytes([104, 105, 33]);
259        // `int in bytes` is byte membership; a value outside 0..=255 is simply absent.
260        assert!(matches!(
261            in_(Value::int(105), hay.clone()).unwrap(),
262            Value::Bool(true)
263        ));
264        assert!(matches!(
265            in_(Value::int(200), hay.clone()).unwrap(),
266            Value::Bool(false)
267        ));
268        assert!(matches!(
269            in_(Value::int(999), hay.clone()).unwrap(),
270            Value::Bool(false)
271        ));
272        // `bytes in bytes` is a contiguous sub-slice.
273        assert!(matches!(
274            in_(Value::bytes([105, 33]), hay.clone()).unwrap(),
275            Value::Bool(true)
276        ));
277        assert!(matches!(
278            in_(Value::bytes([104, 33]), hay.clone()).unwrap(),
279            Value::Bool(false)
280        ));
281        // Ordering is byte-wise.
282        assert_eq!(
283            order(&Value::bytes([1, 2]), &Value::bytes([1, 3])).unwrap(),
284            Ordering::Less
285        );
286    }
287
288    #[test]
289    fn bound_methods_equal_only_on_the_same_receiver_and_name() {
290        let a = Value::object(0, "Shibe");
291        let b = Value::object(0, "Shibe");
292        // Same instance, same method → equal.
293        assert!(values_equal(
294            &Value::bound_method(a.clone(), "speak"),
295            &Value::bound_method(a.clone(), "speak"),
296        ));
297        // Same instance, different method → not equal.
298        assert!(!values_equal(
299            &Value::bound_method(a.clone(), "speak"),
300            &Value::bound_method(a.clone(), "wag"),
301        ));
302        // Different instances of the same class → not equal.
303        assert!(!values_equal(
304            &Value::bound_method(a, "speak"),
305            &Value::bound_method(b, "speak"),
306        ));
307    }
308}