Skip to main content

rune/runtime/
const_value.rs

1#[macro_use]
2mod macros;
3
4mod node;
5
6pub(crate) use self::node::{ConstBuilder, ConstNodeKind, ConstNodesError};
7pub use self::node::{ConstFields, ConstFieldsIter, ConstValue, ConstValueBuf};
8
9use core::any;
10use core::cmp::Ordering;
11
12use crate::alloc;
13use crate::alloc::prelude::*;
14use crate::runtime;
15use crate::{declare_dyn_trait, hash_in, Hash, TypeHash};
16
17use crate::sync::Arc;
18
19use super::{
20    AnySequence, Bytes, ExpectedType, FromValue, Inline, Object, OwnedTuple, Repr, Rtti, RttiKind,
21    RuntimeError, ToValue, Tuple, Type, Value, VmErrorKind, VmIntegerRepr,
22};
23
24/// How deeply a [`ConstValue`] is allowed to nest.
25///
26/// A constant is stored as one array rather than as a tree, so nesting no
27/// longer costs a native frame to build or to take apart. What it still costs
28/// is everything which has to *understand* the nesting - lowering a constant
29/// into instructions, turning one into a pattern - so how deep one may be is
30/// still bounded, and the bound is checked once, where the array is built or
31/// read back.
32///
33/// This is the ceiling the `max-const-depth` option is measured against. The
34/// option can lower the effective bound but not raise it past this.
35pub(crate) const MAX_CONST_DEPTH: usize = 128;
36
37/// How many values a [`ConstValue`] is allowed to be made of.
38///
39/// The value a constant is converted from shares what it is made of - a value
40/// used twice is one allocation pointed at twice - while a `ConstValue` is a
41/// tree which owns each of its parts outright. So converting one expands a graph
42/// into a tree, and a constant function which does nothing more suspicious than
43/// `let v = f(n - 1); [v, v]` produces a value which is linear to evaluate and
44/// exponential to convert. Depth does not catch it: that shape is only `n` deep.
45///
46/// Nothing else bounds it. `const-budget` bounds the instructions evaluation is
47/// allowed to run, and the doubling above needs a handful per level.
48pub(crate) const MAX_CONST_SIZE: usize = 1 << 16;
49/// Derive for the [`ToConstValue`] trait.
50///
51/// This is principally used for associated constants in native modules, since
52/// Rune has to be provided a constant-compatible method for constructing values
53/// of the given type.
54///
55/// [`ToConstValue`]: trait@crate::ToConstValue
56///
57/// # Examples
58///
59/// ```
60/// use rune::{docstring, Any, ContextError, Module, ToConstValue};
61///
62/// #[derive(Any, ToConstValue)]
63/// pub struct Duration {
64///     #[const_value(with = const_duration)]
65///     inner: std::time::Duration,
66/// }
67///
68/// mod const_duration {
69///     use rune::runtime::{ConstValue, ConstValueBuf, RuntimeError, Value};
70///     use std::time::Duration;
71///
72///     #[inline]
73///     pub(super) fn to_const_value(duration: Duration) -> Result<ConstValueBuf, RuntimeError> {
74///         let secs = duration.as_secs();
75///         let nanos = duration.subsec_nanos();
76///         rune::to_const_value((secs, nanos))
77///     }
78///
79///     #[inline]
80///     pub(super) fn from_const_value(value: &ConstValue) -> Result<Duration, RuntimeError> {
81///         let (secs, nanos) = rune::from_const_value::<(u64, u32)>(value)?;
82///         Ok(Duration::new(secs, nanos))
83///     }
84///
85///     #[inline]
86///     pub(super) fn from_value(value: Value) -> Result<Duration, RuntimeError> {
87///         let (secs, nanos) = rune::from_value::<(u64, u32)>(value)?;
88///         Ok(Duration::new(secs, nanos))
89///     }
90/// }
91///
92/// #[rune::module(::time)]
93/// pub fn module() -> Result<Module, ContextError> {
94///     let mut m = Module::from_meta(module__meta)?;
95///     m.ty::<Duration>()?;
96///
97///     m
98///         .constant(
99///             "SECOND",
100///             Duration {
101///                 inner: std::time::Duration::from_secs(1),
102///             },
103///         )
104///         .build_associated::<Duration>()?
105///         .docs(docstring! {
106///             /// The duration of one second.
107///             ///
108///             /// # Examples
109///             ///
110///             /// ```rune
111///             /// use time::Duration;
112///             ///
113///             /// let duration = Duration::SECOND;
114///             /// ```
115///         })?;
116///
117///     Ok(m)
118/// }
119/// ```
120pub use rune_macros::ToConstValue;
121
122/// An array which does not describe a constant within the limits is reported
123/// the way anything else the machine turns away is.
124impl From<ConstNodesError> for RuntimeError {
125    fn from(error: ConstNodesError) -> Self {
126        match error {
127            #[cfg(any(feature = "serde", feature = "musli02"))]
128            ConstNodesError::Empty | ConstNodesError::Malformed => {
129                RuntimeError::new(VmErrorKind::MalformedConstValue)
130            }
131            ConstNodesError::TooDeep { max } => {
132                RuntimeError::new(VmErrorKind::MaxConstDepth { max })
133            }
134            ConstNodesError::TooLarge { max } => {
135                RuntimeError::new(VmErrorKind::MaxConstSize { max })
136            }
137            ConstNodesError::Alloc(error) => RuntimeError::from(error),
138        }
139    }
140}
141
142/// Convert something into a [`ConstValueBuf`].
143///
144/// # Examples
145///
146/// ```
147/// let value = rune::to_const_value((i32::MIN, u64::MAX))?;
148/// let (a, b) = rune::from_const_value::<(i32, u64)>(&value)?;
149///
150/// assert_eq!(a, i32::MIN);
151/// assert_eq!(b, u64::MAX);
152/// # Ok::<_, rune::support::Error>(())
153/// ```
154pub fn from_const_value<T>(value: impl AsRef<ConstValue>) -> Result<T, RuntimeError>
155where
156    T: FromConstValue,
157{
158    T::from_const_value(value.as_ref())
159}
160
161/// Convert something into a [`ConstValueBuf`].
162///
163/// # Examples
164///
165/// ```
166/// let value = rune::to_const_value((i32::MIN, u64::MAX))?;
167/// let (a, b) = rune::from_const_value::<(i32, u64)>(&value)?;
168///
169/// assert_eq!(a, i32::MIN);
170/// assert_eq!(b, u64::MAX);
171/// # Ok::<_, rune::support::Error>(())
172/// ```
173pub fn to_const_value(value: impl ToConstValue) -> Result<ConstValueBuf, RuntimeError> {
174    value.to_const_value()
175}
176
177/// Trait to perform a conversion to a [`ConstValueBuf`].
178pub trait ToConstValue: Sized {
179    /// Convert into a constant value.
180    fn to_const_value(self) -> Result<ConstValueBuf, RuntimeError>;
181
182    /// Return the constant constructor for the given type.
183    #[inline]
184    #[doc(hidden)]
185    fn construct() -> alloc::Result<Option<ConstConstructImpl>> {
186        Ok(None)
187    }
188}
189
190impl ToConstValue for ConstValueBuf {
191    #[inline]
192    fn to_const_value(self) -> Result<ConstValueBuf, RuntimeError> {
193        Ok(self)
194    }
195}
196
197impl ToConstValue for &ConstValue {
198    #[inline]
199    fn to_const_value(self) -> Result<ConstValueBuf, RuntimeError> {
200        Ok(self.try_to_owned()?)
201    }
202}
203
204impl ToConstValue for Value {
205    #[inline]
206    fn to_const_value(self) -> Result<ConstValueBuf, RuntimeError> {
207        ConstValueBuf::from_value_ref(&self)
208    }
209}
210
211impl ConstValueBuf {
212    /// Construct a constant value that is a string.
213    pub fn string(value: impl AsRef<str>) -> Result<ConstValueBuf, RuntimeError> {
214        let value = alloc::Box::try_from(value.as_ref())?;
215        Ok(Self::from_kind(ConstNodeKind::String(value)))
216    }
217
218    /// Construct a constant value that is bytes.
219    pub fn bytes(value: impl AsRef<[u8]>) -> Result<ConstValueBuf, RuntimeError> {
220        let value = alloc::Box::try_from(value.as_ref())?;
221        Ok(Self::from_kind(ConstNodeKind::Bytes(value)))
222    }
223
224    /// Construct a new tuple constant value.
225    pub fn tuple<I>(fields: I) -> Result<ConstValueBuf, RuntimeError>
226    where
227        I: IntoIterator,
228        I::Item: AsRef<ConstValue>,
229        I::IntoIter: ExactSizeIterator,
230    {
231        Self::instance(OwnedTuple::HASH, Hash::EMPTY, fields)
232    }
233
234    /// Construct a constant value for a struct.
235    pub fn for_struct<const N: usize>(
236        hash: Hash,
237        fields: [ConstValueBuf; N],
238    ) -> Result<ConstValueBuf, RuntimeError> {
239        Self::instance(hash, Hash::EMPTY, fields)
240    }
241
242    /// Construct an instance of `hash` out of the constants it is made of,
243    /// which are laid down after it in the order they are given.
244    pub(crate) fn instance<I>(
245        hash: Hash,
246        variant_hash: Hash,
247        fields: I,
248    ) -> Result<ConstValueBuf, RuntimeError>
249    where
250        I: IntoIterator,
251        I::Item: AsRef<ConstValue>,
252        I::IntoIter: ExactSizeIterator,
253    {
254        let fields = fields.into_iter();
255
256        let mut builder = ConstBuilder::new();
257
258        let at = builder.open(ConstNodeKind::Instance {
259            hash,
260            variant_hash,
261            fields: fields.len() as u32,
262        })?;
263
264        for field in fields {
265            builder.extend(field.as_ref())?;
266        }
267
268        builder.close(at);
269        Ok(builder.build()?)
270    }
271
272    /// Construct a constant value from a reference to a value.
273    ///
274    /// The walk is bounded before it descends, which is what keeps a value
275    /// whose depth a script decided from costing a native frame per level.
276    pub(crate) fn from_value_ref(value: &Value) -> Result<ConstValueBuf, RuntimeError> {
277        let mut builder = ConstBuilder::new();
278        from_value_ref_at(value, 0, &mut builder)?;
279        Ok(builder.build()?)
280    }
281}
282
283/// Append the constant `value` describes to `builder`, having already descended
284/// `depth` levels into the value the conversion started at.
285fn from_value_ref_at(
286    value: &Value,
287    depth: usize,
288    builder: &mut ConstBuilder,
289) -> Result<(), RuntimeError> {
290    if depth >= MAX_CONST_DEPTH {
291        return Err(RuntimeError::new(VmErrorKind::MaxConstDepth {
292            max: MAX_CONST_DEPTH,
293        }));
294    }
295
296    // Counted here rather than per container so that what is bounded is
297    // what is actually built, whatever shape it is in.
298    if builder.len() >= MAX_CONST_SIZE {
299        return Err(RuntimeError::new(VmErrorKind::MaxConstSize {
300            max: MAX_CONST_SIZE,
301        }));
302    }
303
304    let depth = depth + 1;
305
306    match value.as_ref() {
307        Repr::Inline(value) => {
308            builder.leaf(ConstNodeKind::Inline(*value))?;
309        }
310        Repr::Dynamic(value) => {
311            // A script-defined struct, tuple struct or variant is stored as an
312            // instance of its type with its fields in declaration order, which is
313            // the order the value keeps them in. The names of the fields are not
314            // stored: they are the unit's, and are looked up in its type
315            // information wherever the constant is turned back into something.
316            let rtti = value.rtti();
317            let fields = value.borrow_ref()?;
318
319            let at = builder.open(ConstNodeKind::Instance {
320                hash: rtti.hash,
321                variant_hash: rtti.variant_hash,
322                fields: fields.len() as u32,
323            })?;
324
325            for value in fields.iter() {
326                from_value_ref_at(value, depth, builder)?;
327            }
328
329            builder.close(at);
330        }
331        Repr::Any(value) => match value.type_hash() {
332            alloc::String::HASH => {
333                let string = value.borrow_ref::<alloc::String>()?;
334                builder.leaf(ConstNodeKind::String(alloc::Box::try_from(
335                    string.as_str(),
336                )?))?;
337            }
338            Bytes::HASH => {
339                let bytes = value.borrow_ref::<Bytes>()?;
340                builder.leaf(ConstNodeKind::Bytes(alloc::Box::try_from(
341                    bytes.as_slice(),
342                )?))?;
343            }
344            OwnedTuple::HASH => {
345                let tuple = value.borrow_ref::<OwnedTuple>()?;
346
347                let at = builder.open(ConstNodeKind::Instance {
348                    hash: OwnedTuple::HASH,
349                    variant_hash: Hash::EMPTY,
350                    fields: tuple.len() as u32,
351                })?;
352
353                for value in tuple.iter() {
354                    from_value_ref_at(value, depth, builder)?;
355                }
356
357                builder.close(at);
358            }
359            Object::HASH => {
360                let object = value.borrow_ref::<Object>()?;
361
362                let mut keys = alloc::Vec::try_with_capacity(object.len())?;
363
364                for key in object.keys() {
365                    keys.try_push(alloc::Box::try_from(key.as_str())?)?;
366                }
367
368                // The keys are stored in the order they are read back in, so
369                // that nothing which walks a constant has to sort them again.
370                keys.sort();
371
372                let at = builder.open(ConstNodeKind::Object {
373                    keys: keys.try_clone()?.try_into_boxed_slice()?,
374                })?;
375
376                for key in keys.iter() {
377                    let Some(value) = object.get(key.as_ref()) else {
378                        return Err(RuntimeError::new(VmErrorKind::MalformedConstValue));
379                    };
380
381                    from_value_ref_at(value, depth, builder)?;
382                }
383
384                builder.close(at);
385            }
386            Option::<Value>::HASH => {
387                let option = value.borrow_ref::<Option<Value>>()?;
388
389                match &*option {
390                    Some(some) => {
391                        let at = builder.open(ConstNodeKind::Instance {
392                            hash: Option::<Value>::HASH,
393                            variant_hash: hash_in!(crate, ::std::option::Option::Some),
394                            fields: 1,
395                        })?;
396
397                        from_value_ref_at(some, depth, builder)?;
398                        builder.close(at);
399                    }
400                    None => {
401                        builder.leaf(ConstNodeKind::Instance {
402                            hash: Option::<Value>::HASH,
403                            variant_hash: hash_in!(crate, ::std::option::Option::None),
404                            fields: 0,
405                        })?;
406                    }
407                }
408            }
409            runtime::Vec::HASH => {
410                let vec = value.borrow_ref::<runtime::Vec>()?;
411
412                let at = builder.open(ConstNodeKind::Instance {
413                    hash: runtime::Vec::HASH,
414                    variant_hash: Hash::EMPTY,
415                    fields: vec.len() as u32,
416                })?;
417
418                for value in vec.iter() {
419                    from_value_ref_at(value, depth, builder)?;
420                }
421
422                builder.close(at);
423            }
424            _ => {
425                return Err(RuntimeError::from(VmErrorKind::ConstNotSupported {
426                    actual: value.type_info(),
427                }));
428            }
429        },
430    }
431
432    Ok(())
433}
434
435impl ConstValue {
436    /// Try to coerce the current value as the specified integer `T`.
437    ///
438    /// # Examples
439    ///
440    /// ```
441    /// let value = rune::to_const_value(u32::MAX)?;
442    ///
443    /// assert_eq!(value.as_integer::<u64>()?, u32::MAX as u64);
444    /// assert!(value.as_integer::<i32>().is_err());
445    ///
446    /// # Ok::<(), rune::support::Error>(())
447    /// ```
448    pub fn as_integer<T>(&self) -> Result<T, RuntimeError>
449    where
450        T: TryFrom<i64> + TryFrom<u64>,
451    {
452        match self.kind() {
453            ConstNodeKind::Inline(Inline::Signed(value)) => match (*value).try_into() {
454                Ok(number) => Ok(number),
455                Err(..) => Err(RuntimeError::new(
456                    VmErrorKind::ValueToIntegerCoercionError {
457                        from: VmIntegerRepr::from(*value),
458                        to: any::type_name::<T>(),
459                    },
460                )),
461            },
462            ConstNodeKind::Inline(Inline::Unsigned(value)) => match (*value).try_into() {
463                Ok(number) => Ok(number),
464                Err(..) => Err(RuntimeError::new(
465                    VmErrorKind::ValueToIntegerCoercionError {
466                        from: VmIntegerRepr::from(*value),
467                        to: any::type_name::<T>(),
468                    },
469                )),
470            },
471            kind => Err(RuntimeError::new(VmErrorKind::ExpectedNumber {
472                actual: kind.type_info(),
473            })),
474        }
475    }
476
477    inline_macros!(inline_into);
478
479    /// Coerce into the string this is, if it is one.
480    pub fn as_string(&self) -> Result<&str, ExpectedType> {
481        let ConstNodeKind::String(value) = self.kind() else {
482            return Err(ExpectedType::new::<alloc::String>(self.type_info()));
483        };
484
485        Ok(value)
486    }
487
488    /// Coerce into the fields of the tuple this is, if it is one.
489    pub fn as_tuple(&self) -> Result<ConstFields<'_>, ExpectedType> {
490        let ConstNodeKind::Instance {
491            hash: OwnedTuple::HASH,
492            variant_hash: Hash::EMPTY,
493            ..
494        } = self.kind()
495        else {
496            return Err(ExpectedType::new::<Tuple>(self.type_info()));
497        };
498
499        Ok(self.fields())
500    }
501
502    /// Convert into virtual machine value.
503    ///
504    /// We provide this associated method since a constant value can be
505    /// converted into a value infallibly, which is not captured by the trait
506    /// otherwise.
507    ///
508    /// The walk is a single pass over the array the constant is stored as, with
509    /// the containers which are part way through kept on a work stack, so a
510    /// constant which nests deeply costs memory rather than native frames.
511    pub(crate) fn to_value_with(&self, cx: &dyn ConstContext) -> Result<Value, RuntimeError> {
512        /// A container whose values are still being built.
513        struct Frame<'a> {
514            kind: FrameKind<'a>,
515            remaining: usize,
516            values: alloc::Vec<Value>,
517        }
518
519        enum FrameKind<'a> {
520            Tuple,
521            Vec,
522            Object(&'a [alloc::Box<str>]),
523            Some,
524            Dynamic(&'a Arc<Rtti>),
525        }
526
527        fn close(frame: Frame<'_>) -> Result<Value, RuntimeError> {
528            match frame.kind {
529                FrameKind::Tuple => Ok(Value::try_from(OwnedTuple::try_from(frame.values)?)?),
530                FrameKind::Vec => Ok(Value::try_from(runtime::Vec::from(frame.values))?),
531                FrameKind::Object(keys) => {
532                    let mut object = Object::with_capacity(keys.len())?;
533
534                    for (key, value) in keys.iter().zip(frame.values) {
535                        object.insert(alloc::String::try_from(key.as_ref())?, value)?;
536                    }
537
538                    Ok(Value::try_from(object)?)
539                }
540                FrameKind::Some => {
541                    let mut values = frame.values.into_iter();
542
543                    let Some(value) = values.next() else {
544                        return Err(RuntimeError::new(VmErrorKind::MalformedConstValue));
545                    };
546
547                    Ok(Value::try_from(Some(value))?)
548                }
549                FrameKind::Dynamic(rtti) => {
550                    Ok(Value::from(AnySequence::new(rtti.clone(), frame.values)?))
551                }
552            }
553        }
554
555        fn open<'a>(kind: FrameKind<'a>, len: usize) -> Result<Frame<'a>, RuntimeError> {
556            Ok(Frame {
557                kind,
558                remaining: len,
559                values: alloc::Vec::try_with_capacity(len)?,
560            })
561        }
562
563        let nodes = self.as_nodes();
564        let mut frames = alloc::Vec::<Frame<'_>>::new();
565        let mut index = 0;
566
567        loop {
568            let Some(node) = nodes.get(index) else {
569                return Err(RuntimeError::new(VmErrorKind::MalformedConstValue));
570            };
571
572            // What the node produces outright, if anything - a node which opens
573            // a container produces nothing until the container is closed.
574            let mut produced = None;
575
576            match &node.kind {
577                ConstNodeKind::Inline(value) => {
578                    produced = Some(Value::from(*value));
579                    index += 1;
580                }
581                ConstNodeKind::String(string) => {
582                    produced = Some(Value::try_from(string.as_ref())?);
583                    index += 1;
584                }
585                ConstNodeKind::Bytes(bytes) => {
586                    produced = Some(Value::try_from(bytes.as_ref())?);
587                    index += 1;
588                }
589                ConstNodeKind::Object { keys } => {
590                    frames.try_push(open(FrameKind::Object(keys), keys.len())?)?;
591                    index += 1;
592                }
593                ConstNodeKind::Instance {
594                    hash,
595                    variant_hash,
596                    fields,
597                } => {
598                    let fields = *fields as usize;
599
600                    match (*hash, *variant_hash) {
601                        (OwnedTuple::HASH, Hash::EMPTY) => {
602                            frames.try_push(open(FrameKind::Tuple, fields)?)?;
603                            index += 1;
604                        }
605                        (runtime::Vec::HASH, Hash::EMPTY) => {
606                            frames.try_push(open(FrameKind::Vec, fields)?)?;
607                            index += 1;
608                        }
609                        (Option::<Value>::HASH, variant_hash) => {
610                            match (variant_hash, fields) {
611                                (hash_in!(crate, ::std::option::Option::Some), 1) => {
612                                    frames.try_push(open(FrameKind::Some, 1)?)?;
613                                }
614                                (hash_in!(crate, ::std::option::Option::None), 0) => {
615                                    produced = Some(Value::try_from(None)?);
616                                }
617                                _ => {
618                                    return Err(RuntimeError::missing_constant_constructor(*hash));
619                                }
620                            }
621
622                            index += 1;
623                        }
624                        (hash, variant_hash) => {
625                            // A type declared in a script is rebuilt out of the
626                            // type information of the unit which declared it.
627                            if let Some(rtti) = cx.script_rtti(hash, variant_hash) {
628                                if matches!(rtti.kind, RttiKind::Struct)
629                                    && rtti.fields.len() != fields
630                                {
631                                    return Err(RuntimeError::new(
632                                        VmErrorKind::MalformedConstValue,
633                                    ));
634                                }
635
636                                // A container with no fields is closed as soon
637                                // as it is opened, like an empty tuple.
638                                frames.try_push(open(FrameKind::Dynamic(rtti), fields)?)?;
639                                index += 1;
640                            } else {
641                                // A type which is only known to whoever declared
642                                // it builds itself out of the constants it is
643                                // made of, so its subtree is handed over whole
644                                // rather than walked into here.
645                                let Some(constructor) = cx.get(hash) else {
646                                    return Err(RuntimeError::missing_constant_constructor(hash));
647                                };
648
649                                let size = node.size as usize;
650
651                                let Some(subtree) = nodes.get(index..index + size) else {
652                                    return Err(RuntimeError::new(
653                                        VmErrorKind::MalformedConstValue,
654                                    ));
655                                };
656
657                                produced = Some(
658                                    constructor.const_construct(ConstValue::from_nodes(subtree))?,
659                                );
660
661                                index += size;
662                            }
663                        }
664                    }
665                }
666            }
667
668            // Hand what was produced to the container which was waiting for it,
669            // and close every container which that completed.
670            loop {
671                if let Some(value) = produced.take() {
672                    let Some(frame) = frames.last_mut() else {
673                        return Ok(value);
674                    };
675
676                    frame.values.try_push(value)?;
677                    frame.remaining -= 1;
678                }
679
680                if !frames.last().is_some_and(|frame| frame.remaining == 0) {
681                    break;
682                }
683
684                let Some(frame) = frames.pop() else {
685                    break;
686                };
687
688                produced = Some(close(frame)?);
689            }
690        }
691    }
692}
693
694impl FromValue for ConstValueBuf {
695    #[inline]
696    fn from_value(value: Value) -> Result<Self, RuntimeError> {
697        ConstValueBuf::from_value_ref(&value)
698    }
699}
700
701impl ToValue for ConstValueBuf {
702    #[inline]
703    fn to_value(self) -> Result<Value, RuntimeError> {
704        ConstValue::to_value_with(&self, &EmptyConstContext)
705    }
706}
707
708impl ConstValue {
709    #[inline]
710    #[cfg(all(test, not(miri)))]
711    pub(crate) fn to_value(&self) -> Result<Value, RuntimeError> {
712        self.to_value_with(&EmptyConstContext)
713    }
714}
715
716impl AsRef<ConstValue> for ConstValue {
717    #[inline]
718    fn as_ref(&self) -> &ConstValue {
719        self
720    }
721}
722
723impl From<Inline> for ConstValueBuf {
724    #[inline]
725    fn from(value: Inline) -> Self {
726        ConstValueBuf::from_kind(ConstNodeKind::Inline(value))
727    }
728}
729
730impl TryFrom<alloc::String> for ConstValueBuf {
731    type Error = alloc::Error;
732
733    #[inline]
734    fn try_from(value: alloc::String) -> Result<Self, Self::Error> {
735        Ok(Self::from_kind(ConstNodeKind::String(
736            alloc::Box::try_from(value)?,
737        )))
738    }
739}
740
741impl TryFrom<alloc::Box<str>> for ConstValueBuf {
742    type Error = alloc::Error;
743
744    #[inline]
745    fn try_from(value: alloc::Box<str>) -> Result<Self, Self::Error> {
746        Ok(Self::from_kind(ConstNodeKind::String(value)))
747    }
748}
749
750impl TryFrom<Bytes> for ConstValueBuf {
751    type Error = alloc::Error;
752
753    #[inline]
754    fn try_from(value: Bytes) -> Result<Self, Self::Error> {
755        Self::try_from(value.as_slice())
756    }
757}
758
759impl TryFrom<&str> for ConstValueBuf {
760    type Error = alloc::Error;
761
762    #[inline]
763    fn try_from(value: &str) -> Result<Self, Self::Error> {
764        Ok(Self::from_kind(ConstNodeKind::String(
765            alloc::Box::try_from(value)?,
766        )))
767    }
768}
769
770impl ToConstValue for &str {
771    #[inline]
772    fn to_const_value(self) -> Result<ConstValueBuf, RuntimeError> {
773        Ok(ConstValueBuf::try_from(self)?)
774    }
775}
776
777impl TryFrom<alloc::Box<[u8]>> for ConstValueBuf {
778    type Error = alloc::Error;
779
780    #[inline]
781    fn try_from(value: alloc::Box<[u8]>) -> Result<Self, Self::Error> {
782        Ok(Self::from_kind(ConstNodeKind::Bytes(value)))
783    }
784}
785
786impl TryFrom<&[u8]> for ConstValueBuf {
787    type Error = alloc::Error;
788
789    #[inline]
790    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
791        Ok(Self::from_kind(ConstNodeKind::Bytes(alloc::Box::try_from(
792            value,
793        )?)))
794    }
795}
796
797impl ToConstValue for &[u8] {
798    #[inline]
799    fn to_const_value(self) -> Result<ConstValueBuf, RuntimeError> {
800        Ok(ConstValueBuf::try_from(self)?)
801    }
802}
803
804/// Trait to perform a conversion from a [`ConstValue`].
805pub trait FromConstValue: Sized {
806    /// Convert from a constant value.
807    fn from_const_value(value: &ConstValue) -> Result<Self, RuntimeError>;
808}
809
810impl FromConstValue for ConstValueBuf {
811    #[inline]
812    fn from_const_value(value: &ConstValue) -> Result<Self, RuntimeError> {
813        Ok(value.try_to_owned()?)
814    }
815}
816
817impl FromConstValue for bool {
818    #[inline]
819    fn from_const_value(value: &ConstValue) -> Result<Self, RuntimeError> {
820        value.as_bool()
821    }
822}
823
824impl FromConstValue for char {
825    #[inline]
826    fn from_const_value(value: &ConstValue) -> Result<Self, RuntimeError> {
827        value.as_char()
828    }
829}
830
831macro_rules! impl_integer {
832    ($($ty:ty),* $(,)?) => {
833        $(
834            impl FromConstValue for $ty {
835                #[inline]
836                fn from_const_value(value: &ConstValue) -> Result<Self, RuntimeError> {
837                    value.as_integer()
838                }
839            }
840        )*
841    };
842}
843
844impl_integer!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
845
846declare_dyn_trait! {
847    /// The vtable for constant constructors.
848    struct ConstConstructVtable;
849
850    /// The implementation wrapper for a constant constructor.
851    pub struct ConstConstructImpl;
852
853    /// Implementation of a constant constructor.
854    ///
855    /// Do not implement manually, this is provided when deriving [`ToConstValue`].
856    ///
857    /// [`ToConstValue`]: derive@ToConstValue
858    pub trait ConstConstruct {
859        /// Construct from the constant which describes the instance, whose
860        /// fields are the subtrees it is made of.
861        #[doc(hidden)]
862        fn const_construct(&self, value: &ConstValue) -> Result<Value, RuntimeError>;
863
864        /// Construct from values.
865        #[doc(hidden)]
866        fn runtime_construct(&self, fields: &mut [Value]) -> Result<Value, RuntimeError>;
867    }
868}
869
870pub(crate) trait ConstContext {
871    fn get(&self, hash: Hash) -> Option<&ConstConstructImpl>;
872
873    /// Look up the type information of a type declared in a script, keyed by
874    /// the item hash of the type or, for a variant, of the variant.
875    #[inline]
876    fn rtti(&self, _: Hash) -> Option<&Arc<Rtti>> {
877        None
878    }
879}
880
881impl dyn ConstContext + '_ {
882    /// The type information of the script type an instance with the given
883    /// hashes describes, if it is one.
884    fn script_rtti(&self, hash: Hash, variant_hash: Hash) -> Option<&Arc<Rtti>> {
885        let key = if variant_hash == Hash::EMPTY {
886            hash
887        } else {
888            variant_hash
889        };
890
891        let rtti = self.rtti(key)?;
892        rtti.is(hash, variant_hash).then_some(rtti)
893    }
894}
895
896/// Something which holds the type information of the types a script declares,
897/// which is a unit or a unit being built.
898pub(crate) trait LookupRtti {
899    fn lookup_rtti(&self, hash: &Hash) -> Option<&Arc<Rtti>>;
900}
901
902/// A [`ConstContext`] which can also rebuild the types a script declares, by
903/// looking them up in `unit`.
904pub(crate) struct UnitConstContext<'a, U: ?Sized> {
905    pub(crate) context: &'a dyn ConstContext,
906    pub(crate) unit: &'a U,
907}
908
909impl<U> ConstContext for UnitConstContext<'_, U>
910where
911    U: ?Sized + LookupRtti,
912{
913    #[inline]
914    fn get(&self, hash: Hash) -> Option<&ConstConstructImpl> {
915        self.context.get(hash)
916    }
917
918    #[inline]
919    fn rtti(&self, hash: Hash) -> Option<&Arc<Rtti>> {
920        self.unit.lookup_rtti(&hash)
921    }
922}
923
924pub(crate) struct EmptyConstContext;
925
926impl ConstContext for EmptyConstContext {
927    #[inline]
928    fn get(&self, _: Hash) -> Option<&ConstConstructImpl> {
929        None
930    }
931}