From 5bd0e723c13b8a41bfba442bd8ef5351e31099e6 Mon Sep 17 00:00:00 2001 From: Griffin Smith Date: Sun, 23 Oct 2022 13:24:05 -0400 Subject: refactor(tvix/eval): Implement value comparison with a method Rather than implementing all of the interesting semantics of value comparison with a macro bound to the VM, implement the bulk of the logic with a method on Value itself that returns an Ordering, and then use the macro to implement the comparison against that Ordering. This has no functional change, but paves the way to implementing lexicographic comparison of list values, which is supported in the latest version of upstream nix. Change-Id: I8af1a020b41577021af5939f5edc160c407d4a9e Reviewed-on: https://cl.tvl.fyi/c/depot/+/7069 Autosubmit: grfn Tested-by: BuildkiteCI Reviewed-by: tazjin --- tvix/eval/src/value/mod.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'tvix/eval/src/value') diff --git a/tvix/eval/src/value/mod.rs b/tvix/eval/src/value/mod.rs index 14b1a5c6122e..82be292819ae 100644 --- a/tvix/eval/src/value/mod.rs +++ b/tvix/eval/src/value/mod.rs @@ -1,5 +1,6 @@ //! This module implements the backing representation of runtime //! values in the Nix language. +use std::cmp::Ordering; use std::ops::Deref; use std::path::PathBuf; use std::rc::Rc; @@ -348,6 +349,26 @@ impl Value { } } + /// Compare `self` against other using (fallible) Nix ordering semantics. + pub fn nix_cmp(&self, other: &Self) -> Result, ErrorKind> { + match (self, other) { + // same types + (Value::Integer(i1), Value::Integer(i2)) => Ok(i1.partial_cmp(i2)), + (Value::Float(f1), Value::Float(f2)) => Ok(f1.partial_cmp(f2)), + (Value::String(s1), Value::String(s2)) => Ok(s1.partial_cmp(s2)), + + // different types + (Value::Integer(i1), Value::Float(f2)) => Ok((*i1 as f64).partial_cmp(f2)), + (Value::Float(f1), Value::Integer(i2)) => Ok(f1.partial_cmp(&(*i2 as f64))), + + // unsupported types + (lhs, rhs) => Err(ErrorKind::Incomparable { + lhs: lhs.type_of(), + rhs: rhs.type_of(), + }), + } + } + /// Ensure `self` is forced if it is a thunk, and return a reference to the resulting value. pub(crate) fn force(&self, vm: &mut VM) -> Result { match self { -- cgit 1.4.1