rune/runtime/value/
inline.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use core::any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::Hash as _;

use musli::{Decode, Encode};
use serde::{Deserialize, Serialize};

use crate as rune;
use crate::hash::Hash;
use crate::runtime::{
    Hasher, OwnedTuple, Protocol, RuntimeError, Type, TypeInfo, VmErrorKind, VmIntegerRepr,
};
use crate::TypeHash;

/// An inline value.
#[derive(Clone, Copy, Encode, Decode, Deserialize, Serialize)]
pub enum Inline {
    /// An empty value.
    ///
    /// Note that this value *can not* be instantiated. Internally any
    /// operations over it will result in a type error, even when operating with
    /// itself.
    ///
    /// Some operations will return a "falsy" value, like type checks.
    Empty,
    /// The unit value.
    Unit,
    /// A boolean.
    Bool(bool),
    /// A character.
    Char(char),
    /// A number.
    Signed(i64),
    /// An unsigned number.
    Unsigned(u64),
    /// A float.
    Float(f64),
    /// A type hash. Describes a type in the virtual machine.
    Type(Type),
    /// Ordering.
    Ordering(
        #[musli(with = crate::musli::ordering)]
        #[serde(with = "crate::serde::ordering")]
        Ordering,
    ),
}

impl Inline {
    pub(crate) fn as_integer<T>(self) -> Result<T, RuntimeError>
    where
        T: TryFrom<u64> + TryFrom<i64>,
    {
        match self {
            Inline::Unsigned(value) => match value.try_into() {
                Ok(number) => Ok(number),
                Err(..) => Err(RuntimeError::new(
                    VmErrorKind::ValueToIntegerCoercionError {
                        from: VmIntegerRepr::from(value),
                        to: any::type_name::<T>(),
                    },
                )),
            },
            Inline::Signed(value) => match value.try_into() {
                Ok(number) => Ok(number),
                Err(..) => Err(RuntimeError::new(
                    VmErrorKind::ValueToIntegerCoercionError {
                        from: VmIntegerRepr::from(value),
                        to: any::type_name::<T>(),
                    },
                )),
            },
            ref value => Err(RuntimeError::new(VmErrorKind::ExpectedNumber {
                actual: value.type_info(),
            })),
        }
    }

    /// Perform a partial equality check over two inline values.
    pub(crate) fn partial_eq(&self, other: &Self) -> Result<bool, RuntimeError> {
        match (self, other) {
            (Inline::Unit, Inline::Unit) => Ok(true),
            (Inline::Bool(a), Inline::Bool(b)) => Ok(*a == *b),
            (Inline::Char(a), Inline::Char(b)) => Ok(*a == *b),
            (Inline::Signed(a), Inline::Signed(b)) => Ok(*a == *b),
            (Inline::Signed(a), rhs) => Ok(*a == rhs.as_integer::<i64>()?),
            (Inline::Unsigned(a), Inline::Unsigned(b)) => Ok(*a == *b),
            (Inline::Unsigned(a), rhs) => Ok(*a == rhs.as_integer::<u64>()?),
            (Inline::Float(a), Inline::Float(b)) => Ok(*a == *b),
            (Inline::Type(a), Inline::Type(b)) => Ok(*a == *b),
            (Inline::Ordering(a), Inline::Ordering(b)) => Ok(*a == *b),
            (lhs, rhs) => Err(RuntimeError::from(
                VmErrorKind::UnsupportedBinaryOperation {
                    op: Protocol::PARTIAL_EQ.name,
                    lhs: lhs.type_info(),
                    rhs: rhs.type_info(),
                },
            )),
        }
    }

    /// Perform a total equality check over two inline values.
    pub(crate) fn eq(&self, other: &Self) -> Result<bool, RuntimeError> {
        match (self, other) {
            (Inline::Unit, Inline::Unit) => Ok(true),
            (Inline::Bool(a), Inline::Bool(b)) => Ok(*a == *b),
            (Inline::Char(a), Inline::Char(b)) => Ok(*a == *b),
            (Inline::Unsigned(a), Inline::Unsigned(b)) => Ok(*a == *b),
            (Inline::Signed(a), Inline::Signed(b)) => Ok(*a == *b),
            (Inline::Float(a), Inline::Float(b)) => {
                let Some(ordering) = a.partial_cmp(b) else {
                    return Err(RuntimeError::new(VmErrorKind::IllegalFloatComparison {
                        lhs: *a,
                        rhs: *b,
                    }));
                };

                Ok(matches!(ordering, Ordering::Equal))
            }
            (Inline::Type(a), Inline::Type(b)) => Ok(*a == *b),
            (Inline::Ordering(a), Inline::Ordering(b)) => Ok(*a == *b),
            (lhs, rhs) => Err(RuntimeError::new(VmErrorKind::UnsupportedBinaryOperation {
                op: Protocol::EQ.name,
                lhs: lhs.type_info(),
                rhs: rhs.type_info(),
            })),
        }
    }

