rustc_middle/mir/interpret/
error.rs

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    /// Already reported an error for this evaluation, and the compilation is
23    /// *guaranteed* to fail. Warnings/lints *must not* produce `Reported`.
24    Reported(ReportedErrorInfo, Span),
25    /// Don't emit an error, the evaluation failed because the MIR was generic
26    /// and the args didn't fully monomorphize it.
27    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 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    /// Whether this error is allowed to show up even in otherwise "infallible" promoteds.
61    /// This is for things like overflows during size computation or resource exhaustion.
62    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    /// Use this when the error that led to this is *not* a const-eval error
72    /// (e.g., a layout or type checking error).
73    #[inline]
74    pub fn non_const_eval_error(error: ErrorGuaranteed) -> ReportedErrorInfo {
75        ReportedErrorInfo { allowed_in_infallible: true, error }
76    }
77
78    /// Use this when the error that led to this *is* a const-eval error, but
79    /// we do allow it to occur in infallible constants (e.g., resource exhaustion).
80    #[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
97pub type EvalToAllocationRawResult<'tcx> = Result<ConstAlloc<'tcx>, ErrorHandled>;
98pub type EvalStaticInitializerRawResult<'tcx> = Result<ConstAllocation<'tcx>, ErrorHandled>;
99pub type EvalToConstValueResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>;
100/// `Ok(Err(ty))` indicates the constant was fine, but the valtree couldn't be constructed
101/// because the value contains something of type `ty` that is not valtree-compatible.
102/// The caller can then show an appropriate error; the query does not have the
103/// necessary context to give good user-facing errors for this case.
104pub type EvalToValTreeResult<'tcx> = Result<Result<ValTree<'tcx>, Ty<'tcx>>, ErrorHandled>;
105
106#[cfg(target_pointer_width = "64")]
107rustc_data_structures::static_assert_size!(InterpErrorInfo<'_>, 8);
108
109/// Packages the kind of error we got from the const code interpreter
110/// up with a Rust-level backtrace of where the error occurred.
111/// These should always be constructed by calling `.into()` on
112/// an `InterpError`. In `rustc_mir::interpret`, we have `throw_err_*`
113/// macros for this.
114///
115/// Interpreter errors must *not* be silently discarded (that will lead to a panic). Instead,
116/// explicitly call `discard_err` if this is really the right thing to do. Note that if
117/// this happens during const-eval or in Miri, it could lead to a UB error being lost!
118#[derive(Debug)]
119pub struct InterpErrorInfo<'tcx>(Box<InterpErrorInfoInner<'tcx>>);
120
121#[derive(Debug)]
122struct InterpErrorInfoInner<'tcx> {
123    kind: InterpErrorKind<'tcx>,
124    backtrace: InterpErrorBacktrace,
125}
126
127#[derive(Debug)]
128pub struct InterpErrorBacktrace {
129    backtrace: Option<Box<Backtrace>>,
130}
131
132impl InterpErrorBacktrace {
133    pub fn new() -> InterpErrorBacktrace {
134        let capture_backtrace = tls::with_opt(|tcx| {
135            if let Some(tcx) = tcx {
136                *Lock::borrow(&tcx.sess.ctfe_backtrace)
137            } else {
138                CtfeBacktrace::Disabled
139            }
140        });
141
142        let backtrace = match capture_backtrace {
143            CtfeBacktrace::Disabled => None,
144            CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())),
145            CtfeBacktrace::Immediate => {
146                // Print it now.
147                let backtrace = Backtrace::force_capture();
148                print_backtrace(&backtrace);
149                None
150            }
151        };
152
153        InterpErrorBacktrace { backtrace }
154    }
155
156    pub fn print_backtrace(&self) {
157        if let Some(backtrace) = self.backtrace.as_ref() {
158            print_backtrace(backtrace);
159        }
160    }
161}
162
163impl<'tcx> InterpErrorInfo<'tcx> {
164    pub fn into_parts(self) -> (InterpErrorKind<'tcx>, InterpErrorBacktrace) {
165        let InterpErrorInfo(box InterpErrorInfoInner { kind, backtrace }) = self;
166        (kind, backtrace)
167    }
168
169    pub fn into_kind(self) -> InterpErrorKind<'tcx> {
170        self.0.kind
171    }
172
173    pub fn from_parts(kind: InterpErrorKind<'tcx>, backtrace: InterpErrorBacktrace) -> Self {
174        Self(Box::new(InterpErrorInfoInner { kind, backtrace }))
175    }
176
177    #[inline]
178    pub fn kind(&self) -> &InterpErrorKind<'tcx> {
179        &self.0.kind
180    }
181}
182
183fn print_backtrace(backtrace: &Backtrace) {
184    eprintln!("\n\nAn error occurred in the MIR interpreter:\n{backtrace}");
185}
186
187impl From<ErrorHandled> for InterpErrorInfo<'_> {
188    fn from(err: ErrorHandled) -> Self {
189        InterpErrorKind::InvalidProgram(match err {
190            ErrorHandled::Reported(r, _span) => InvalidProgramInfo::AlreadyReported(r),
191            ErrorHandled::TooGeneric(_span) => InvalidProgramInfo::TooGeneric,
192        })
193        .into()
194    }
195}
196
197impl<'tcx> From<InterpErrorKind<'tcx>> for InterpErrorInfo<'tcx> {
198    fn from(kind: InterpErrorKind<'tcx>) -> Self {
199        InterpErrorInfo(Box::new(InterpErrorInfoInner {
200            kind,
201            backtrace: InterpErrorBacktrace::new(),
202        }))
203    }
204}
205
206/// Error information for when the program we executed turned out not to actually be a valid
207/// program. This cannot happen in stand-alone Miri (except for layout errors that are only detect
208/// during monomorphization), but it can happen during CTFE/ConstProp where we work on generic code
209/// or execution does not have all information available.
210#[derive(Debug)]
211pub enum InvalidProgramInfo<'tcx> {
212    /// Resolution can fail if we are in a too generic context.
213    TooGeneric,
214    /// Abort in case errors are already reported.
215    AlreadyReported(ReportedErrorInfo),
216    /// An error occurred during layout computation.
217    Layout(layout::LayoutError<'tcx>),
218}
219
220/// Details of why a pointer had to be in-bounds.
221#[derive(Debug, Copy, Clone)]
222pub enum CheckInAllocMsg {
223    /// We are access memory.
224    MemoryAccess,
225    /// We are doing pointer arithmetic.
226    InboundsPointerArithmetic,
227    /// None of the above -- generic/unspecific inbounds test.
228    Dereferenceable,
229}
230
231/// Details of which pointer is not aligned.
232#[derive(Debug, Copy, Clone)]
233pub enum CheckAlignMsg {
234    /// The accessed pointer did not have proper alignment.
235    AccessedPtr,
236    /// The access occurred with a place that was based on a misaligned pointer.
237    BasedOn,
238}
239
240#[derive(Debug, Copy, Clone)]
241pub enum InvalidMetaKind {
242    /// Size of a `[T]` is too big
243    SliceTooBig,
244    /// Size of a DST is too big
245    TooBig,
246}
247
248impl IntoDiagArg for InvalidMetaKind {
249    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
250        DiagArgValue::Str(Cow::Borrowed(match self {
251            InvalidMetaKind::SliceTooBig => "slice_too_big",
252            InvalidMetaKind::TooBig => "too_big",
253        }))
254    }
255}
256
257/// Details of an access to uninitialized bytes / bad pointer bytes where it is not allowed.
258#[derive(Debug, Clone, Copy)]
259pub struct BadBytesAccess {
260    /// Range of the original memory access.
261    pub access: AllocRange,
262    /// Range of the bad memory that was encountered. (Might not be maximal.)
263    pub bad: AllocRange,
264}
265
266/// Information about a size mismatch.
267#[derive(Debug)]
268pub struct ScalarSizeMismatch {
269    pub target_size: u64,
270    pub data_size: u64,
271}
272
273/// Information about a misaligned pointer.
274#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
275pub struct Misalignment {
276    pub has: Align,
277    pub required: Align,
278}
279
280macro_rules! impl_into_diag_arg_through_debug {
281    ($($ty:ty),*$(,)?) => {$(
282        impl IntoDiagArg for $ty {
283            fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
284                DiagArgValue::Str(Cow::Owned(format!("{self:?}")))
285            }
286        }
287    )*}
288}
289
290// These types have nice `Debug` output so we can just use them in diagnostics.
291impl_into_diag_arg_through_debug! {
292    AllocId,
293    Pointer<AllocId>,
294    AllocRange,
295}
296
297/// Error information for when the program caused Undefined Behavior.
298#[derive(Debug)]
299pub enum UndefinedBehaviorInfo<'tcx> {
300    /// Free-form case. Only for errors that are never caught! Used by miri
301    Ub(String),
302    // FIXME(fee1-dead) these should all be actual variants of the enum instead of dynamically
303    // dispatched
304    /// A custom (free-form) fluent-translated error, created by `err_ub_custom!`.
305    Custom(crate::error::CustomSubdiagnostic<'tcx>),
306    /// Validation error.
307    ValidationError(ValidationErrorInfo<'tcx>),
308
309    /// Unreachable code was executed.
310    Unreachable,
311    /// A slice/array index projection went out-of-bounds.
312    BoundsCheckFailed { len: u64, index: u64 },
313    /// Something was divided by 0 (x / 0).
314    DivisionByZero,
315    /// Something was "remainded" by 0 (x % 0).
316    RemainderByZero,
317    /// Signed division overflowed (INT_MIN / -1).
318    DivisionOverflow,
319    /// Signed remainder overflowed (INT_MIN % -1).
320    RemainderOverflow,
321    /// Overflowing inbounds pointer arithmetic.
322    PointerArithOverflow,
323    /// Overflow in arithmetic that may not overflow.
324    ArithOverflow { intrinsic: Symbol },
325    /// Shift by too much.
326    ShiftOverflow { intrinsic: Symbol, shift_amount: Either<u128, i128> },
327    /// Invalid metadata in a wide pointer
328    InvalidMeta(InvalidMetaKind),
329    /// Reading a C string that does not end within its allocation.
330    UnterminatedCString(Pointer<AllocId>),
331    /// Using a pointer after it got freed.
332    PointerUseAfterFree(AllocId, CheckInAllocMsg),
333    /// Used a pointer outside the bounds it is valid for.
334    PointerOutOfBounds {
335        alloc_id: AllocId,
336        alloc_size: Size,
337        ptr_offset: i64,
338        /// The size of the memory range that was expected to be in-bounds.
339        inbounds_size: i64,
340        msg: CheckInAllocMsg,
341    },
342    /// Using an integer as a pointer in the wrong way.
343    DanglingIntPointer {
344        addr: u64,
345        /// The size of the memory range that was expected to be in-bounds (or 0 if we need an
346        /// allocation but not any actual memory there, e.g. for function pointers).
347        inbounds_size: i64,
348        msg: CheckInAllocMsg,
349    },
350    /// Used a pointer with bad alignment.
351    AlignmentCheckFailed(Misalignment, CheckAlignMsg),
352    /// Writing to read-only memory.
353    WriteToReadOnly(AllocId),
354    /// Trying to access the data behind a function pointer.
355    DerefFunctionPointer(AllocId),
356    /// Trying to access the data behind a vtable pointer.
357    DerefVTablePointer(AllocId),
358    /// Using a non-boolean `u8` as bool.
359    InvalidBool(u8),
360    /// Using a non-character `u32` as character.
361    InvalidChar(u32),
362    /// The tag of an enum does not encode an actual discriminant.
363    InvalidTag(Scalar<AllocId>),
364    /// Using a pointer-not-to-a-function as function pointer.
365    InvalidFunctionPointer(Pointer<AllocId>),
366    /// Using a pointer-not-to-a-vtable as vtable pointer.
367    InvalidVTablePointer(Pointer<AllocId>),
368    /// Using a vtable for the wrong trait.
369    InvalidVTableTrait {
370        /// The vtable that was actually referenced by the wide pointer metadata.
371        vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
372        /// The vtable that was expected at the point in MIR that it was accessed.
373        expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
374    },
375    /// Using a string that is not valid UTF-8,
376    InvalidStr(std::str::Utf8Error),
377    /// Using uninitialized data where it is not allowed.
378    InvalidUninitBytes(Option<(AllocId, BadBytesAccess)>),
379    /// Working with a local that is not currently live.
380    DeadLocal,
381    /// Data size is not equal to target size.
382    ScalarSizeMismatch(ScalarSizeMismatch),
383    /// A discriminant of an uninhabited enum variant is written.
384    UninhabitedEnumVariantWritten(VariantIdx),
385    /// An uninhabited enum variant is projected.
386    UninhabitedEnumVariantRead(Option<VariantIdx>),
387    /// Trying to set discriminant to the niched variant, but the value does not match.
388    InvalidNichedEnumVariantWritten { enum_ty: Ty<'tcx> },
389    /// ABI-incompatible argument types.
390    AbiMismatchArgument { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> },
391    /// ABI-incompatible return types.
392    AbiMismatchReturn { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> },
393}
394
395#[derive(Debug, Clone, Copy)]
396pub enum PointerKind {
397    Ref(Mutability),
398    Box,
399}
400
401impl IntoDiagArg for PointerKind {
402    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
403        DiagArgValue::Str(
404            match self {
405                Self::Ref(_) => "ref",
406                Self::Box => "box",
407            }
408            .into(),
409        )
410    }
411}
412
413#[derive(Debug)]
414pub struct ValidationErrorInfo<'tcx> {
415    pub path: Option<String>,
416    pub kind: ValidationErrorKind<'tcx>,
417}
418
419#[derive(Debug)]
420pub enum ExpectedKind {
421    Reference,
422    Box,
423    RawPtr,
424    InitScalar,
425    Bool,
426    Char,
427    Float,
428    Int,
429    FnPtr,
430    EnumTag,
431    Str,
432}
433
434impl From<PointerKind> for ExpectedKind {
435    fn from(x: PointerKind) -> ExpectedKind {
436        match x {
437            PointerKind::Box => ExpectedKind::Box,
438            PointerKind::Ref(_) => ExpectedKind::Reference,
439        }
440    }
441}
442
443#[derive(Debug)]
444pub enum ValidationErrorKind<'tcx> {
445    PointerAsInt {
446        expected: ExpectedKind,
447    },
448    PartialPointer,
449    PtrToUninhabited {
450        ptr_kind: PointerKind,
451        ty: Ty<'tcx>,
452    },
453    ConstRefToMutable,
454    ConstRefToExtern,
455    MutableRefToImmutable,
456    UnsafeCellInImmutable,
457    NullFnPtr,
458    NeverVal,
459    NullablePtrOutOfRange {
460        range: WrappingRange,
461        max_value: u128,
462    },
463    PtrOutOfRange {
464        range: WrappingRange,
465        max_value: u128,
466    },
467    OutOfRange {
468        value: String,
469        range: WrappingRange,
470        max_value: u128,
471    },
472    UninhabitedVal {
473        ty: Ty<'tcx>,
474    },
475    InvalidEnumTag {
476        value: String,
477    },
478    UninhabitedEnumVariant,
479    Uninit {
480        expected: ExpectedKind,
481    },
482    InvalidVTablePtr {
483        value: String,
484    },
485    InvalidMetaWrongTrait {
486        /// The vtable that was actually referenced by the wide pointer metadata.
487        vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
488        /// The vtable that was expected at the point in MIR that it was accessed.
489        expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
490    },
491    InvalidMetaSliceTooLarge {
492        ptr_kind: PointerKind,
493    },
494    InvalidMetaTooLarge {
495        ptr_kind: PointerKind,
496    },
497    UnalignedPtr {
498        ptr_kind: PointerKind,
499        required_bytes: u64,
500        found_bytes: u64,
501    },
502    NullPtr {
503        ptr_kind: PointerKind,
504    },
505    DanglingPtrNoProvenance {
506        ptr_kind: PointerKind,
507        pointer: String,
508    },
509    DanglingPtrOutOfBounds {
510        ptr_kind: PointerKind,
511    },
512    DanglingPtrUseAfterFree {
513        ptr_kind: PointerKind,
514    },
515    InvalidBool {
516        value: String,
517    },
518    InvalidChar {
519        value: String,
520    },
521    InvalidFnPtr {
522        value: String,
523    },
524}
525
526/// Error information for when the program did something that might (or might not) be correct
527/// to do according to the Rust spec, but due to limitations in the interpreter, the
528/// operation could not be carried out. These limitations can differ between CTFE and the
529/// Miri engine, e.g., CTFE does not support dereferencing pointers at integral addresses.
530#[derive(Debug)]
531pub enum UnsupportedOpInfo {
532    /// Free-form case. Only for errors that are never caught! Used by Miri.
533    // FIXME still use translatable diagnostics
534    Unsupported(String),
535    /// Unsized local variables.
536    UnsizedLocal,
537    /// Extern type field with an indeterminate offset.
538    ExternTypeField,
539    //
540    // The variants below are only reachable from CTFE/const prop, miri will never emit them.
541    //
542    /// Overwriting parts of a pointer; without knowing absolute addresses, the resulting state
543    /// cannot be represented by the CTFE interpreter.
544    OverwritePartialPointer(Pointer<AllocId>),
545    /// Attempting to read or copy parts of a pointer to somewhere else; without knowing absolute
546    /// addresses, the resulting state cannot be represented by the CTFE interpreter.
547    ReadPartialPointer(Pointer<AllocId>),
548    /// Encountered a pointer where we needed an integer.
549    ReadPointerAsInt(Option<(AllocId, BadBytesAccess)>),
550    /// Accessing thread local statics
551    ThreadLocalStatic(DefId),
552    /// Accessing an unsupported extern static.
553    ExternStatic(DefId),
554}
555
556/// Error information for when the program exhausted the resources granted to it
557/// by the interpreter.
558#[derive(Debug)]
559pub enum ResourceExhaustionInfo {
560    /// The stack grew too big.
561    StackFrameLimitReached,
562    /// There is not enough memory (on the host) to perform an allocation.
563    MemoryExhausted,
564    /// The address space (of the target) is full.
565    AddressSpaceFull,
566    /// The compiler got an interrupt signal (a user ran out of patience).
567    Interrupted,
568}
569
570/// A trait for machine-specific errors (or other "machine stop" conditions).
571pub trait MachineStopType: Any + fmt::Debug + Send {
572    /// The diagnostic message for this error
573    fn diagnostic_message(&self) -> DiagMessage;
574    /// Add diagnostic arguments by passing name and value pairs to `adder`, which are passed to
575    /// fluent for formatting the translated diagnostic message.
576    fn add_args(self: Box<Self>, adder: &mut dyn FnMut(DiagArgName, DiagArgValue));
577}
578
579impl dyn MachineStopType {
580    #[inline(always)]
581    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
582        let x: &dyn Any = self;
583        x.downcast_ref()
584    }
585}
586
587#[derive(Debug)]
588pub enum InterpErrorKind<'tcx> {
589    /// The program caused undefined behavior.
590    UndefinedBehavior(UndefinedBehaviorInfo<'tcx>),
591    /// The program did something the interpreter does not support (some of these *might* be UB
592    /// but the interpreter is not sure).
593    Unsupported(UnsupportedOpInfo),
594    /// The program was invalid (ill-typed, bad MIR, not sufficiently monomorphized, ...).
595    InvalidProgram(InvalidProgramInfo<'tcx>),
596    /// The program exhausted the interpreter's resources (stack/heap too big,
597    /// execution takes too long, ...).
598    ResourceExhaustion(ResourceExhaustionInfo),
599    /// Stop execution for a machine-controlled reason. This is never raised by
600    /// the core engine itself.
601    MachineStop(Box<dyn MachineStopType>),
602}
603
604impl InterpErrorKind<'_> {
605    /// Some errors do string formatting even if the error is never printed.
606    /// To avoid performance issues, there are places where we want to be sure to never raise these formatting errors,
607    /// so this method lets us detect them and `bug!` on unexpected errors.
608    pub fn formatted_string(&self) -> bool {
609        matches!(
610            self,
611            InterpErrorKind::Unsupported(UnsupportedOpInfo::Unsupported(_))
612                | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::ValidationError { .. })
613                | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_))
614        )
615    }
616}
617
618// Macros for constructing / throwing `InterpErrorKind`
619#[macro_export]
620macro_rules! err_unsup {
621    ($($tt:tt)*) => {
622        $crate::mir::interpret::InterpErrorKind::Unsupported(
623            $crate::mir::interpret::UnsupportedOpInfo::$($tt)*
624        )
625    };
626}
627
628#[macro_export]
629macro_rules! err_unsup_format {
630    ($($tt:tt)*) => { $crate::err_unsup!(Unsupported(format!($($tt)*))) };
631}
632
633#[macro_export]
634macro_rules! err_inval {
635    ($($tt:tt)*) => {
636        $crate::mir::interpret::InterpErrorKind::InvalidProgram(
637            $crate::mir::interpret::InvalidProgramInfo::$($tt)*
638        )
639    };
640}
641
642#[macro_export]
643macro_rules! err_ub {
644    ($($tt:tt)*) => {
645        $crate::mir::interpret::InterpErrorKind::UndefinedBehavior(
646            $crate::mir::interpret::UndefinedBehaviorInfo::$($tt)*
647        )
648    };
649}
650
651#[macro_export]
652macro_rules! err_ub_format {
653    ($($tt:tt)*) => { $crate::err_ub!(Ub(format!($($tt)*))) };
654}
655
656#[macro_export]
657macro_rules! err_ub_custom {
658    ($msg:expr $(, $($name:ident = $value:expr),* $(,)?)?) => {{
659        $(
660            let ($($name,)*) = ($($value,)*);
661        )?
662        $crate::err_ub!(Custom(
663            $crate::error::CustomSubdiagnostic {
664                msg: || $msg,
665                add_args: Box::new(move |mut set_arg| {
666                    $($(
667                        set_arg(stringify!($name).into(), rustc_errors::IntoDiagArg::into_diag_arg($name, &mut None));
668                    )*)?
669                })
670            }
671        ))
672    }};
673}
674
675#[macro_export]
676macro_rules! err_exhaust {
677    ($($tt:tt)*) => {
678        $crate::mir::interpret::InterpErrorKind::ResourceExhaustion(
679            $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
680        )
681    };
682}
683
684#[macro_export]
685macro_rules! err_machine_stop {
686    ($($tt:tt)*) => {
687        $crate::mir::interpret::InterpErrorKind::MachineStop(Box::new($($tt)*))
688    };
689}
690
691// In the `throw_*` macros, avoid `return` to make them work with `try {}`.
692#[macro_export]
693macro_rules! throw_unsup {
694    ($($tt:tt)*) => { do yeet $crate::err_unsup!($($tt)*) };
695}
696
697#[macro_export]
698macro_rules! throw_unsup_format {
699    ($($tt:tt)*) => { do yeet $crate::err_unsup_format!($($tt)*) };
700}
701
702#[macro_export]
703macro_rules! throw_inval {
704    ($($tt:tt)*) => { do yeet $crate::err_inval!($($tt)*) };
705}
706
707#[macro_export]
708macro_rules! throw_ub {
709    ($($tt:tt)*) => { do yeet $crate::err_ub!($($tt)*) };
710}
711
712#[macro_export]
713macro_rules! throw_ub_format {
714    ($($tt:tt)*) => { do yeet $crate::err_ub_format!($($tt)*) };
715}
716
717#[macro_export]
718macro_rules! throw_ub_custom {
719    ($($tt:tt)*) => { do yeet $crate::err_ub_custom!($($tt)*) };
720}
721
722#[macro_export]
723macro_rules! throw_exhaust {
724    ($($tt:tt)*) => { do yeet $crate::err_exhaust!($($tt)*) };
725}
726
727#[macro_export]
728macro_rules! throw_machine_stop {
729    ($($tt:tt)*) => { do yeet $crate::err_machine_stop!($($tt)*) };
730}
731
732/// Guard type that panics on drop.
733#[derive(Debug)]
734struct Guard;
735
736impl Drop for Guard {
737    fn drop(&mut self) {
738        // We silence the guard if we are already panicking, to avoid double-panics.
739        if !std::thread::panicking() {
740            panic!(
741                "an interpreter error got improperly discarded; use `discard_err()` if this is intentional"
742            );
743        }
744    }
745}
746
747/// The result type used by the interpreter. This is a newtype around `Result`
748/// to block access to operations like `ok()` that discard UB errors.
749///
750/// We also make things panic if this type is ever implicitly dropped.
751#[derive(Debug)]
752#[must_use]
753pub struct InterpResult_<'tcx, T> {
754    res: Result<T, InterpErrorInfo<'tcx>>,
755    guard: Guard,
756}
757
758// Type alias to be able to set a default type argument.
759pub type InterpResult<'tcx, T = ()> = InterpResult_<'tcx, T>;
760
761impl<'tcx, T> ops::Try for InterpResult_<'tcx, T> {
762    type Output = T;
763    type Residual = InterpResult_<'tcx, convert::Infallible>;
764
765    #[inline]
766    fn from_output(output: Self::Output) -> Self {
767        InterpResult_::new(Ok(output))
768    }
769
770    #[inline]
771    fn branch(self) -> ops::ControlFlow<Self::Residual, Self::Output> {
772        match self.disarm() {
773            Ok(v) => ops::ControlFlow::Continue(v),
774            Err(e) => ops::ControlFlow::Break(InterpResult_::new(Err(e))),
775        }
776    }
777}
778
779impl<'tcx, T> ops::FromResidual for InterpResult_<'tcx, T> {
780    #[inline]
781    #[track_caller]
782    fn from_residual(residual: InterpResult_<'tcx, convert::Infallible>) -> Self {
783        match residual.disarm() {
784            Err(e) => Self::new(Err(e)),
785        }
786    }
787}
788
789// Allow `yeet`ing `InterpError` in functions returning `InterpResult_`.
790impl<'tcx, T> ops::FromResidual<ops::Yeet<InterpErrorKind<'tcx>>> for InterpResult_<'tcx, T> {
791    #[inline]
792    fn from_residual(ops::Yeet(e): ops::Yeet<InterpErrorKind<'tcx>>) -> Self {
793        Self::new(Err(e.into()))
794    }
795}
796
797// Allow `?` on `Result<_, InterpError>` in functions returning `InterpResult_`.
798// This is useful e.g. for `option.ok_or_else(|| err_ub!(...))`.
799impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> ops::FromResidual<Result<convert::Infallible, E>>
800    for InterpResult_<'tcx, T>
801{
802    #[inline]
803    fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
804        match residual {
805            Err(e) => Self::new(Err(e.into())),
806        }
807    }
808}
809
810impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> From<Result<T, E>> for InterpResult<'tcx, T> {
811    #[inline]
812    fn from(value: Result<T, E>) -> Self {
813        Self::new(value.map_err(|e| e.into()))
814    }
815}
816
817impl<'tcx, T, V: FromIterator<T>> FromIterator<InterpResult<'tcx, T>> for InterpResult<'tcx, V> {
818    fn from_iter<I: IntoIterator<Item = InterpResult<'tcx, T>>>(iter: I) -> Self {
819        Self::new(iter.into_iter().map(|x| x.disarm()).collect())
820    }
821}
822
823impl<'tcx, T> InterpResult_<'tcx, T> {
824    #[inline(always)]
825    fn new(res: Result<T, InterpErrorInfo<'tcx>>) -> Self {
826        Self { res, guard: Guard }
827    }
828
829    #[inline(always)]
830    fn disarm(self) -> Result<T, InterpErrorInfo<'tcx>> {
831        mem::forget(self.guard);
832        self.res
833    }
834
835    /// Discard the error information in this result. Only use this if ignoring Undefined Behavior is okay!
836    #[inline]
837    pub fn discard_err(self) -> Option<T> {
838        self.disarm().ok()
839    }
840
841    /// Look at the `Result` wrapped inside of this.
842    /// Must only be used to report the error!
843    #[inline]
844    pub fn report_err(self) -> Result<T, InterpErrorInfo<'tcx>> {
845        self.disarm()
846    }
847
848    #[inline]
849    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> InterpResult<'tcx, U> {
850        InterpResult_::new(self.disarm().map(f))
851    }
852
853    #[inline]
854    pub fn map_err_info(
855        self,
856        f: impl FnOnce(InterpErrorInfo<'tcx>) -> InterpErrorInfo<'tcx>,
857    ) -> InterpResult<'tcx, T> {
858        InterpResult_::new(self.disarm().map_err(f))
859    }
860
861    #[inline]
862    pub fn map_err_kind(
863        self,
864        f: impl FnOnce(InterpErrorKind<'tcx>) -> InterpErrorKind<'tcx>,
865    ) -> InterpResult<'tcx, T> {
866        InterpResult_::new(self.disarm().map_err(|mut e| {
867            e.0.kind = f(e.0.kind);
868            e
869        }))
870    }
871
872    #[inline]
873    pub fn inspect_err_kind(self, f: impl FnOnce(&InterpErrorKind<'tcx>)) -> InterpResult<'tcx, T> {
874        InterpResult_::new(self.disarm().inspect_err(|e| f(&e.0.kind)))
875    }
876
877    #[inline]
878    #[track_caller]
879    pub fn unwrap(self) -> T {
880        self.disarm().unwrap()
881    }
882
883    #[inline]
884    #[track_caller]
885    pub fn unwrap_or_else(self, f: impl FnOnce(InterpErrorInfo<'tcx>) -> T) -> T {
886        self.disarm().unwrap_or_else(f)
887    }
888
889    #[inline]
890    #[track_caller]
891    pub fn expect(self, msg: &str) -> T {
892        self.disarm().expect(msg)
893    }
894
895    #[inline]
896    pub fn and_then<U>(self, f: impl FnOnce(T) -> InterpResult<'tcx, U>) -> InterpResult<'tcx, U> {
897        InterpResult_::new(self.disarm().and_then(|t| f(t).disarm()))
898    }
899
900    /// Returns success if both `self` and `other` succeed, while ensuring we don't
901    /// accidentally drop an error.
902    ///
903    /// If both are an error, `self` will be reported.
904    #[inline]
905    pub fn and<U>(self, other: InterpResult<'tcx, U>) -> InterpResult<'tcx, (T, U)> {
906        match self.disarm() {
907            Ok(t) => interp_ok((t, other?)),
908            Err(e) => {
909                // Discard the other error.
910                drop(other.disarm());
911                // Return `self`.
912                InterpResult_::new(Err(e))
913            }
914        }
915    }
916}
917
918#[inline(always)]
919pub fn interp_ok<'tcx, T>(x: T) -> InterpResult<'tcx, T> {
920    InterpResult_::new(Ok(x))
921}
OSZAR »