1use std::any::Any;
2use std::backtrace::Backtrace;
3use std::borrow::Cow;
4use std::{convert, fmt, mem, ops};
5
6use either::Either;
7use rustc_abi::{Align, Size, VariantIdx, WrappingRange};
8use rustc_data_structures::sync::Lock;
9use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, ErrorGuaranteed, IntoDiagArg};
10use rustc_macros::{HashStable, TyDecodable, TyEncodable};
11use rustc_session::CtfeBacktrace;
12use rustc_span::def_id::DefId;
13use rustc_span::{DUMMY_SP, Span, Symbol};
14
15use super::{AllocId, AllocRange, ConstAllocation, Pointer, Scalar};
16use crate::error;
17use crate::mir::{ConstAlloc, ConstValue};
18use crate::ty::{self, Mutability, Ty, TyCtxt, ValTree, layout, tls};
19
20#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
21pub enum ErrorHandled {
22 Reported(ReportedErrorInfo, Span),
25 TooGeneric(Span),
28}
29
30impl From<ReportedErrorInfo> for ErrorHandled {
31 #[inline]
32 fn from(error: ReportedErrorInfo) -> ErrorHandled {
33 ErrorHandled::Reported(error, DUMMY_SP)
34 }
35}
36
37impl ErrorHandled {
38 pub(crate) fn with_span(self, span: Span) -> Self {
39 match self {
40 ErrorHandled::Reported(err, _span) => ErrorHandled::Reported(err, span),
41 ErrorHandled::TooGeneric(_span) => ErrorHandled::TooGeneric(span),
42 }
43 }
44
45 pub fn emit_note(&self, tcx: TyCtxt<'_>) {
46 match self {
47 &ErrorHandled::Reported(err, span) => {
48 if !err.allowed_in_infallible && !span.is_dummy() {
49 tcx.dcx().emit_note(error::ErroneousConstant { span });
50 }
51 }
52 &ErrorHandled::TooGeneric(_) => {}
53 }
54 }
55}
56
57#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
58pub struct ReportedErrorInfo {
59 error: ErrorGuaranteed,
60 allowed_in_infallible: bool,
63}
64
65impl ReportedErrorInfo {
66 #[inline]
67 pub fn const_eval_error(error: ErrorGuaranteed) -> ReportedErrorInfo {
68 ReportedErrorInfo { allowed_in_infallible: false, error }
69 }
70
71 #[inline]
74 pub fn non_const_eval_error(error: ErrorGuaranteed) -> ReportedErrorInfo {
75 ReportedErrorInfo { allowed_in_infallible: true, error }
76 }
77
78 #[inline]
81 pub fn allowed_in_infallible(error: ErrorGuaranteed) -> ReportedErrorInfo {
82 ReportedErrorInfo { allowed_in_infallible: true, error }
83 }
84
85 pub fn is_allowed_in_infallible(&self) -> bool {
86 self.allowed_in_infallible
87 }
88}
89
90impl From<ReportedErrorInfo> for ErrorGuaranteed {
91 #[inline]
92 fn from(val: ReportedErrorInfo) -> Self {
93 val.error
94 }
95}
96
97#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
100pub enum ValTreeCreationError<'tcx> {
101 NodesOverflow,
103 InvalidConst,
105 NonSupportedType(Ty<'tcx>),
107 ErrorHandled(ErrorHandled),
109}
110
111impl<'tcx> From<ErrorHandled> for ValTreeCreationError<'tcx> {
112 fn from(err: ErrorHandled) -> Self {
113 ValTreeCreationError::ErrorHandled(err)
114 }
115}
116
117impl<'tcx> From<InterpErrorInfo<'tcx>> for ValTreeCreationError<'tcx> {
118 fn from(err: InterpErrorInfo<'tcx>) -> Self {
119 let (_kind, backtrace) = err.into_parts();
123 backtrace.print_backtrace();
124 ValTreeCreationError::InvalidConst
125 }
126}
127
128impl<'tcx> ValTreeCreationError<'tcx> {
129 pub(crate) fn with_span(self, span: Span) -> Self {
130 use ValTreeCreationError::*;
131 match self {
132 ErrorHandled(handled) => ErrorHandled(handled.with_span(span)),
133 other => other,
134 }
135 }
136}
137
138pub type EvalToAllocationRawResult<'tcx> = Result<ConstAlloc<'tcx>, ErrorHandled>;
139pub type EvalStaticInitializerRawResult<'tcx> = Result<ConstAllocation<'tcx>, ErrorHandled>;
140pub type EvalToConstValueResult<'tcx> = Result<ConstValue, ErrorHandled>;
141pub type EvalToValTreeResult<'tcx> = Result<ValTree<'tcx>, ValTreeCreationError<'tcx>>;
142
143#[cfg(target_pointer_width = "64")]
144rustc_data_structures::static_assert_size!(InterpErrorInfo<'_>, 8);
145
146#[derive(Debug)]
156pub struct InterpErrorInfo<'tcx>(Box<InterpErrorInfoInner<'tcx>>);
157
158#[derive(Debug)]
159struct InterpErrorInfoInner<'tcx> {
160 kind: InterpErrorKind<'tcx>,
161 backtrace: InterpErrorBacktrace,
162}
163
164#[derive(Debug)]
165pub struct InterpErrorBacktrace {
166 backtrace: Option<Box<Backtrace>>,
167}
168
169impl InterpErrorBacktrace {
170 pub fn new() -> InterpErrorBacktrace {
171 let capture_backtrace = tls::with_opt(|tcx| {
172 if let Some(tcx) = tcx {
173 *Lock::borrow(&tcx.sess.ctfe_backtrace)
174 } else {
175 CtfeBacktrace::Disabled
176 }
177 });
178
179 let backtrace = match capture_backtrace {
180 CtfeBacktrace::Disabled => None,
181 CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())),
182 CtfeBacktrace::Immediate => {
183 let backtrace = Backtrace::force_capture();
185 print_backtrace(&backtrace);
186 None
187 }
188 };
189
190 InterpErrorBacktrace { backtrace }
191 }
192
193 pub fn print_backtrace(&self) {
194 if let Some(backtrace) = self.backtrace.as_ref() {
195 print_backtrace(backtrace);
196 }
197 }
198}
199
200impl<'tcx> InterpErrorInfo<'tcx> {
201 pub fn into_parts(self) -> (InterpErrorKind<'tcx>, InterpErrorBacktrace) {
202 let InterpErrorInfo(box InterpErrorInfoInner { kind, backtrace }) = self;
203 (kind, backtrace)
204 }
205
206 pub fn into_kind(self) -> InterpErrorKind<'tcx> {
207 self.0.kind
208 }
209
210 pub fn from_parts(kind: InterpErrorKind<'tcx>, backtrace: InterpErrorBacktrace) -> Self {
211 Self(Box::new(InterpErrorInfoInner { kind, backtrace }))
212 }
213
214 #[inline]
215 pub fn kind(&self) -> &InterpErrorKind<'tcx> {
216 &self.0.kind
217 }
218}
219
220fn print_backtrace(backtrace: &Backtrace) {
221 eprintln!("\n\nAn error occurred in the MIR interpreter:\n{backtrace}");
222}
223
224impl From<ErrorHandled> for InterpErrorInfo<'_> {
225 fn from(err: ErrorHandled) -> Self {
226 InterpErrorKind::InvalidProgram(match err {
227 ErrorHandled::Reported(r, _span) => InvalidProgramInfo::AlreadyReported(r),
228 ErrorHandled::TooGeneric(_span) => InvalidProgramInfo::TooGeneric,
229 })
230 .into()
231 }
232}
233
234impl<'tcx> From<InterpErrorKind<'tcx>> for InterpErrorInfo<'tcx> {
235 fn from(kind: InterpErrorKind<'tcx>) -> Self {
236 InterpErrorInfo(Box::new(InterpErrorInfoInner {
237 kind,
238 backtrace: InterpErrorBacktrace::new(),
239 }))
240 }
241}
242
243#[derive(Debug)]
248pub enum InvalidProgramInfo<'tcx> {
249 TooGeneric,
251 AlreadyReported(ReportedErrorInfo),
253 Layout(layout::LayoutError<'tcx>),
255}
256
257#[derive(Debug, Copy, Clone)]
259pub enum CheckInAllocMsg {
260 MemoryAccess,
262 InboundsPointerArithmetic,
264 Dereferenceable,
266}
267
268#[derive(Debug, Copy, Clone)]
270pub enum CheckAlignMsg {
271 AccessedPtr,
273 BasedOn,
275}
276
277#[derive(Debug, Copy, Clone)]
278pub enum InvalidMetaKind {
279 SliceTooBig,
281 TooBig,
283}
284
285impl IntoDiagArg for InvalidMetaKind {
286 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
287 DiagArgValue::Str(Cow::Borrowed(match self {
288 InvalidMetaKind::SliceTooBig => "slice_too_big",
289 InvalidMetaKind::TooBig => "too_big",
290 }))
291 }
292}
293
294#[derive(Debug, Clone, Copy)]
296pub struct BadBytesAccess {
297 pub access: AllocRange,
299 pub bad: AllocRange,
301}
302
303#[derive(Debug)]
305pub struct ScalarSizeMismatch {
306 pub target_size: u64,
307 pub data_size: u64,
308}
309
310#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
312pub struct Misalignment {
313 pub has: Align,
314 pub required: Align,
315}
316
317macro_rules! impl_into_diag_arg_through_debug {
318 ($($ty:ty),*$(,)?) => {$(
319 impl IntoDiagArg for $ty {
320 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
321 DiagArgValue::Str(Cow::Owned(format!("{self:?}")))
322 }
323 }
324 )*}
325}
326
327impl_into_diag_arg_through_debug! {
329 AllocId,
330 Pointer<AllocId>,
331 AllocRange,
332}
333
334#[derive(Debug)]
336pub enum UndefinedBehaviorInfo<'tcx> {
337 Ub(String),
339 Custom(crate::error::CustomSubdiagnostic<'tcx>),
343 ValidationError(ValidationErrorInfo<'tcx>),
345
346 Unreachable,
348 BoundsCheckFailed { len: u64, index: u64 },
350 DivisionByZero,
352 RemainderByZero,
354 DivisionOverflow,
356 RemainderOverflow,
358 PointerArithOverflow,
360 ArithOverflow { intrinsic: Symbol },
362 ShiftOverflow { intrinsic: Symbol, shift_amount: Either<u128, i128> },
364 InvalidMeta(InvalidMetaKind),
366 UnterminatedCString(Pointer<AllocId>),
368 PointerUseAfterFree(AllocId, CheckInAllocMsg),
370 PointerOutOfBounds {
372 alloc_id: AllocId,
373 alloc_size: Size,
374 ptr_offset: i64,
375 inbounds_size: i64,
377 msg: CheckInAllocMsg,
378 },
379 DanglingIntPointer {
381 addr: u64,
382 inbounds_size: i64,
385 msg: CheckInAllocMsg,
386 },
387 AlignmentCheckFailed(Misalignment, CheckAlignMsg),
389 WriteToReadOnly(AllocId),
391 DerefFunctionPointer(AllocId),
393 DerefVTablePointer(AllocId),
395 DerefTypeIdPointer(AllocId),
397 InvalidBool(u8),
399 InvalidChar(u32),
401 InvalidTag(Scalar<AllocId>),
403 InvalidFunctionPointer(Pointer<AllocId>),
405 InvalidVTablePointer(Pointer<AllocId>),
407 InvalidVTableTrait {
409 vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
411 expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
413 },
414 InvalidStr(std::str::Utf8Error),
416 InvalidUninitBytes(Option<(AllocId, BadBytesAccess)>),
418 DeadLocal,
420 ScalarSizeMismatch(ScalarSizeMismatch),
422 UninhabitedEnumVariantWritten(VariantIdx),
424 UninhabitedEnumVariantRead(Option<VariantIdx>),
426 InvalidNichedEnumVariantWritten { enum_ty: Ty<'tcx> },
428 AbiMismatchArgument {
430 arg_idx: usize,
432 caller_ty: Ty<'tcx>,
433 callee_ty: Ty<'tcx>,
434 },
435 AbiMismatchReturn { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> },
437}
438
439#[derive(Debug, Clone, Copy)]
440pub enum PointerKind {
441 Ref(Mutability),
442 Box,
443}
444
445impl IntoDiagArg for PointerKind {
446 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
447 DiagArgValue::Str(
448 match self {
449 Self::Ref(_) => "ref",
450 Self::Box => "box",
451 }
452 .into(),
453 )
454 }
455}
456
457#[derive(Debug)]
458pub struct ValidationErrorInfo<'tcx> {
459 pub path: Option<String>,
460 pub kind: ValidationErrorKind<'tcx>,
461}
462
463#[derive(Debug)]
464pub enum ExpectedKind {
465 Reference,
466 Box,
467 RawPtr,
468 InitScalar,
469 Bool,
470 Char,
471 Float,
472 Int,
473 FnPtr,
474 EnumTag,
475 Str,
476}
477
478impl From<PointerKind> for ExpectedKind {
479 fn from(x: PointerKind) -> ExpectedKind {
480 match x {
481 PointerKind::Box => ExpectedKind::Box,
482 PointerKind::Ref(_) => ExpectedKind::Reference,
483 }
484 }
485}
486
487#[derive(Debug)]
488pub enum ValidationErrorKind<'tcx> {
489 PointerAsInt {
490 expected: ExpectedKind,
491 },
492 PartialPointer,
493 PtrToUninhabited {
494 ptr_kind: PointerKind,
495 ty: Ty<'tcx>,
496 },
497 MutableRefToImmutable,
498 UnsafeCellInImmutable,
499 MutableRefInConst,
500 NullFnPtr,
501 NeverVal,
502 NonnullPtrMaybeNull,
503 PtrOutOfRange {
504 range: WrappingRange,
505 max_value: u128,
506 },
507 OutOfRange {
508 value: String,
509 range: WrappingRange,
510 max_value: u128,
511 },
512 UninhabitedVal {
513 ty: Ty<'tcx>,
514 },
515 InvalidEnumTag {
516 value: String,
517 },
518 UninhabitedEnumVariant,
519 Uninit {
520 expected: ExpectedKind,
521 },
522 InvalidVTablePtr {
523 value: String,
524 },
525 InvalidMetaWrongTrait {
526 vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
528 expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
530 },
531 InvalidMetaSliceTooLarge {
532 ptr_kind: PointerKind,
533 },
534 InvalidMetaTooLarge {
535 ptr_kind: PointerKind,
536 },
537 UnalignedPtr {
538 ptr_kind: PointerKind,
539 required_bytes: u64,
540 found_bytes: u64,
541 },
542 NullPtr {
543 ptr_kind: PointerKind,
544 maybe: bool,
546 },
547 DanglingPtrNoProvenance {
548 ptr_kind: PointerKind,
549 pointer: String,
550 },
551 DanglingPtrOutOfBounds {
552 ptr_kind: PointerKind,
553 },
554 DanglingPtrUseAfterFree {
555 ptr_kind: PointerKind,
556 },
557 InvalidBool {
558 value: String,
559 },
560 InvalidChar {
561 value: String,
562 },
563 InvalidFnPtr {
564 value: String,
565 },
566}
567
568#[derive(Debug)]
573pub enum UnsupportedOpInfo {
574 Unsupported(String),
577 UnsizedLocal,
579 ExternTypeField,
581 ReadPartialPointer(Pointer<AllocId>),
587 ReadPointerAsInt(Option<(AllocId, BadBytesAccess)>),
589 ThreadLocalStatic(DefId),
591 ExternStatic(DefId),
593}
594
595#[derive(Debug)]
598pub enum ResourceExhaustionInfo {
599 StackFrameLimitReached,
601 MemoryExhausted,
603 AddressSpaceFull,
605 Interrupted,
607}
608
609pub trait MachineStopType: Any + fmt::Debug + Send {
611 fn diagnostic_message(&self) -> DiagMessage;
613 fn add_args(self: Box<Self>, adder: &mut dyn FnMut(DiagArgName, DiagArgValue));
616}
617
618impl dyn MachineStopType {
619 #[inline(always)]
620 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
621 let x: &dyn Any = self;
622 x.downcast_ref()
623 }
624}
625
626#[derive(Debug)]
627pub enum InterpErrorKind<'tcx> {
628 UndefinedBehavior(UndefinedBehaviorInfo<'tcx>),
630 Unsupported(UnsupportedOpInfo),
633 InvalidProgram(InvalidProgramInfo<'tcx>),
635 ResourceExhaustion(ResourceExhaustionInfo),
638 MachineStop(Box<dyn MachineStopType>),
641}
642
643impl InterpErrorKind<'_> {
644 pub fn formatted_string(&self) -> bool {
648 matches!(
649 self,
650 InterpErrorKind::Unsupported(UnsupportedOpInfo::Unsupported(_))
651 | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::ValidationError { .. })
652 | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_))
653 )
654 }
655}
656
657#[macro_export]
659macro_rules! err_unsup {
660 ($($tt:tt)*) => {
661 $crate::mir::interpret::InterpErrorKind::Unsupported(
662 $crate::mir::interpret::UnsupportedOpInfo::$($tt)*
663 )
664 };
665}
666
667#[macro_export]
668macro_rules! err_unsup_format {
669 ($($tt:tt)*) => { $crate::err_unsup!(Unsupported(format!($($tt)*))) };
670}
671
672#[macro_export]
673macro_rules! err_inval {
674 ($($tt:tt)*) => {
675 $crate::mir::interpret::InterpErrorKind::InvalidProgram(
676 $crate::mir::interpret::InvalidProgramInfo::$($tt)*
677 )
678 };
679}
680
681#[macro_export]
682macro_rules! err_ub {
683 ($($tt:tt)*) => {
684 $crate::mir::interpret::InterpErrorKind::UndefinedBehavior(
685 $crate::mir::interpret::UndefinedBehaviorInfo::$($tt)*
686 )
687 };
688}
689
690#[macro_export]
691macro_rules! err_ub_format {
692 ($($tt:tt)*) => { $crate::err_ub!(Ub(format!($($tt)*))) };
693}
694
695#[macro_export]
696macro_rules! err_ub_custom {
697 ($msg:expr $(, $($name:ident = $value:expr),* $(,)?)?) => {{
698 $(
699 let ($($name,)*) = ($($value,)*);
700 )?
701 $crate::err_ub!(Custom(
702 $crate::error::CustomSubdiagnostic {
703 msg: || $msg,
704 add_args: Box::new(move |mut set_arg| {
705 $($(
706 set_arg(stringify!($name).into(), rustc_errors::IntoDiagArg::into_diag_arg($name, &mut None));
707 )*)?
708 })
709 }
710 ))
711 }};
712}
713
714#[macro_export]
715macro_rules! err_exhaust {
716 ($($tt:tt)*) => {
717 $crate::mir::interpret::InterpErrorKind::ResourceExhaustion(
718 $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
719 )
720 };
721}
722
723#[macro_export]
724macro_rules! err_machine_stop {
725 ($($tt:tt)*) => {
726 $crate::mir::interpret::InterpErrorKind::MachineStop(Box::new($($tt)*))
727 };
728}
729
730#[macro_export]
732macro_rules! throw_unsup {
733 ($($tt:tt)*) => { do yeet $crate::err_unsup!($($tt)*) };
734}
735
736#[macro_export]
737macro_rules! throw_unsup_format {
738 ($($tt:tt)*) => { do yeet $crate::err_unsup_format!($($tt)*) };
739}
740
741#[macro_export]
742macro_rules! throw_inval {
743 ($($tt:tt)*) => { do yeet $crate::err_inval!($($tt)*) };
744}
745
746#[macro_export]
747macro_rules! throw_ub {
748 ($($tt:tt)*) => { do yeet $crate::err_ub!($($tt)*) };
749}
750
751#[macro_export]
752macro_rules! throw_ub_format {
753 ($($tt:tt)*) => { do yeet $crate::err_ub_format!($($tt)*) };
754}
755
756#[macro_export]
757macro_rules! throw_ub_custom {
758 ($($tt:tt)*) => { do yeet $crate::err_ub_custom!($($tt)*) };
759}
760
761#[macro_export]
762macro_rules! throw_exhaust {
763 ($($tt:tt)*) => { do yeet $crate::err_exhaust!($($tt)*) };
764}
765
766#[macro_export]
767macro_rules! throw_machine_stop {
768 ($($tt:tt)*) => { do yeet $crate::err_machine_stop!($($tt)*) };
769}
770
771#[derive(Debug)]
773struct Guard;
774
775impl Drop for Guard {
776 fn drop(&mut self) {
777 if !std::thread::panicking() {
779 panic!(
780 "an interpreter error got improperly discarded; use `discard_err()` if this is intentional"
781 );
782 }
783 }
784}
785
786#[derive(Debug)]
791#[must_use]
792pub struct InterpResult<'tcx, T = ()> {
793 res: Result<T, InterpErrorInfo<'tcx>>,
794 guard: Guard,
795}
796
797impl<'tcx, T> ops::Try for InterpResult<'tcx, T> {
798 type Output = T;
799 type Residual = InterpResult<'tcx, convert::Infallible>;
800
801 #[inline]
802 fn from_output(output: Self::Output) -> Self {
803 InterpResult::new(Ok(output))
804 }
805
806 #[inline]
807 fn branch(self) -> ops::ControlFlow<Self::Residual, Self::Output> {
808 match self.disarm() {
809 Ok(v) => ops::ControlFlow::Continue(v),
810 Err(e) => ops::ControlFlow::Break(InterpResult::new(Err(e))),
811 }
812 }
813}
814
815impl<'tcx, T> ops::Residual<T> for InterpResult<'tcx, convert::Infallible> {
816 type TryType = InterpResult<'tcx, T>;
817}
818
819impl<'tcx, T> ops::FromResidual for InterpResult<'tcx, T> {
820 #[inline]
821 #[track_caller]
822 fn from_residual(residual: InterpResult<'tcx, convert::Infallible>) -> Self {
823 match residual.disarm() {
824 Err(e) => Self::new(Err(e)),
825 }
826 }
827}
828
829impl<'tcx, T> ops::FromResidual<ops::Yeet<InterpErrorKind<'tcx>>> for InterpResult<'tcx, T> {
831 #[inline]
832 fn from_residual(ops::Yeet(e): ops::Yeet<InterpErrorKind<'tcx>>) -> Self {
833 Self::new(Err(e.into()))
834 }
835}
836
837impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> ops::FromResidual<Result<convert::Infallible, E>>
840 for InterpResult<'tcx, T>
841{
842 #[inline]
843 fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
844 match residual {
845 Err(e) => Self::new(Err(e.into())),
846 }
847 }
848}
849
850impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> From<Result<T, E>> for InterpResult<'tcx, T> {
851 #[inline]
852 fn from(value: Result<T, E>) -> Self {
853 Self::new(value.map_err(|e| e.into()))
854 }
855}
856
857impl<'tcx, T, V: FromIterator<T>> FromIterator<InterpResult<'tcx, T>> for InterpResult<'tcx, V> {
858 fn from_iter<I: IntoIterator<Item = InterpResult<'tcx, T>>>(iter: I) -> Self {
859 Self::new(iter.into_iter().map(|x| x.disarm()).collect())
860 }
861}
862
863impl<'tcx, T> InterpResult<'tcx, T> {
864 #[inline(always)]
865 fn new(res: Result<T, InterpErrorInfo<'tcx>>) -> Self {
866 Self { res, guard: Guard }
867 }
868
869 #[inline(always)]
870 fn disarm(self) -> Result<T, InterpErrorInfo<'tcx>> {
871 mem::forget(self.guard);
872 self.res
873 }
874
875 #[inline]
877 pub fn discard_err(self) -> Option<T> {
878 self.disarm().ok()
879 }
880
881 #[inline]
884 pub fn report_err(self) -> Result<T, InterpErrorInfo<'tcx>> {
885 self.disarm()
886 }
887
888 #[inline]
889 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> InterpResult<'tcx, U> {
890 InterpResult::new(self.disarm().map(f))
891 }
892
893 #[inline]
894 pub fn map_err_info(
895 self,
896 f: impl FnOnce(InterpErrorInfo<'tcx>) -> InterpErrorInfo<'tcx>,
897 ) -> InterpResult<'tcx, T> {
898 InterpResult::new(self.disarm().map_err(f))
899 }
900
901 #[inline]
902 pub fn map_err_kind(
903 self,
904 f: impl FnOnce(InterpErrorKind<'tcx>) -> InterpErrorKind<'tcx>,
905 ) -> InterpResult<'tcx, T> {
906 InterpResult::new(self.disarm().map_err(|mut e| {
907 e.0.kind = f(e.0.kind);
908 e
909 }))
910 }
911
912 #[inline]
913 pub fn inspect_err_kind(self, f: impl FnOnce(&InterpErrorKind<'tcx>)) -> InterpResult<'tcx, T> {
914 InterpResult::new(self.disarm().inspect_err(|e| f(&e.0.kind)))
915 }
916
917 #[inline]
918 #[track_caller]
919 pub fn unwrap(self) -> T {
920 self.disarm().unwrap()
921 }
922
923 #[inline]
924 #[track_caller]
925 pub fn unwrap_or_else(self, f: impl FnOnce(InterpErrorInfo<'tcx>) -> T) -> T {
926 self.disarm().unwrap_or_else(f)
927 }
928
929 #[inline]
930 #[track_caller]
931 pub fn expect(self, msg: &str) -> T {
932 self.disarm().expect(msg)
933 }
934
935 #[inline]
936 pub fn and_then<U>(self, f: impl FnOnce(T) -> InterpResult<'tcx, U>) -> InterpResult<'tcx, U> {
937 InterpResult::new(self.disarm().and_then(|t| f(t).disarm()))
938 }
939
940 #[inline]
945 pub fn and<U>(self, other: InterpResult<'tcx, U>) -> InterpResult<'tcx, (T, U)> {
946 match self.disarm() {
947 Ok(t) => interp_ok((t, other?)),
948 Err(e) => {
949 drop(other.disarm());
951 InterpResult::new(Err(e))
953 }
954 }
955 }
956}
957
958#[inline(always)]
959pub fn interp_ok<'tcx, T>(x: T) -> InterpResult<'tcx, T> {
960 InterpResult::new(Ok(x))
961}