rune/runtime/
const_value.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#[macro_use]
mod macros;

use core::any;
use core::cmp::Ordering;
use core::fmt;

use rust_alloc::sync::Arc;

use serde::{Deserialize, Serialize};

use crate as rune;
use crate::alloc::prelude::*;
use crate::alloc::{self, HashMap};
use crate::runtime;
use crate::{Hash, TypeHash};

use super::{
    Bytes, FromValue, Inline, Object, OwnedTuple, Repr, ToValue, Tuple, Type, TypeInfo, Value,
    VmErrorKind,
};

/// Derive for the [`ToConstValue`](trait@ToConstValue) trait.
pub use rune_macros::ToConstValue;

use super::{AnyTypeInfo, RuntimeError, VmIntegerRepr};

/// Cheap conversion trait to convert something infallibly into a [`ConstValue`].
pub trait IntoConstValue {
    /// Convert into a dynamic [`ConstValue`].
    #[doc(hidden)]
    fn into_const_value(self) -> alloc::Result<ConstValue>;
}

impl IntoConstValue for ConstValue {
    #[inline]
    fn into_const_value(self) -> alloc::Result<ConstValue> {
        Ok(self)
    }
}

impl IntoConstValue for &ConstValue {
    #[inline]
    fn into_const_value(self) -> alloc::Result<ConstValue> {
        self.try_clone()
    }
}

/// Convert something into a [`ConstValue`].
///
/// # Examples
///
/// ```
/// let value = rune::to_const_value((i32::MIN, u64::MAX))?;
/// let (a, b) = rune::from_const_value::<(i32, u64)>(value)?;
///
/// assert_eq!(a, i32::MIN);
/// assert_eq!(b, u64::MAX);
/// # Ok::<_, rune::support::Error>(())
/// ```
pub fn from_const_value<T>(value: impl IntoConstValue) -> Result<T, RuntimeError>
where
    T: FromConstValue,
{
    T::from_const_value(value.into_const_value()?)
}

/// Convert something into a [`ConstValue`].
///
/// # Examples
///
/// ```
/// let value = rune::to_const_value((i32::MIN, u64::MAX))?;
/// let (a, b) = rune::from_const_value::<(i32, u64)>(value)?;
///
/// assert_eq!(a, i32::MIN);
/// assert_eq!(b, u64::MAX);
/// # Ok::<_, rune::support::Error>(())
/// ```
pub fn to_const_value(value: impl ToConstValue) -> Result<ConstValue, RuntimeError> {
    value.to_const_value()
}

/// Convert a value into a constant value.
pub trait ToConstValue: Sized {
    /// Convert into a constant value.
    fn to_const_value(self) -> Result<ConstValue, RuntimeError>;

    /// Return the constant constructor for the given type.
    #[inline]
    fn construct() -> Option<Arc<dyn ConstConstruct>> {
        None
    }
}

impl ToConstValue for ConstValue {
    #[inline]
    fn to_const_value(self) -> Result<ConstValue, RuntimeError> {
        Ok(self)
    }
}

impl ToConstValue for Value {
    #[inline]
    fn to_const_value(self) -> Result<ConstValue, RuntimeError> {
        ConstValue::from_value_ref(&self)
    }
}

#[derive(Debug, TryClone, Deserialize, Serialize)]
pub(crate) enum ConstValueKind {
    /// An inline constant value.
    Inline(#[try_clone(copy)] Inline),
    /// A string constant designated by its slot.
    String(String),
    /// A byte string.
    Bytes(Bytes),
    /// A vector of values.
    Vec(Vec<ConstValue>),
    /// An anonymous tuple.
    Tuple(Box<[ConstValue]>),
    /// An anonymous object.
    Object(HashMap<String, ConstValue>),
    /// An option.
    Option(Option<Box<ConstValue>>),
    /// A struct with the given type.
    Struct(Hash, Box<[ConstValue]>),
}

impl ConstValueKind {
    fn type_info(&self) -> TypeInfo {
        fn full_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "constant struct")
        }

        match self {
            ConstValueKind::Inline(value) => value.type_info(),
            ConstValueKind::String(..) => TypeInfo::any::<String>(),
            ConstValueKind::Bytes(..) => TypeInfo::any::<Bytes>(),
            ConstValueKind::Vec(..) => TypeInfo::any::<runtime::Vec>(),
            ConstValueKind::Tuple(..) => TypeInfo::any::<OwnedTuple>(),
            ConstValueKind::Object(..) => TypeInfo::any::<Object>(),
            ConstValueKind::Option(..) => TypeInfo::any::<Option<Value>>(),
            ConstValueKind::Struct(hash, ..) => {
                TypeInfo::any_type_info(AnyTypeInfo::new(full_name, *hash))
            }
        }
    }
}

/// A constant value.
#[derive(Deserialize, Serialize)]
#[serde(transparent)]
pub struct ConstValue {
    kind: ConstValueKind,
}