    /// Partial comparison implementation for inline.
    pub(crate) fn partial_cmp(&self, other: &Self) -> Result<Option<Ordering>, RuntimeError> {
        match (self, other) {
            (Inline::Unit, Inline::Unit) => Ok(Some(Ordering::Equal)),
            (Inline::Bool(lhs), Inline::Bool(rhs)) => Ok(lhs.partial_cmp(rhs)),
            (Inline::Char(lhs), Inline::Char(rhs)) => Ok(lhs.partial_cmp(rhs)),
            (Inline::Unsigned(lhs), Inline::Unsigned(rhs)) => Ok(lhs.partial_cmp(rhs)),
            (Inline::Unsigned(lhs), rhs) => {
                let rhs = rhs.as_integer::<u64>()?;
                Ok(lhs.partial_cmp(&rhs))
            }
            (Inline::Signed(lhs), Inline::Signed(rhs)) => Ok(lhs.partial_cmp(rhs)),
            (Inline::Signed(lhs), rhs) => {
                let rhs = rhs.as_integer::<i64>()?;
                Ok(lhs.partial_cmp(&rhs))
            }
            (Inline::Float(lhs), Inline::Float(rhs)) => Ok(lhs.partial_cmp(rhs)),
            (Inline::Type(lhs), Inline::Type(rhs)) => Ok(lhs.partial_cmp(rhs)),
            (Inline::Ordering(lhs), Inline::Ordering(rhs)) => Ok(lhs.partial_cmp(rhs)),
            (lhs, rhs) => Err(RuntimeError::from(
                VmErrorKind::UnsupportedBinaryOperation {
                    op: Protocol::PARTIAL_CMP.name,
                    lhs: lhs.type_info(),
                    rhs: rhs.type_info(),
                },
            )),
        }
    }

    /// Total comparison implementation for inline.
    pub(crate) fn cmp(&self, other: &Self) -> Result<Ordering, RuntimeError> {
        match (self, other) {
            (Inline::Unit, Inline::Unit) => Ok(Ordering::Equal),
            (Inline::Bool(a), Inline::Bool(b)) => Ok(a.cmp(b)),
            (Inline::Char(a), Inline::Char(b)) => Ok(a.cmp(b)),
            (Inline::Unsigned(a), Inline::Unsigned(b)) => Ok(a.cmp(b)),
            (Inline::Signed(a), Inline::Signed(b)) => Ok(a.cmp(b)),
            (Inline::Float(a), Inline::Float(b)) => {
                let Some(ordering) = a.partial_cmp(b) else {
                    return Err(RuntimeError::new(VmErrorKind::IllegalFloatComparison {
                        lhs: *a,
                        rhs: *b,
                    }));
                };

                Ok(ordering)
            }
            (Inline::Type(a), Inline::Type(b)) => Ok(a.cmp(b)),
            (Inline::Ordering(a), Inline::Ordering(b)) => Ok(a.cmp(b)),
            (lhs, rhs) => Err(RuntimeError::new(VmErrorKind::UnsupportedBinaryOperation {
                op: Protocol::CMP.name,
                lhs: lhs.type_info(),
                rhs: rhs.type_info(),
            })),
        }
    }

    /// Hash an inline value.
    pub(crate) fn hash(&self, hasher: &mut Hasher) -> Result<(), RuntimeError> {
        match self {
            Inline::Unsigned(value) => {
                value.hash(hasher);
            }
            Inline::Signed(value) => {
                value.hash(hasher);
            }
            // Care must be taken whan hashing floats, to ensure that `hash(v1)
            // === hash(v2)` if `eq(v1) === eq(v2)`. Hopefully we accomplish
            // this by rejecting NaNs and rectifying subnormal values of zero.
            Inline::Float(value) => {
                if value.is_nan() {
                    return Err(RuntimeError::new(VmErrorKind::IllegalFloatOperation {
                        value: *value,
                    }));
                }

                let zero = *value == 0.0;
                let value = ((zero as u8 as f64) * 0.0 + (!zero as u8 as f64) * *value).to_bits();
                value.hash(hasher);
            }
            operand => {
                return Err(RuntimeError::new(VmErrorKind::UnsupportedUnaryOperation {
                    op: Protocol::HASH.name,
                    operand: operand.type_info(),
                }));
            }
        }

        Ok(())
    }
}

impl fmt::Debug for Inline {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Inline::Empty => write!(f, "<empty>"),
            Inline::Unit => write!(f, "()"),
            Inline::Bool(value) => value.fmt(f),
            Inline::Char(value) => value.fmt(f),
            Inline::Unsigned(value) => value.fmt(f),
            Inline::Signed(value) => value.fmt(f),
            Inline::Float(value) => value.fmt(f),
            Inline::Type(value) => value.fmt(f),
            Inline::Ordering(value) => value.fmt(f),
        }
    }
}

impl Inline {
    pub(crate) fn type_info(&self) -> TypeInfo {
        match self {
            Inline::Empty => TypeInfo::empty(),
            Inline::Unit => TypeInfo::any::<OwnedTuple>(),
            Inline::Bool(..) => TypeInfo::named::<bool>(),
            Inline::Char(..) => TypeInfo::named::<char>(),
            Inline::Unsigned(..) => TypeInfo::named::<u64>(),
            Inline::Signed(..) => TypeInfo::named::<i64>(),
            Inline::Float(..) => TypeInfo::named::<f64>(),
            Inline::Type(..) => TypeInfo::named::<Type>(),
            Inline::Ordering(..) => TypeInfo::named::<Ordering>(),
        }
    }

    /// Get the type hash for the current value.
    ///
    /// One notable feature is that the type of a variant is its container
    /// *enum*, and not the type hash of the variant itself.
    pub(crate) fn type_hash(&self) -> Hash {
        match self {
            Inline::Empty => crate::hash!(::std::empty::Empty),
            Inline::Unit => OwnedTuple::HASH,
            Inline::Bool(..) => bool::HASH,
            Inline::Char(..) => char::HASH,
            Inline::Signed(..) => i64::HASH,
            Inline::Unsigned(..) => u64::HASH,
            Inline::Float(..) => f64::HASH,
            Inline::Type(..) => Type::HASH,
            Inline::Ordering(..) => Ordering::HASH,
        }
    }
}