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
24pub(crate) const MAX_CONST_DEPTH: usize = 128;
36
37pub(crate) const MAX_CONST_SIZE: usize = 1 << 16;
49pub use rune_macros::ToConstValue;
121
122impl 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
142pub 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
161pub fn to_const_value(value: impl ToConstValue) -> Result<ConstValueBuf, RuntimeError> {
174 value.to_const_value()
175}
176
177pub trait ToConstValue: Sized {
179 fn to_const_value(self) -> Result<ConstValueBuf, RuntimeError>;
181
182 #[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 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 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 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 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 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 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
283fn 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 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 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 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 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 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 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 pub(crate) fn to_value_with(&self, cx: &dyn ConstContext) -> Result<Value, RuntimeError> {
512 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 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 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 frames.try_push(open(FrameKind::Dynamic(rtti), fields)?)?;
639 index += 1;
640 } else {
641 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 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
804pub trait FromConstValue: Sized {
806 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 struct ConstConstructVtable;
849
850 pub struct ConstConstructImpl;
852
853 pub trait ConstConstruct {
859 #[doc(hidden)]
862 fn const_construct(&self, value: &ConstValue) -> Result<Value, RuntimeError>;
863
864 #[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 #[inline]
876 fn rtti(&self, _: Hash) -> Option<&Arc<Rtti>> {
877 None
878 }
879}
880
881impl dyn ConstContext + '_ {
882 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
896pub(crate) trait LookupRtti {
899 fn lookup_rtti(&self, hash: &Hash) -> Option<&Arc<Rtti>>;
900}
901
902pub(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}