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<'tcx>, 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 InvalidBool(u8),
397 InvalidChar(u32),
399 InvalidTag(Scalar<AllocId>),
401 InvalidFunctionPointer(Pointer<AllocId>),
403 InvalidVTablePointer(Pointer<AllocId>),
405 InvalidVTableTrait {
407 vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
409 expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
411 },
412 InvalidStr(std::str::Utf8Error),
414 InvalidUninitBytes(Option<(AllocId, BadBytesAccess)>),
416 DeadLocal,
418 ScalarSizeMismatch(ScalarSizeMismatch),
420 UninhabitedEnumVariantWritten(VariantIdx),
422 UninhabitedEnumVariantRead(Option<VariantIdx>),
424 InvalidNichedEnumVariantWritten { enum_ty: Ty<'tcx> },
426 AbiMismatchArgument { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> },
428 AbiMismatchReturn { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> },
430}
431
432#[derive(Debug, Clone, Copy)]
433pub enum PointerKind {
434 Ref(Mutability),
435 Box,
436}
437
438impl IntoDiagArg for PointerKind {
439 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
440 DiagArgValue::Str(
441 match self {
442 Self::Ref(_) => "ref",
443 Self::Box => "box",
444 }
445 .into(),
446 )
447 }
448}
449
450#[derive(Debug)]
451pub struct ValidationErrorInfo<'tcx> {
452 pub path: Option<String>,
453 pub kind: ValidationErrorKind<'tcx>,
454}
455
456#[derive(Debug)]
457pub enum ExpectedKind {
458 Reference,
459 Box,
460 RawPtr,
461 InitScalar,
462 Bool,
463 Char,
464 Float,
465 Int,
466 FnPtr,
467 EnumTag,
468 Str,
469}
470
471impl From<PointerKind> for ExpectedKind {
472 fn from(x: PointerKind) -> ExpectedKind {
473 match x {
474 PointerKind::Box => ExpectedKind::Box,
475 PointerKind::Ref(_) => ExpectedKind::Reference,
476 }
477 }
478}
479
480#[derive(Debug)]
481pub enum ValidationErrorKind<'tcx> {
482 PointerAsInt {
483 expected: ExpectedKind,
484 },
485 PartialPointer,
486 PtrToUninhabited {
487 ptr_kind: PointerKind,
488 ty: Ty<'tcx>,
489 },
490 MutableRefToImmutable,
491 UnsafeCellInImmutable,
492 MutableRefInConst,
493 NullFnPtr,
494 NeverVal,
495 NullablePtrOutOfRange {
496 range: WrappingRange,
497 max_value: u128,
498 },
499 PtrOutOfRange {
500 range: WrappingRange,
501 max_value: u128,
502 },
503 OutOfRange {
504 value: String,
505 range: WrappingRange,
506 max_value: u128,
507 },
508 UninhabitedVal {
509 ty: Ty<'tcx>,
510 },
511 InvalidEnumTag {
512 value: String,
513 },
514 UninhabitedEnumVariant,
515 Uninit {
516 expected: ExpectedKind,
517 },
518 InvalidVTablePtr {
519 value: String,
520 },
521 InvalidMetaWrongTrait {
522 vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
524 expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
526 },
527 InvalidMetaSliceTooLarge {
528 ptr_kind: PointerKind,
529 },
530 InvalidMetaTooLarge {
531 ptr_kind: PointerKind,
532 },
533 UnalignedPtr {
534 ptr_kind: PointerKind,
535 required_bytes: u64,
536 found_bytes: u64,
537 },
538 NullPtr {
539 ptr_kind: PointerKind,
540 },
541 DanglingPtrNoProvenance {
542 ptr_kind: PointerKind,
543 pointer: String,
544 },
545 DanglingPtrOutOfBounds {
546 ptr_kind: PointerKind,
547 },
548 DanglingPtrUseAfterFree {
549 ptr_kind: PointerKind,
550 },
551 InvalidBool {
552 value: String,
553 },
554 InvalidChar {
555 value: String,
556 },
557 InvalidFnPtr {
558 value: String,
559 },
560}
561
562#[derive(Debug)]
567pub enum UnsupportedOpInfo {
568 Unsupported(String),
571 UnsizedLocal,
573 ExternTypeField,
575 OverwritePartialPointer(Pointer<AllocId>),
581 ReadPartialPointer(Pointer<AllocId>),
584 ReadPointerAsInt(Option<(AllocId, BadBytesAccess)>),
586 ThreadLocalStatic(DefId),
588 ExternStatic(DefId),
590}
591
592#[derive(Debug)]
595pub enum ResourceExhaustionInfo {
596 StackFrameLimitReached,
598 MemoryExhausted,
600 AddressSpaceFull,
602 Interrupted,
604}
605
606pub trait MachineStopType: Any + fmt::Debug + Send {
608 fn diagnostic_message(&self) -> DiagMessage;
610 fn add_args(self: Box<Self>, adder: &mut dyn FnMut(DiagArgName, DiagArgValue));
613}
614
615impl dyn MachineStopType {
616 #[inline(always)]
617 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
618 let x: &dyn Any = self;
619 x.downcast_ref()
620 }
621}
622
623#[derive(Debug)]
624pub enum InterpErrorKind<'tcx> {
625 UndefinedBehavior(UndefinedBehaviorInfo<'tcx>),
627 Unsupported(UnsupportedOpInfo),
630 InvalidProgram(InvalidProgramInfo<'tcx>),
632 ResourceExhaustion(ResourceExhaustionInfo),
635 MachineStop(Box<dyn MachineStopType>),
638}
639
640impl InterpErrorKind<'_> {
641 pub fn formatted_string(&self) -> bool {
645 matches!(
646 self,
647 InterpErrorKind::Unsupported(UnsupportedOpInfo::Unsupported(_))
648 | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::ValidationError { .. })
649 | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_))
650 )
651 }
652}
653
654#[macro_export]
656macro_rules! err_unsup {
657 ($($tt:tt)*) => {
658 $crate::mir::interpret::InterpErrorKind::Unsupported(
659 $crate::mir::interpret::UnsupportedOpInfo::$($tt)*
660 )
661 };
662}
663
664#[macro_export]
665macro_rules! err_unsup_format {
666 ($($tt:tt)*) => { $crate::err_unsup!(Unsupported(format!($($tt)*))) };
667}
668
669#[macro_export]
670macro_rules! err_inval {
671 ($($tt:tt)*) => {
672 $crate::mir::interpret::InterpErrorKind::InvalidProgram(
673 $crate::mir::interpret::InvalidProgramInfo::$($tt)*
674 )
675 };
676}
677
678#[macro_export]
679macro_rules! err_ub {
680 ($($tt:tt)*) => {
681 $crate::mir::interpret::InterpErrorKind::UndefinedBehavior(
682 $crate::mir::interpret::UndefinedBehaviorInfo::$($tt)*
683 )
684 };
685}
686
687#[macro_export]
688macro_rules! err_ub_format {
689 ($($tt:tt)*) => { $crate::err_ub!(Ub(format!($($tt)*))) };
690}
691
692#[macro_export]
693macro_rules! err_ub_custom {
694 ($msg:expr $(, $($name:ident = $value:expr),* $(,)?)?) => {{
695 $(
696 let ($($name,)*) = ($($value,)*);
697 )?
698 $crate::err_ub!(Custom(
699 $crate::error::CustomSubdiagnostic {
700 msg: || $msg,
701 add_args: Box::new(move |mut set_arg| {
702 $($(
703 set_arg(stringify!($name).into(), rustc_errors::IntoDiagArg::into_diag_arg($name, &mut None));
704 )*)?
705 })
706 }
707 ))
708 }};
709}
710
711#[macro_export]
712macro_rules! err_exhaust {
713 ($($tt:tt)*) => {
714 $crate::mir::interpret::InterpErrorKind::ResourceExhaustion(
715 $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
716 )
717 };
718}
719
720#[macro_export]
721macro_rules! err_machine_stop {
722 ($($tt:tt)*) => {
723 $crate::mir::interpret::InterpErrorKind::MachineStop(Box::new($($tt)*))
724 };
725}
726
727#[macro_export]
729macro_rules! throw_unsup {
730 ($($tt:tt)*) => { do yeet $crate::err_unsup!($($tt)*) };
731}
732
733#[macro_export]
734macro_rules! throw_unsup_format {
735 ($($tt:tt)*) => { do yeet $crate::err_unsup_format!($($tt)*) };
736}
737
738#[macro_export]
739macro_rules! throw_inval {
740 ($($tt:tt)*) => { do yeet $crate::err_inval!($($tt)*) };
741}
742
743#[macro_export]
744macro_rules! throw_ub {
745 ($($tt:tt)*) => { do yeet $crate::err_ub!($($tt)*) };
746}
747
748#[macro_export]
749macro_rules! throw_ub_format {
750 ($($tt:tt)*) => { do yeet $crate::err_ub_format!($($tt)*) };
751}
752
753#[macro_export]
754macro_rules! throw_ub_custom {
755 ($($tt:tt)*) => { do yeet $crate::err_ub_custom!($($tt)*) };
756}
757
758#[macro_export]
759macro_rules! throw_exhaust {
760 ($($tt:tt)*) => { do yeet $crate::err_exhaust!($($tt)*) };
761}
762
763#[macro_export]
764macro_rules! throw_machine_stop {
765 ($($tt:tt)*) => { do yeet $crate::err_machine_stop!($($tt)*) };
766}
767
768#[derive(Debug)]
770struct Guard;
771
772impl Drop for Guard {
773 fn drop(&mut self) {
774 if !std::thread::panicking() {
776 panic!(
777 "an interpreter error got improperly discarded; use `discard_err()` if this is intentional"
778 );
779 }
780 }
781}
782
783#[derive(Debug)]
788#[must_use]
789pub struct InterpResult_<'tcx, T> {
790 res: Result<T, InterpErrorInfo<'tcx>>,
791 guard: Guard,
792}
793
794pub type InterpResult<'tcx, T = ()> = InterpResult_<'tcx, T>;
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::FromResidual for InterpResult_<'tcx, T> {
816 #[inline]
817 #[track_caller]
818 fn from_residual(residual: InterpResult_<'tcx, convert::Infallible>) -> Self {
819 match residual.disarm() {
820 Err(e) => Self::new(Err(e)),
821 }
822 }
823}
824
825impl<'tcx, T> ops::FromResidual<ops::Yeet<InterpErrorKind<'tcx>>> for InterpResult_<'tcx, T> {
827 #[inline]
828 fn from_residual(ops::Yeet(e): ops::Yeet<InterpErrorKind<'tcx>>) -> Self {
829 Self::new(Err(e.into()))
830 }
831}
832
833impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> ops::FromResidual<Result<convert::Infallible, E>>
836 for InterpResult_<'tcx, T>
837{
838 #[inline]
839 fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
840 match residual {
841 Err(e) => Self::new(Err(e.into())),
842 }
843 }
844}
845
846impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> From<Result<T, E>> for InterpResult<'tcx, T> {
847 #[inline]
848 fn from(value: Result<T, E>) -> Self {
849 Self::new(value.map_err(|e| e.into()))
850 }
851}
852
853impl<'tcx, T, V: FromIterator<T>> FromIterator<InterpResult<'tcx, T>> for InterpResult<'tcx, V> {
854 fn from_iter<I: IntoIterator<Item = InterpResult<'tcx, T>>>(iter: I) -> Self {
855 Self::new(iter.into_iter().map(|x| x.disarm()).collect())
856 }
857}
858
859impl<'tcx, T> InterpResult_<'tcx, T> {
860 #[inline(always)]
861 fn new(res: Result<T, InterpErrorInfo<'tcx>>) -> Self {
862 Self { res, guard: Guard }
863 }
864
865 #[inline(always)]
866 fn disarm(self) -> Result<T, InterpErrorInfo<'tcx>> {
867 mem::forget(self.guard);
868 self.res
869 }
870
871 #[inline]
873 pub fn discard_err(self) -> Option<T> {
874 self.disarm().ok()
875 }
876
877 #[inline]
880 pub fn report_err(self) -> Result<T, InterpErrorInfo<'tcx>> {
881 self.disarm()
882 }
883
884 #[inline]
885 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> InterpResult<'tcx, U> {
886 InterpResult_::new(self.disarm().map(f))
887 }
888
889 #[inline]
890 pub fn map_err_info(
891 self,
892 f: impl FnOnce(InterpErrorInfo<'tcx>) -> InterpErrorInfo<'tcx>,
893 ) -> InterpResult<'tcx, T> {
894 InterpResult_::new(self.disarm().map_err(f))
895 }
896
897 #[inline]
898 pub fn map_err_kind(
899 self,
900 f: impl FnOnce(InterpErrorKind<'tcx>) -> InterpErrorKind<'tcx>,
901 ) -> InterpResult<'tcx, T> {
902 InterpResult_::new(self.disarm().map_err(|mut e| {
903 e.0.kind = f(e.0.kind);
904 e
905 }))
906 }
907
908 #[inline]
909 pub fn inspect_err_kind(self, f: impl FnOnce(&InterpErrorKind<'tcx>)) -> InterpResult<'tcx, T> {
910 InterpResult_::new(self.disarm().inspect_err(|e| f(&e.0.kind)))
911 }
912
913 #[inline]
914 #[track_caller]
915 pub fn unwrap(self) -> T {
916 self.disarm().unwrap()
917 }
918
919 #[inline]
920 #[track_caller]
921 pub fn unwrap_or_else(self, f: impl FnOnce(InterpErrorInfo<'tcx>) -> T) -> T {
922 self.disarm().unwrap_or_else(f)
923 }
924
925 #[inline]
926 #[track_caller]
927 pub fn expect(self, msg: &str) -> T {
928 self.disarm().expect(msg)
929 }
930
931 #[inline]
932 pub fn and_then<U>(self, f: impl FnOnce(T) -> InterpResult<'tcx, U>) -> InterpResult<'tcx, U> {
933 InterpResult_::new(self.disarm().and_then(|t| f(t).disarm()))
934 }
935
936 #[inline]
941 pub fn and<U>(self, other: InterpResult<'tcx, U>) -> InterpResult<'tcx, (T, U)> {
942 match self.disarm() {
943 Ok(t) => interp_ok((t, other?)),
944 Err(e) => {
945 drop(other.disarm());
947 InterpResult_::new(Err(e))
949 }
950 }
951 }
952}
953
954#[inline(always)]
955pub fn interp_ok<'tcx, T>(x: T) -> InterpResult<'tcx, T> {
956 InterpResult_::new(Ok(x))
957}