1use core::convert::Infallible;
2use core::fmt;
3
4use rust_alloc::boxed::Box;
5
6use crate::alloc::error::CustomError;
7use crate::alloc::{self, String};
8use crate::runtime::unit::{BadInstruction, BadJump};
9use crate::sync::Arc;
10use crate::{vm_error, Any, Hash, Item, ItemBuf};
11
12use super::{
13 AccessError, AnyObjError, AnyObjErrorKind, AnySequenceTakeError, BoxedPanic, CallFrame,
14 DynArgsUsed, ExecutionState, Panic, Protocol, SliceError, StackError, StaticString, StoreError,
15 StoreErrorKind, TypeInfo, TypeOf, Unit, Vm, VmHaltInfo,
16};
17
18macro_rules! from_new {
19 (
20 $($ty:ty { $($from:ty),* $(,)? })*
21 ) => {
22 $($(
23 impl From<$from> for $ty {
24 #[inline]
25 fn from(error: $from) -> Self {
26 Self::new(error)
27 }
28 }
29 )*)*
30 }
31}
32
33vm_error!(VmError);
34
35pub struct VmError {
37 inner: Box<VmErrorInner>,
38}
39
40impl VmError {
41 #[inline]
42 pub(crate) fn new<E>(error: E) -> Self
43 where
44 VmErrorKind: From<E>,
45 {
46 Self {
47 inner: Box::new(VmErrorInner {
48 error: VmErrorAt {
49 #[cfg(feature = "emit")]
50 index: 0,
51 kind: VmErrorKind::from(error),
52 },
53 chain: rust_alloc::vec::Vec::new(),
54 stacktrace: rust_alloc::vec::Vec::new(),
55 }),
56 }
57 }
58
59 #[inline]
61 pub fn panic<D>(message: D) -> Self
62 where
63 D: 'static + BoxedPanic,
64 {
65 Self::from(Panic::custom(message))
66 }
67
68 #[inline]
71 pub fn expected<E>(actual: TypeInfo) -> Self
72 where
73 E: ?Sized + TypeOf,
74 {
75 Self::from(VmErrorKind::expected::<E>(actual))
76 }
77
78 #[inline]
80 pub fn at(&self) -> &VmErrorAt {
81 &self.inner.error
82 }
83
84 #[inline]
86 pub fn error(&self) -> &VmErrorAt {
87 &self.inner.error
88 }
89
90 #[inline]
92 pub fn chain(&self) -> &[VmErrorAt] {
93 &self.inner.chain
94 }
95
96 #[inline]
98 pub fn stacktrace(&self) -> &[VmErrorLocation] {
99 &self.inner.stacktrace
100 }
101
102 #[inline]
104 pub fn overflow() -> Self {
105 Self::from(VmErrorKind::Overflow)
106 }
107
108 #[inline]
110 pub fn first_location(&self) -> Option<&VmErrorLocation> {
111 self.inner.stacktrace.first()
112 }
113
114 #[inline]
115 pub(crate) fn into_kind(self) -> VmErrorKind {
116 self.inner.error.kind
117 }
118
119 pub(crate) fn with_vm<T>(result: Result<T, Self>, vm: &Vm) -> Result<T, Self> {
121 match result {
122 Ok(ok) => Ok(ok),
123 Err(mut err) => {
124 err.inner.stacktrace.push(VmErrorLocation {
125 unit: vm.unit().clone(),
126 ip: vm.last_ip(),
127 frames: vm.call_frames().to_vec(),
128 });
129
130 Err(err)
131 }
132 }
133 }
134
135 #[inline]
137 pub(crate) fn with_error<E>(mut self, error: E) -> Self
138 where
139 VmErrorKind: From<E>,
140 {
141 #[cfg(feature = "emit")]
142 let index = self.inner.stacktrace.len();
143
144 self.inner.chain.push(VmErrorAt {
145 #[cfg(feature = "emit")]
146 index,
147 kind: VmErrorKind::from(error),
148 });
149
150 self
151 }
152}
153
154impl fmt::Display for VmError {
155 #[inline]
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 self.inner.error.fmt(f)
158 }
159}
160
161impl fmt::Debug for VmError {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 f.debug_struct("VmError")
164 .field("error", &self.inner.error)
165 .field("chain", &self.inner.chain)
166 .field("stacktrace", &self.inner.stacktrace)
167 .finish()
168 }
169}
170
171impl core::error::Error for VmError {}
172
173#[derive(Debug)]
175#[non_exhaustive]
176pub struct VmErrorLocation {
177 pub unit: Arc<Unit>,
179 pub ip: usize,
181 pub frames: rust_alloc::vec::Vec<CallFrame>,
183}
184
185#[derive(Debug)]
186#[non_exhaustive]
187pub struct VmErrorAt {
188 #[cfg(feature = "emit")]
190 index: usize,
191 kind: VmErrorKind,
193}
194
195impl VmErrorAt {
196 #[cfg(feature = "emit")]
198 pub(crate) fn index(&self) -> usize {
199 self.index
200 }
201
202 #[cfg(feature = "emit")]
203 pub(crate) fn kind(&self) -> &VmErrorKind {
204 &self.kind
205 }
206}
207
208impl fmt::Display for VmErrorAt {
209 #[inline]
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 self.kind.fmt(f)
212 }
213}
214
215#[non_exhaustive]
216pub(crate) struct VmErrorInner {
217 pub(crate) error: VmErrorAt,
218 pub(crate) chain: rust_alloc::vec::Vec<VmErrorAt>,
219 pub(crate) stacktrace: rust_alloc::vec::Vec<VmErrorLocation>,
220}
221
222#[deprecated = "Use `Result<T, VmError>` directly instead."]
224pub type VmResult<T> = Result<T, VmError>;
225
226impl<E> From<E> for VmError
227where
228 VmErrorKind: From<E>,
229{
230 #[inline]
231 fn from(error: E) -> Self {
232 Self::new(error)
233 }
234}
235
236impl<E> From<CustomError<E>> for VmError
237where
238 VmError: From<E>,
239{
240 #[inline]
241 fn from(error: CustomError<E>) -> Self {
242 match error {
243 CustomError::Custom(error) => Self::from(error),
244 CustomError::Error(error) => VmError::new(error),
245 }
246 }
247}
248
249impl<const N: usize> From<[VmErrorKind; N]> for VmError {
250 fn from(kinds: [VmErrorKind; N]) -> Self {
251 let mut it = kinds.into_iter();
252
253 let Some(first) = it.next() else {
254 return VmError::panic("Cannot construct an empty collection of errors");
255 };
256
257 let mut chain = rust_alloc::vec::Vec::with_capacity(it.len());
258
259 for kind in it {
260 chain.push(VmErrorAt {
261 #[cfg(feature = "emit")]
262 index: 0,
263 kind,
264 });
265 }
266
267 Self {
268 inner: Box::new(VmErrorInner {
269 error: VmErrorAt {
270 #[cfg(feature = "emit")]
271 index: 0,
272 kind: first,
273 },
274 chain,
275 stacktrace: rust_alloc::vec::Vec::new(),
276 }),
277 }
278 }
279}
280
281impl From<Panic> for VmErrorKind {
282 #[inline]
283 fn from(reason: Panic) -> Self {
284 VmErrorKind::Panic { reason }
285 }
286}
287
288impl From<ExpectedType> for VmErrorKind {
289 #[inline]
290 fn from(expected: ExpectedType) -> Self {
291 VmErrorKind::ExpectedType {
292 expected: expected.expected,
293 actual: expected.actual,
294 }
295 }
296}
297
298pub struct ExpectedType {
300 pub(crate) expected: TypeInfo,
301 pub(crate) actual: TypeInfo,
302}
303
304impl ExpectedType {
305 pub(crate) fn new<T>(actual: TypeInfo) -> Self
307 where
308 T: ?Sized + TypeOf,
309 {
310 Self {
311 expected: T::type_info(),
312 actual,
313 }
314 }
315}
316
317vm_error!(RuntimeError);
318
319#[cfg_attr(test, derive(PartialEq))]
321pub struct RuntimeError {
322 error: Box<VmErrorKind>,
323}
324
325impl RuntimeError {
326 #[inline]
327 pub(crate) fn new<E>(error: E) -> Self
328 where
329 VmErrorKind: From<E>,
330 {
331 Self {
332 error: Box::new(VmErrorKind::from(error)),
333 }
334 }
335
336 #[inline]
337 pub(crate) fn into_vm_error_kind(self) -> VmErrorKind {
338 *self.error
339 }
340
341 #[inline]
343 pub fn panic<D>(message: D) -> Self
344 where
345 D: 'static + BoxedPanic,
346 {
347 Self::new(Panic::custom(message))
348 }
349
350 pub fn bad_argument_count(actual: usize, expected: usize) -> Self {
352 Self::new(VmErrorKind::BadArgumentCount { actual, expected })
353 }
354
355 pub fn expected<T>(actual: TypeInfo) -> Self
357 where
358 T: ?Sized + TypeOf,
359 {
360 Self::new(VmErrorKind::ExpectedType {
361 expected: T::type_info(),
362 actual,
363 })
364 }
365
366 pub(crate) fn expected_any<T>(actual: TypeInfo) -> Self
368 where
369 T: Any,
370 {
371 Self::new(VmErrorKind::ExpectedType {
372 expected: TypeInfo::any::<T>(),
373 actual,
374 })
375 }
376
377 pub(crate) fn expected_any_obj(actual: TypeInfo) -> Self {
379 Self::new(VmErrorKind::ExpectedAny { actual })
380 }
381
382 pub(crate) fn missing_constant_constructor(hash: Hash) -> Self {
384 Self::new(VmErrorKind::MissingConstantConstructor { hash })
385 }
386
387 pub(crate) fn expected_empty(actual: TypeInfo) -> Self {
388 Self::new(VmErrorKind::ExpectedEmpty { actual })
389 }
390
391 pub(crate) fn expected_tuple(actual: TypeInfo) -> Self {
392 Self::new(VmErrorKind::ExpectedTuple { actual })
393 }
394
395 pub(crate) fn expected_struct(actual: TypeInfo) -> Self {
396 Self::new(VmErrorKind::ExpectedStruct { actual })
397 }
398}
399
400impl core::error::Error for RuntimeError {}
401
402impl fmt::Display for RuntimeError {
403 #[inline]
404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 self.error.fmt(f)
406 }
407}
408
409impl fmt::Debug for RuntimeError {
410 #[inline]
411 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412 self.error.fmt(f)
413 }
414}
415
416impl From<VmError> for RuntimeError {
417 #[inline]
418 fn from(error: VmError) -> Self {
419 Self::new(error.into_kind())
420 }
421}
422
423impl From<Infallible> for RuntimeError {
424 #[inline]
425 fn from(error: Infallible) -> Self {
426 match error {}
427 }
428}
429
430from_new! {
431 RuntimeError {
432 alloc::Error,
433 alloc::alloc::AllocError,
434 AccessError,
435 AnySequenceTakeError,
436 AnyObjError,
437 StackError,
438 VmErrorKind,
439 ExpectedType,
440 }
441}
442
443#[derive(Debug)]
445#[cfg_attr(test, derive(PartialEq))]
446#[doc(hidden)]
447pub(crate) enum VmErrorKind {
448 AllocError {
449 error: alloc::Error,
450 },
451 AccessError {
452 error: AccessError,
453 },
454 StackError {
455 error: StackError,
456 },
457 SliceError {
458 error: SliceError,
459 },
460 BadInstruction {
461 error: BadInstruction,
462 },
463 BadJump {
464 error: BadJump,
465 },
466 DynArgsUsed {
467 error: DynArgsUsed,
468 },
469 Panic {
470 reason: Panic,
471 },
472 NoRunningVm,
473 Halted {
474 halt: VmHaltInfo,
475 },
476 Overflow,
477 Underflow,
478 DivideByZero,
479 MissingEntry {
480 item: ItemBuf,
481 hash: Hash,
482 },
483 MissingEntryHash {
484 hash: Hash,
485 },
486 MissingFunction {
487 hash: Hash,
488 },
489 MissingDeclaredFunction {
490 item: ItemBuf,
491 hash: Hash,
492 },
493 MissingContextFunction {
494 hash: Hash,
495 },
496 NotOwned {
497 type_info: TypeInfo,
498 },
499 MissingProtocolFunction {
500 protocol: &'static Protocol,
501 instance: TypeInfo,
502 },
503 MissingInstanceFunction {
504 hash: Hash,
505 instance: TypeInfo,
506 },
507 IpOutOfBounds {
508 ip: usize,
509 length: usize,
510 },
511 UnsupportedBinaryOperation {
512 op: &'static str,
513 lhs: TypeInfo,
514 rhs: TypeInfo,
515 },
516 UnsupportedUnaryOperation {
517 op: &'static str,
518 operand: TypeInfo,
519 },
520 MissingStaticString {
521 slot: usize,
522 },
523 MissingStaticBytes {
524 slot: usize,
525 },
526 MissingStaticObjectKeys {
527 slot: usize,
528 },
529 MissingDropSet {
530 set: usize,
531 },
532 MissingGlobals {
533 slot: usize,
534 name: Option<ItemBuf>,
535 },
536 BadGlobalSlot {
537 slot: usize,
538 name: Option<ItemBuf>,
539 },
540 UninitializedGlobal {
541 slot: usize,
542 name: Option<ItemBuf>,
543 },
544 MissingRtti {
545 hash: Hash,
546 },
547 BadArgumentCount {
548 actual: usize,
549 expected: usize,
550 },
551 MaxValueDepth {
557 max: usize,
558 },
559 MaxConstDepth {
565 max: usize,
566 },
567 MaxConstSize {
569 max: usize,
570 },
571 MalformedConstValue,
578 MaxExecutionDepth {
584 max: usize,
585 },
586 BadEnvironmentCount {
587 actual: usize,
588 expected: usize,
589 },
590 BadArgument {
591 arg: usize,
592 },
593 UnsupportedIndexSet {
594 target: TypeInfo,
595 index: TypeInfo,
596 value: TypeInfo,
597 },
598 UnsupportedIndexGet {
599 target: TypeInfo,
600 index: TypeInfo,
601 },
602 UnsupportedTupleIndexGet {
603 target: TypeInfo,
604 index: usize,
605 },
606 UnsupportedTupleIndexSet {
607 target: TypeInfo,
608 },
609 UnsupportedObjectSlotIndexGet {
610 target: TypeInfo,
611 field: Arc<StaticString>,
612 },
613 UnsupportedObjectSlotIndexSet {
614 target: TypeInfo,
615 field: Arc<StaticString>,
616 },
617 UnsupportedIs {
618 value: TypeInfo,
619 test_type: TypeInfo,
620 },
621 UnsupportedAs {
622 value: TypeInfo,
623 },
624 UnsupportedAsTarget {
625 value: TypeInfo,
626 },
627 UnsupportedCallFn {
628 actual: TypeInfo,
629 },
630 ObjectIndexMissing {
631 slot: usize,
632 },
633 MissingIndex {
634 target: TypeInfo,
635 },
636 MissingIndexInteger {
637 target: TypeInfo,
638 index: VmIntegerRepr,
639 },
640 MissingIndexKey {
641 target: TypeInfo,
642 },
643 OutOfRange {
644 index: VmIntegerRepr,
645 length: VmIntegerRepr,
646 },
647 UnsupportedTryOperand {
648 actual: TypeInfo,
649 },
650 UnsupportedIterRangeInclusive {
651 start: TypeInfo,
652 end: TypeInfo,
653 },
654 UnsupportedIterRangeFrom {
655 start: TypeInfo,
656 },
657 UnsupportedIterRange {
658 start: TypeInfo,
659 end: TypeInfo,
660 },
661 UnsupportedIterNextOperand {
662 actual: TypeInfo,
663 },
664 ExpectedType {
665 expected: TypeInfo,
666 actual: TypeInfo,
667 },
668 ExpectedAny {
669 actual: TypeInfo,
670 },
671 ExpectedNumber {
672 actual: TypeInfo,
673 },
674 ExpectedEmpty {
675 actual: TypeInfo,
676 },
677 ExpectedTuple {
678 actual: TypeInfo,
679 },
680 ExpectedStruct {
681 actual: TypeInfo,
682 },
683 MissingConstantConstructor {
684 hash: Hash,
685 },
686 ValueToIntegerCoercionError {
687 from: VmIntegerRepr,
688 to: &'static str,
689 },
690 IntegerToValueCoercionError {
691 from: VmIntegerRepr,
692 to: &'static str,
693 },
694 ExpectedTupleLength {
695 actual: usize,
696 expected: usize,
697 },
698 ExpectedVecLength {
699 actual: usize,
700 expected: usize,
701 },
702 ConstNotSupported {
703 actual: TypeInfo,
704 },
705 MissingInterfaceEnvironment,
706 ExpectedExitedExecutionState {
707 actual: ExecutionState,
708 },
709 GeneratorComplete,
710 FutureCompleted,
711 MissingVariant {
713 name: String,
714 },
715 MissingField {
716 target: TypeInfo,
717 field: String,
718 },
719 MissingVariantName,
720 MissingStructField {
721 target: &'static str,
722 name: &'static str,
723 },
724 MissingTupleIndex {
725 target: &'static str,
726 index: usize,
727 },
728 ExpectedVariant {
729 actual: TypeInfo,
730 },
731 UnsupportedObjectFieldGet {
732 target: TypeInfo,
733 },
734 IllegalFloatComparison {
735 lhs: f64,
736 rhs: f64,
737 },
738 IllegalFloatOperation {
739 value: f64,
740 },
741 MissingCallFrame,
742 IllegalFormat,
743}
744
745impl fmt::Display for VmErrorKind {
746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747 match self {
748 VmErrorKind::AllocError { error } => error.fmt(f),
749 VmErrorKind::AccessError { error } => error.fmt(f),
750 VmErrorKind::StackError { error } => error.fmt(f),
751 VmErrorKind::SliceError { error } => error.fmt(f),
752 VmErrorKind::BadInstruction { error } => error.fmt(f),
753 VmErrorKind::BadJump { error } => error.fmt(f),
754 VmErrorKind::DynArgsUsed { error } => error.fmt(f),
755 VmErrorKind::Panic { reason } => write!(f, "Panicked: {reason}"),
756 VmErrorKind::NoRunningVm => write!(f, "No running virtual machines"),
757 VmErrorKind::Halted { halt } => match halt {
762 VmHaltInfo::Limited => write!(f, "Exhausted the budget it was given"),
763 VmHaltInfo::Yielded => write!(
764 f,
765 "Yielded, but was called as if it could not - a generator has to be \
766 driven through an execution"
767 ),
768 VmHaltInfo::Awaited => write!(
769 f,
770 "Awaited, but was called as if it could not - an asynchronous function \
771 has to be called asynchronously"
772 ),
773 },
774 VmErrorKind::Overflow => write!(f, "Numerical overflow"),
775 VmErrorKind::Underflow => write!(f, "Numerical underflow"),
776 VmErrorKind::DivideByZero => write!(f, "Division by zero"),
777 VmErrorKind::MissingEntry { item, hash } => {
778 write!(f, "Missing entry `{item}` with hash `{hash}`")
779 }
780 VmErrorKind::MissingEntryHash { hash } => {
781 write!(f, "Missing entry with hash `{hash}`")
782 }
783 VmErrorKind::MissingFunction { hash } => {
784 write!(f, "Missing function with hash `{hash}`")
785 }
786 VmErrorKind::MissingDeclaredFunction { item, hash } => {
787 write!(
788 f,
789 "Function `{item}` (hash `{hash}`) is declared but not provided by the host"
790 )
791 }
792 VmErrorKind::MissingContextFunction { hash } => {
793 write!(f, "Missing context function with hash `{hash}`")
794 }
795 VmErrorKind::NotOwned { type_info } => {
796 write!(f, "Cannot use owned operations for {type_info}")
797 }
798 VmErrorKind::MissingProtocolFunction { protocol, instance } => {
799 write!(f, "Missing protocol function `{protocol}` for `{instance}`")
800 }
801 VmErrorKind::MissingInstanceFunction { hash, instance } => {
802 write!(f, "Missing instance function `{hash}` for `{instance}`")
803 }
804 VmErrorKind::IpOutOfBounds { ip, length } => write!(
805 f,
806 "Instruction pointer `{ip}` is out-of-bounds `0-{length}`",
807 ),
808 VmErrorKind::UnsupportedBinaryOperation { op, lhs, rhs } => {
809 write!(
810 f,
811 "Unsupported binary operation `{op}` on `{lhs}` and `{rhs}`",
812 )
813 }
814 VmErrorKind::UnsupportedUnaryOperation { op, operand } => {
815 write!(f, "Unsupported unary operation `{op}` on {operand}")
816 }
817 VmErrorKind::MissingStaticString { slot } => {
818 write!(f, "Static string slot {slot} does not exist")
819 }
820 VmErrorKind::MissingStaticBytes { slot } => {
821 write!(f, "Static bytes slot {slot} does not exist")
822 }
823 VmErrorKind::MissingStaticObjectKeys { slot } => {
824 write!(f, "Static object keys slot {slot} does not exist")
825 }
826 VmErrorKind::MissingDropSet { set } => {
827 write!(f, "Static drop set {set} does not exist")
828 }
829 VmErrorKind::MissingGlobals { slot, name } => {
830 write!(f, "No storage has been configured for the static ")?;
831 fmt_global(f, *slot, name.as_deref())
832 }
833 VmErrorKind::BadGlobalSlot { slot, name } => {
834 write!(f, "The configured storage has no slot for the static ")?;
835 fmt_global(f, *slot, name.as_deref())
836 }
837 VmErrorKind::UninitializedGlobal { slot, name } => {
838 write!(f, "Reading uninitialized static ")?;
839 fmt_global(f, *slot, name.as_deref())
840 }
841 VmErrorKind::MissingRtti { hash } => {
842 write!(f, "Missing runtime information for type with hash `{hash}`")
843 }
844 VmErrorKind::BadArgumentCount { actual, expected } => {
845 write!(f, "Wrong number of arguments {actual}, expected {expected}",)
846 }
847 VmErrorKind::MaxValueDepth { max } => {
848 write!(f, "Value is nested too deeply to walk, limit is {max}")
849 }
850 VmErrorKind::MaxConstSize { max } => {
851 write!(f, "Value is too large to be a constant, limit is {max}")
852 }
853 VmErrorKind::MalformedConstValue => {
854 write!(f, "Constant value is not a tree")
855 }
856 VmErrorKind::MaxConstDepth { max } => {
857 write!(
858 f,
859 "Value is nested too deeply to be a constant, limit is {max}"
860 )
861 }
862 VmErrorKind::MaxExecutionDepth { max } => {
863 write!(f, "Executions are nested too deeply, limit is {max}")
864 }
865 VmErrorKind::BadEnvironmentCount { actual, expected } => write!(
866 f,
867 "Wrong environment size `{actual}`, expected `{expected}`",
868 ),
869 VmErrorKind::BadArgument { arg } => write!(f, "Bad argument #{arg}"),
870 VmErrorKind::UnsupportedIndexSet {
871 target,
872 index,
873 value,
874 } => write!(
875 f,
876 "The index set operation `{target}[{index}] = {value}` is not supported",
877 ),
878 VmErrorKind::UnsupportedIndexGet { target, index } => write!(
879 f,
880 "The index get operation `{target}[{index}]` is not supported",
881 ),
882 VmErrorKind::UnsupportedTupleIndexGet { target, index } => write!(
883 f,
884 "The tuple index get {index} operation is not supported on `{target}`",
885 ),
886 VmErrorKind::UnsupportedTupleIndexSet { target } => write!(
887 f,
888 "The tuple index set operation is not supported on `{target}`",
889 ),
890 VmErrorKind::UnsupportedObjectSlotIndexGet { target, field } => {
891 write!(f, "Field `{field}` not available on `{target}`")
892 }
893 VmErrorKind::UnsupportedObjectSlotIndexSet { target, field } => {
894 write!(f, "Field `{field}` not available to set on `{target}`")
895 }
896 VmErrorKind::UnsupportedIs { value, test_type } => {
897 write!(f, "Operation `{value} is {test_type}` is not supported")
898 }
899 VmErrorKind::UnsupportedAs { value } => write!(
900 f,
901 "Type `{value}` cannot be converted with `as`, which only converts between `i64`, `u64` and `f64`"
902 ),
903 VmErrorKind::UnsupportedAsTarget { value } => write!(
908 f,
909 "Type `{value}` cannot be converted with `as` to that type, which only converts to `i64`, `u64` or `f64`"
910 ),
911 VmErrorKind::UnsupportedCallFn { actual } => write!(
912 f,
913 "Type `{actual}` cannot be called since it's not a function",
914 ),
915 VmErrorKind::ObjectIndexMissing { slot } => {
916 write!(f, "Missing index by static string slot `{slot}`")
917 }
918 VmErrorKind::MissingIndex { target } => {
919 write!(f, "Type `{target}` missing index")
920 }
921 VmErrorKind::MissingIndexInteger { target, index } => {
922 write!(f, "Type `{target}` missing integer index `{index}`")
923 }
924 VmErrorKind::MissingIndexKey { target } => {
925 write!(f, "Type `{target}` missing index")
926 }
927 VmErrorKind::OutOfRange { index, length } => write!(
928 f,
929 "Index out of bounds, the length is `{length}` but the index is `{index}`",
930 ),
931 VmErrorKind::UnsupportedTryOperand { actual } => {
932 write!(f, "Type `{actual}` is not supported as try operand")
933 }
934 VmErrorKind::UnsupportedIterRangeInclusive { start, end } => {
935 write!(f, "Cannot build an iterator out of {start}..={end}")
936 }
937 VmErrorKind::UnsupportedIterRangeFrom { start } => {
938 write!(f, "Cannot build an iterator out of {start}..")
939 }
940 VmErrorKind::UnsupportedIterRange { start, end } => {
941 write!(f, "Cannot build an iterator out of {start}..{end}")
942 }
943 VmErrorKind::UnsupportedIterNextOperand { actual } => {
944 write!(f, "Type `{actual}` is not supported as iter-next operand")
945 }
946 VmErrorKind::ExpectedType { expected, actual } => {
947 write!(f, "Expected type `{expected}` but found `{actual}`")
948 }
949 VmErrorKind::ExpectedAny { actual } => {
950 write!(f, "Expected `Any` type, but found `{actual}`")
951 }
952 VmErrorKind::ExpectedNumber { actual } => {
953 write!(f, "Expected number type, but found `{actual}`")
954 }
955 VmErrorKind::ExpectedEmpty { actual } => {
956 write!(f, "Expected empty, but found `{actual}`")
957 }
958 VmErrorKind::ExpectedTuple { actual } => {
959 write!(f, "Expected tuple, but found `{actual}`")
960 }
961 VmErrorKind::ExpectedStruct { actual } => {
962 write!(f, "Expected struct, but found `{actual}`")
963 }
964 VmErrorKind::MissingConstantConstructor { hash } => {
965 write!(f, "Missing constant constructor for type with hash {hash}")
966 }
967 VmErrorKind::ValueToIntegerCoercionError { from, to } => {
968 write!(f, "Failed to convert value `{from}` to integer `{to}`")
969 }
970 VmErrorKind::IntegerToValueCoercionError { from, to } => {
971 write!(f, "Failed to convert integer `{from}` to value `{to}`")
972 }
973 VmErrorKind::ExpectedTupleLength { actual, expected } => write!(
974 f,
975 "Expected a tuple of length `{expected}`, but found one with length `{actual}`",
976 ),
977 VmErrorKind::ExpectedVecLength { actual, expected } => write!(
978 f,
979 "Expected a vector of length `{expected}`, but found one with length `{actual}`",
980 ),
981 VmErrorKind::ConstNotSupported { actual } => {
982 write!(f, "Type `{actual}` can't be converted to a constant value")
983 }
984 VmErrorKind::MissingInterfaceEnvironment => {
985 write!(f, "Missing interface environment")
986 }
987 VmErrorKind::ExpectedExitedExecutionState { actual } => {
988 write!(f, "Expected exited execution state, but was {actual}")
989 }
990 VmErrorKind::GeneratorComplete => {
991 write!(f, "Cannot resume a generator that has completed")
992 }
993 VmErrorKind::FutureCompleted => write!(f, "Future already completed"),
994 VmErrorKind::MissingVariant { name } => write!(f, "No variant matching `{name}`"),
995 VmErrorKind::MissingField { target, field } => {
996 write!(f, "Missing field `{field}` on `{target}`")
997 }
998 VmErrorKind::MissingVariantName => {
999 write!(f, "missing variant name in runtime information")
1000 }
1001 VmErrorKind::MissingStructField { target, name } => write!(
1002 f,
1003 "missing dynamic field for struct field `{target}::{name}`",
1004 ),
1005 VmErrorKind::MissingTupleIndex { target, index } => write!(
1006 f,
1007 "missing dynamic index #{index} in tuple struct `{target}`",
1008 ),
1009 VmErrorKind::ExpectedVariant { actual } => {
1010 write!(f, "Expected an enum variant, but got `{actual}`")
1011 }
1012 VmErrorKind::UnsupportedObjectFieldGet { target } => write!(
1013 f,
1014 "The object field get operation is not supported on `{target}`",
1015 ),
1016 VmErrorKind::IllegalFloatComparison { lhs, rhs } => {
1017 write!(
1018 f,
1019 "Cannot perform a comparison of the floats {lhs} and {rhs}",
1020 )
1021 }
1022 VmErrorKind::IllegalFloatOperation { value } => {
1023 write!(f, "Cannot perform operation on float `{value}`")
1024 }
1025 VmErrorKind::MissingCallFrame => {
1026 write!(f, "Missing call frame for internal vm call")
1027 }
1028 VmErrorKind::IllegalFormat => {
1029 write!(f, "Value cannot be formatted")
1030 }
1031 }
1032 }
1033}
1034
1035impl From<Infallible> for VmErrorKind {
1036 #[inline]
1037 fn from(error: Infallible) -> Self {
1038 match error {}
1039 }
1040}
1041
1042impl<E> From<StoreError<E>> for VmErrorKind
1043where
1044 VmErrorKind: From<E>,
1045{
1046 #[inline]
1047 fn from(value: StoreError<E>) -> Self {
1048 match value.into_kind() {
1049 StoreErrorKind::Stack(error) => VmErrorKind::StackError { error },
1050 StoreErrorKind::Error(error) => VmErrorKind::from(error),
1051 StoreErrorKind::Alloc(error) => VmErrorKind::AllocError { error },
1052 }
1053 }
1054}
1055
1056impl From<RuntimeError> for VmErrorKind {
1057 #[inline]
1058 fn from(value: RuntimeError) -> Self {
1059 value.into_vm_error_kind()
1060 }
1061}
1062
1063impl From<AnySequenceTakeError> for VmErrorKind {
1064 #[inline]
1065 fn from(value: AnySequenceTakeError) -> Self {
1066 match value {
1067 AnySequenceTakeError::Access(error) => Self::from(error),
1068 AnySequenceTakeError::Alloc(error) => Self::from(error),
1069 }
1070 }
1071}
1072
1073impl From<AnyObjError> for VmErrorKind {
1074 #[inline]
1075 fn from(value: AnyObjError) -> Self {
1076 match value.into_kind() {
1077 AnyObjErrorKind::Alloc(error) => Self::from(error),
1078 AnyObjErrorKind::Cast(expected, actual) => VmErrorKind::ExpectedType {
1079 expected: TypeInfo::any_type_info(expected),
1080 actual,
1081 },
1082 AnyObjErrorKind::AccessError(error) => Self::from(error),
1083 AnyObjErrorKind::NotOwned(type_info) => VmErrorKind::NotOwned { type_info },
1084 }
1085 }
1086}
1087
1088impl From<AccessError> for VmErrorKind {
1089 #[inline]
1090 fn from(error: AccessError) -> Self {
1091 VmErrorKind::AccessError { error }
1092 }
1093}
1094
1095impl From<StackError> for VmErrorKind {
1096 #[inline]
1097 fn from(error: StackError) -> Self {
1098 VmErrorKind::StackError { error }
1099 }
1100}
1101
1102impl From<SliceError> for VmErrorKind {
1103 #[inline]
1104 fn from(error: SliceError) -> Self {
1105 VmErrorKind::SliceError { error }
1106 }
1107}
1108
1109impl From<BadInstruction> for VmErrorKind {
1110 #[inline]
1111 fn from(error: BadInstruction) -> Self {
1112 VmErrorKind::BadInstruction { error }
1113 }
1114}
1115
1116impl From<BadJump> for VmErrorKind {
1117 #[inline]
1118 fn from(error: BadJump) -> Self {
1119 VmErrorKind::BadJump { error }
1120 }
1121}
1122
1123impl From<DynArgsUsed> for VmErrorKind {
1124 #[inline]
1125 fn from(error: DynArgsUsed) -> Self {
1126 VmErrorKind::DynArgsUsed { error }
1127 }
1128}
1129
1130impl From<alloc::Error> for VmErrorKind {
1131 #[inline]
1132 fn from(error: alloc::Error) -> Self {
1133 VmErrorKind::AllocError { error }
1134 }
1135}
1136
1137impl From<alloc::alloc::AllocError> for VmErrorKind {
1138 #[inline]
1139 fn from(error: alloc::alloc::AllocError) -> Self {
1140 VmErrorKind::AllocError {
1141 error: error.into(),
1142 }
1143 }
1144}
1145
1146impl VmErrorKind {
1147 pub(crate) fn bad_argument(arg: usize) -> Self {
1149 Self::BadArgument { arg }
1150 }
1151
1152 pub(crate) fn expected<T>(actual: TypeInfo) -> Self
1154 where
1155 T: ?Sized + TypeOf,
1156 {
1157 Self::ExpectedType {
1158 expected: T::type_info(),
1159 actual,
1160 }
1161 }
1162}
1163
1164#[derive(Debug, Clone, Copy)]
1165#[cfg_attr(test, derive(PartialEq))]
1166enum VmIntegerReprKind {
1167 Signed(i128),
1168 Unsigned(u128),
1169 Isize(isize),
1170 Usize(usize),
1171}
1172
1173#[derive(Clone)]
1175#[cfg_attr(test, derive(PartialEq))]
1176pub(crate) struct VmIntegerRepr {
1177 kind: VmIntegerReprKind,
1178}
1179
1180impl VmIntegerRepr {
1181 #[inline]
1182 fn new(kind: VmIntegerReprKind) -> Self {
1183 Self { kind }
1184 }
1185}
1186
1187macro_rules! impl_from {
1188 ($($variant:ident => [$($ty:ty),* $(,)?]),* $(,)?) => {
1189 $($(
1190 impl From<$ty> for VmIntegerRepr {
1191 #[inline]
1192 fn from(value: $ty) -> Self {
1193 Self::new(VmIntegerReprKind::$variant(From::from(value)))
1194 }
1195 }
1196 )*)*
1197 };
1198}
1199
1200impl_from! {
1201 Signed => [i8, i16, i32, i64, i128],
1202 Unsigned => [u8, u16, u32, u64, u128],
1203 Isize => [isize],
1204 Usize => [usize],
1205}
1206
1207impl fmt::Display for VmIntegerRepr {
1208 #[inline]
1209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1210 match &self.kind {
1211 VmIntegerReprKind::Signed(value) => value.fmt(f),
1212 VmIntegerReprKind::Unsigned(value) => value.fmt(f),
1213 VmIntegerReprKind::Isize(value) => value.fmt(f),
1214 VmIntegerReprKind::Usize(value) => value.fmt(f),
1215 }
1216 }
1217}
1218
1219impl fmt::Debug for VmIntegerRepr {
1220 #[inline]
1221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1222 self.kind.fmt(f)
1223 }
1224}
1225
1226fn fmt_global(f: &mut fmt::Formatter<'_>, slot: usize, name: Option<&Item>) -> fmt::Result {
1229 match name {
1230 Some(name) => write!(f, "`{name}` (slot {slot})"),
1231 None => write!(f, "in slot {slot}"),
1232 }
1233}