impl ConstValue {
    /// Construct a new tuple constant value.
    pub fn tuple(values: Box<[ConstValue]>) -> ConstValue {
        ConstValue {
            kind: ConstValueKind::Tuple(values),
        }
    }

    /// Construct a constant value for a struct.
    pub fn for_struct<const N: usize>(
        hash: Hash,
        fields: [ConstValue; N],
    ) -> Result<ConstValue, RuntimeError> {
        let fields = Box::<[ConstValue]>::try_from(fields)?;

        Ok(ConstValue {
            kind: ConstValueKind::Struct(hash, fields),
        })
    }

    /// Try to coerce the current value as the specified integer `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// let value = rune::to_const_value(u32::MAX)?;
    ///
    /// assert_eq!(value.as_integer::<u64>()?, u32::MAX as u64);
    /// assert!(value.as_integer::<i32>().is_err());
    ///
    /// # Ok::<(), rune::support::Error>(())
    /// ```
    pub fn as_integer<T>(&self) -> Result<T, RuntimeError>
    where
        T: TryFrom<i64> + TryFrom<u64>,
    {
        match self.kind {
            ConstValueKind::Inline(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>(),
                    },
                )),
            },
            ConstValueKind::Inline(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>(),
                    },
                )),
            },
            ref kind => Err(RuntimeError::new(VmErrorKind::ExpectedNumber {
                actual: kind.type_info(),
            })),
        }
    }

    inline_macros!(inline_into);

    /// Coerce into tuple.
    #[inline]
    pub fn into_tuple(self) -> Result<Box<[ConstValue]>, RuntimeError> {
        match self.kind {
            ConstValueKind::Tuple(tuple) => Ok(tuple),
            kind => Err(RuntimeError::expected::<Tuple>(kind.type_info())),
        }
    }

    /// Access the interior value.
    pub(crate) fn as_kind(&self) -> &ConstValueKind {
        &self.kind
    }

    /// Construct a constant value from a reference to a value..
    pub(crate) fn from_value_ref(value: &Value) -> Result<ConstValue, RuntimeError> {
        let inner = match value.as_ref() {
            Repr::Inline(value) => ConstValueKind::Inline(*value),
            Repr::Dynamic(value) => {
                return Err(RuntimeError::from(VmErrorKind::ConstNotSupported {
                    actual: value.type_info(),
                }));
            }
            Repr::Any(value) => match value.type_hash() {
                Option::<Value>::HASH => {
                    let option = value.borrow_ref::<Option<Value>>()?;

                    ConstValueKind::Option(match &*option {
                        Some(some) => Some(Box::try_new(Self::from_value_ref(some)?)?),
                        None => None,
                    })
                }
                String::HASH => {
                    let s = value.borrow_ref::<String>()?;
                    ConstValueKind::String(s.try_to_owned()?)
                }
                Bytes::HASH => {
                    let s = value.borrow_ref::<Bytes>()?;
                    ConstValueKind::Bytes(s.try_to_owned()?)
                }
                runtime::Vec::HASH => {
                    let vec = value.borrow_ref::<runtime::Vec>()?;
                    let mut const_vec = Vec::try_with_capacity(vec.len())?;

                    for value in vec.iter() {
                        const_vec.try_push(Self::from_value_ref(value)?)?;
                    }

                    ConstValueKind::Vec(const_vec)
                }
                runtime::OwnedTuple::HASH => {
                    let tuple = value.borrow_ref::<runtime::OwnedTuple>()?;
                    let mut const_tuple = Vec::try_with_capacity(tuple.len())?;

                    for value in tuple.iter() {
                        const_tuple.try_push(Self::from_value_ref(value)?)?;
                    }

                    ConstValueKind::Tuple(const_tuple.try_into_boxed_slice()?)
                }
                Object::HASH => {
                    let object = value.borrow_ref::<Object>()?;
                    let mut const_object = HashMap::try_with_capacity(object.len())?;

                    for (key, value) in object.iter() {
                        let key = key.try_clone()?;
                        let value = Self::from_value_ref(value)?;
                        const_object.try_insert(key, value)?;
                    }

                    ConstValueKind::Object(const_object)
                }
                _ => {
                    return Err(RuntimeError::from(VmErrorKind::ConstNotSupported {
                        actual: value.type_info(),
                    }));
                }
            },
        };

        Ok(Self { kind: inner })
    }

    #[inline]
    #[cfg(test)]
    pub(crate) fn to_value(&self) -> Result<Value, RuntimeError> {
        self.to_value_with(&EmptyConstContext)
    }

    /// Convert into virtual machine value.
    ///
    /// We provide this associated method since a constant value can be
    /// converted into a value infallibly, which is not captured by the trait
    /// otherwise.
    pub(crate) fn to_value_with(&self, cx: &dyn ConstContext) -> Result<Value, RuntimeError> {
        match &self.kind {
            ConstValueKind::Inline(value) => Ok(Value::from(*value)),
            ConstValueKind::String(string) => Ok(Value::try_from(string.try_clone()?)?),
            ConstValueKind::Bytes(b) => Ok(Value::try_from(b.try_clone()?)?),
            ConstValueKind::Option(option) => Ok(Value::try_from(match option {
                Some(some) => Some(Self::to_value_with(some, cx)?),
                None => None,
            })?),
            ConstValueKind::Vec(vec) => {
                let mut v = runtime::Vec::with_capacity(vec.len())?;

                for value in vec {
                    v.push(Self::to_value_with(value, cx)?)?;
                }

                Ok(Value::try_from(v)?)
            }
            ConstValueKind::Tuple(tuple) => {
                let mut t = Vec::try_with_capacity(tuple.len())?;

                for value in tuple.iter() {
                    t.try_push(Self::to_value_with(value, cx)?)?;
                }

                Ok(Value::try_from(OwnedTuple::try_from(t)?)?)
            }
            ConstValueKind::Object(object) => {
                let mut o = Object::with_capacity(object.len())?;

                for (key, value) in object {
                    let key = key.try_clone()?;
                    let value = Self::to_value_with(value, cx)?;
                    o.insert(key, value)?;
                }

                Ok(Value::try_from(o)?)
            }
            ConstValueKind::Struct(hash, fields) => {
                let Some(constructor) = cx.get(*hash) else {
                    return Err(RuntimeError::missing_constant_constructor(*hash));
                };

                constructor.const_construct(fields)
            }
        }
    }

    /// Get the type information of the value.
    pub(crate) fn type_info(&self) -> TypeInfo {
        self.kind.type_info()
    }
}

impl TryClone for ConstValue {
    fn try_clone(&self) -> alloc::Result<Self> {
        Ok(Self {
            kind: self.kind.try_clone()?,
        })
    }
}

impl FromValue for ConstValue {
    #[inline]
    fn from_value(value: Value) -> Result<Self, RuntimeError> {
        ConstValue::from_value_ref(&value)
    }
}

impl ToValue for ConstValue {
    #[inline]
    fn to_value(self) -> Result<Value, RuntimeError> {
        ConstValue::to_value_with(&self, &EmptyConstContext)
    }
}

impl From<ConstValueKind> for ConstValue {
    #[inline]
    fn from(kind: ConstValueKind) -> Self {
        Self { kind }
    }
}

impl From<Inline> for ConstValue {
    #[inline]
    fn from(value: Inline) -> Self {
        Self::from(ConstValueKind::Inline(value))
    }
}

impl From<String> for ConstValue {
    #[inline]
    fn from(value: String) -> Self {
        Self::from(ConstValueKind::String(value))
    }
}

impl From<Bytes> for ConstValue {
    #[inline]
    fn from(value: Bytes) -> Self {
        Self::from(ConstValueKind::Bytes(value))
    }
}

impl TryFrom<&str> for ConstValue {
    type Error = alloc::Error;

    #[inline]
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(ConstValue::from(String::try_from(value)?))
    }
}

impl ToConstValue for &str {
    #[inline]
    fn to_const_value(self) -> Result<ConstValue, RuntimeError> {
        Ok(ConstValue::try_from(self)?)
    }
}

impl TryFrom<&[u8]> for ConstValue {
    type Error = alloc::Error;

    #[inline]
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        Ok(ConstValue::from(Bytes::try_from(value)?))
    }
}

impl ToConstValue for &[u8] {
    #[inline]
    fn to_const_value(self) -> Result<ConstValue, RuntimeError> {
        Ok(ConstValue::try_from(self)?)
    }
}

impl fmt::Debug for ConstValue {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.kind.fmt(f)
    }
}

/// Convert a value from a constant value.
pub trait FromConstValue: Sized {
    /// Convert from a constant value.
    fn from_const_value(value: ConstValue) -> Result<Self, RuntimeError>;
}

impl FromConstValue for ConstValue {
    #[inline]
    fn from_const_value(value: ConstValue) -> Result<Self, RuntimeError> {
        Ok(value)
    }
}

/// Implementation of a constant constructor.
///
/// Do not implement manually, this is provided when deriving
/// [`ToConstValue`](derive@ToConstValue).
pub trait ConstConstruct: 'static + Send + Sync {
    /// Construct from values.
    #[doc(hidden)]
    fn const_construct(&self, fields: &[ConstValue]) -> Result<Value, RuntimeError>;

    /// Construct from values.
    #[doc(hidden)]
    fn runtime_construct(&self, fields: &mut [Value]) -> Result<Value, RuntimeError>;
}

pub(crate) trait ConstContext {
    fn get(&self, hash: Hash) -> Option<&dyn ConstConstruct>;
}

pub(crate) struct EmptyConstContext;

impl ConstContext for EmptyConstContext {
    #[inline]
    fn get(&self, _: Hash) -> Option<&dyn ConstConstruct> {
        None
    }
}