]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/mir/interpret/error.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / compiler / rustc_middle / src / mir / interpret / error.rs
CommitLineData
1b1a35ee 1use super::{AllocId, ConstAlloc, Pointer, Scalar};
ea8adc8c 2
74b04a01 3use crate::mir::interpret::ConstValue;
3dfed10e 4use crate::ty::{layout, query::TyCtxtAt, tls, FnSig, Ty};
ea8adc8c 5
ba9703b0 6use rustc_data_structures::sync::Lock;
5e7ed085 7use rustc_errors::{pluralize, struct_span_err, DiagnosticBuilder, ErrorGuaranteed};
e1599b0c 8use rustc_macros::HashStable;
ba9703b0 9use rustc_session::CtfeBacktrace;
3dfed10e 10use rustc_span::def_id::DefId;
a2a8927a 11use rustc_target::abi::{call, Align, Size};
6a06907d 12use std::{any::Any, backtrace::Backtrace, fmt};
e1599b0c 13
3dfed10e 14#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
a1dfa0c6 15pub enum ErrorHandled {
ba9703b0
XL
16 /// Already reported an error for this evaluation, and the compilation is
17 /// *guaranteed* to fail. Warnings/lints *must not* produce `Reported`.
5e7ed085 18 Reported(ErrorGuaranteed),
ba9703b0
XL
19 /// Already emitted a lint for this evaluation.
20 Linted,
a1dfa0c6
XL
21 /// Don't emit an error, the evaluation failed because the MIR was generic
22 /// and the substs didn't fully monomorphize it.
23 TooGeneric,
24}
25
5e7ed085
FG
26impl From<ErrorGuaranteed> for ErrorHandled {
27 fn from(err: ErrorGuaranteed) -> ErrorHandled {
1b1a35ee
XL
28 ErrorHandled::Reported(err)
29 }
30}
31
fc512014 32TrivialTypeFoldableAndLiftImpls! {
dc9dc135
XL
33 ErrorHandled,
34}
35
1b1a35ee
XL
36pub type EvalToAllocationRawResult<'tcx> = Result<ConstAlloc<'tcx>, ErrorHandled>;
37pub type EvalToConstValueResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>;
8faf50e0 38
5e7ed085
FG
39pub fn struct_error<'tcx>(
40 tcx: TyCtxtAt<'tcx>,
41 msg: &str,
42) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
8faf50e0
XL
43 struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
44}
45
6a06907d
XL
46#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
47static_assert_size!(InterpErrorInfo<'_>, 8);
48
dc9dc135 49/// Packages the kind of error we got from the const code interpreter
60c5eb7d 50/// up with a Rust-level backtrace of where the error occurred.
cdc7bbd5 51/// These should always be constructed by calling `.into()` on
94222f64 52/// an `InterpError`. In `rustc_mir::interpret`, we have `throw_err_*`
416331ca 53/// macros for this.
60c5eb7d 54#[derive(Debug)]
6a06907d
XL
55pub struct InterpErrorInfo<'tcx>(Box<InterpErrorInfoInner<'tcx>>);
56
57#[derive(Debug)]
58struct InterpErrorInfoInner<'tcx> {
59 kind: InterpError<'tcx>,
dc9dc135 60 backtrace: Option<Box<Backtrace>>,
a1dfa0c6
XL
61}
62
416331ca
XL
63impl fmt::Display for InterpErrorInfo<'_> {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6a06907d 65 write!(f, "{}", self.0.kind)
416331ca
XL
66 }
67}
68
a2a8927a 69impl<'tcx> InterpErrorInfo<'tcx> {
f9f354fc 70 pub fn print_backtrace(&self) {
6a06907d 71 if let Some(backtrace) = self.0.backtrace.as_ref() {
f9f354fc 72 print_backtrace(backtrace);
a1dfa0c6
XL
73 }
74 }
6a06907d
XL
75
76 pub fn into_kind(self) -> InterpError<'tcx> {
77 let InterpErrorInfo(box InterpErrorInfoInner { kind, .. }) = self;
78 kind
79 }
80
81 #[inline]
82 pub fn kind(&self) -> &InterpError<'tcx> {
83 &self.0.kind
84 }
a1dfa0c6
XL
85}
86
f9f354fc
XL
87fn print_backtrace(backtrace: &Backtrace) {
88 eprintln!("\n\nAn error occurred in miri:\n{}", backtrace);
ea8adc8c
XL
89}
90
74b04a01 91impl From<ErrorHandled> for InterpErrorInfo<'_> {
e1599b0c
XL
92 fn from(err: ErrorHandled) -> Self {
93 match err {
5e7ed085 94 ErrorHandled::Reported(ErrorGuaranteed { .. }) | ErrorHandled::Linted => {
ba9703b0
XL
95 err_inval!(ReferencedConstant)
96 }
e1599b0c 97 ErrorHandled::TooGeneric => err_inval!(TooGeneric),
dfeec247
XL
98 }
99 .into()
e1599b0c
XL
100 }
101}
102
5e7ed085
FG
103impl From<ErrorGuaranteed> for InterpErrorInfo<'_> {
104 fn from(err: ErrorGuaranteed) -> Self {
29967ef6
XL
105 InterpError::InvalidProgram(InvalidProgramInfo::AlreadyReported(err)).into()
106 }
107}
108
416331ca
XL
109impl<'tcx> From<InterpError<'tcx>> for InterpErrorInfo<'tcx> {
110 fn from(kind: InterpError<'tcx>) -> Self {
3dfed10e
XL
111 let capture_backtrace = tls::with_opt(|tcx| {
112 if let Some(tcx) = tcx {
113 *Lock::borrow(&tcx.sess.ctfe_backtrace)
ba9703b0
XL
114 } else {
115 CtfeBacktrace::Disabled
116 }
117 });
a1dfa0c6 118
ba9703b0
XL
119 let backtrace = match capture_backtrace {
120 CtfeBacktrace::Disabled => None,
f9f354fc 121 CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())),
ba9703b0
XL
122 CtfeBacktrace::Immediate => {
123 // Print it now.
f9f354fc
XL
124 let backtrace = Backtrace::force_capture();
125 print_backtrace(&backtrace);
ba9703b0 126 None
dfeec247 127 }
a1dfa0c6 128 };
ba9703b0 129
6a06907d 130 InterpErrorInfo(Box::new(InterpErrorInfoInner { kind, backtrace }))
ea8adc8c
XL
131 }
132}
133
e1599b0c
XL
134/// Error information for when the program we executed turned out not to actually be a valid
135/// program. This cannot happen in stand-alone Miri, but it can happen during CTFE/ConstProp
136/// where we work on generic code or execution does not have all information available.
416331ca
XL
137pub enum InvalidProgramInfo<'tcx> {
138 /// Resolution can fail if we are in a too generic context.
139 TooGeneric,
140 /// Cannot compute this constant because it depends on another one
141 /// which already produced an error.
142 ReferencedConstant,
29967ef6 143 /// Abort in case errors are already reported.
5e7ed085 144 AlreadyReported(ErrorGuaranteed),
416331ca
XL
145 /// An error occurred during layout computation.
146 Layout(layout::LayoutError<'tcx>),
a2a8927a
XL
147 /// An error occurred during FnAbi computation: the passed --target lacks FFI support
148 /// (which unfortunately typeck does not reject).
149 /// Not using `FnAbiError` as that contains a nested `LayoutError`.
150 FnAbiAdjustForForeignAbi(call::AdjustForForeignAbiError),
ba9703b0
XL
151 /// An invalid transmute happened.
152 TransmuteSizeDiff(Ty<'tcx>, Ty<'tcx>),
5869c6ff
XL
153 /// SizeOf of unsized type was requested.
154 SizeOfUnsizedType(Ty<'tcx>),
416331ca 155}
b7449926 156
f9f354fc 157impl fmt::Display for InvalidProgramInfo<'_> {
416331ca
XL
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 use InvalidProgramInfo::*;
160 match self {
dfeec247
XL
161 TooGeneric => write!(f, "encountered overly generic constant"),
162 ReferencedConstant => write!(f, "referenced constant has errors"),
5e7ed085 163 AlreadyReported(ErrorGuaranteed { .. }) => {
ba9703b0
XL
164 write!(f, "encountered constants with type errors, stopping evaluation")
165 }
dfeec247 166 Layout(ref err) => write!(f, "{}", err),
a2a8927a 167 FnAbiAdjustForForeignAbi(ref err) => write!(f, "{}", err),
ba9703b0
XL
168 TransmuteSizeDiff(from_ty, to_ty) => write!(
169 f,
170 "transmuting `{}` to `{}` is not possible, because these types do not have the same size",
171 from_ty, to_ty
172 ),
5869c6ff 173 SizeOfUnsizedType(ty) => write!(f, "size_of called on unsized type `{}`", ty),
416331ca
XL
174 }
175 }
176}
177
f9f354fc 178/// Details of why a pointer had to be in-bounds.
3dfed10e 179#[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)]
f9f354fc 180pub enum CheckInAllocMsg {
136023e0
XL
181 /// We are dereferencing a pointer (i.e., creating a place).
182 DerefTest,
17df50a5 183 /// We are access memory.
f9f354fc 184 MemoryAccessTest,
17df50a5 185 /// We are doing pointer arithmetic.
f9f354fc 186 PointerArithmeticTest,
5e7ed085
FG
187 /// We are doing pointer offset_from.
188 OffsetFromTest,
17df50a5 189 /// None of the above -- generic/unspecific inbounds test.
f9f354fc
XL
190 InboundsTest,
191}
192
193impl fmt::Display for CheckInAllocMsg {
136023e0
XL
194 /// When this is printed as an error the context looks like this:
195 /// "{msg}0x01 is not a valid pointer".
f9f354fc
XL
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 write!(
198 f,
199 "{}",
200 match *self {
136023e0 201 CheckInAllocMsg::DerefTest => "dereferencing pointer failed: ",
17df50a5
XL
202 CheckInAllocMsg::MemoryAccessTest => "memory access failed: ",
203 CheckInAllocMsg::PointerArithmeticTest => "pointer arithmetic failed: ",
5e7ed085 204 CheckInAllocMsg::OffsetFromTest => "out-of-bounds offset_from: ",
17df50a5 205 CheckInAllocMsg::InboundsTest => "",
f9f354fc
XL
206 }
207 )
208 }
209}
210
211/// Details of an access to uninitialized bytes where it is not allowed.
212#[derive(Debug)]
213pub struct UninitBytesAccess {
214 /// Location of the original memory access.
17df50a5 215 pub access_offset: Size,
f9f354fc
XL
216 /// Size of the original memory access.
217 pub access_size: Size,
218 /// Location of the first uninitialized byte that was accessed.
17df50a5 219 pub uninit_offset: Size,
f9f354fc
XL
220 /// Number of consecutive uninitialized bytes that were accessed.
221 pub uninit_size: Size,
222}
223
e1599b0c 224/// Error information for when the program caused Undefined Behavior.
f9f354fc 225pub enum UndefinedBehaviorInfo<'tcx> {
416331ca
XL
226 /// Free-form case. Only for errors that are never caught!
227 Ub(String),
416331ca
XL
228 /// Unreachable code was executed.
229 Unreachable,
60c5eb7d 230 /// A slice/array index projection went out-of-bounds.
ba9703b0
XL
231 BoundsCheckFailed {
232 len: u64,
233 index: u64,
234 },
60c5eb7d
XL
235 /// Something was divided by 0 (x / 0).
236 DivisionByZero,
237 /// Something was "remainded" by 0 (x % 0).
238 RemainderByZero,
5e7ed085
FG
239 /// Signed division overflowed (INT_MIN / -1).
240 DivisionOverflow,
241 /// Signed remainder overflowed (INT_MIN % -1).
242 RemainderOverflow,
60c5eb7d
XL
243 /// Overflowing inbounds pointer arithmetic.
244 PointerArithOverflow,
74b04a01
XL
245 /// Invalid metadata in a wide pointer (using `str` to avoid allocations).
246 InvalidMeta(&'static str),
f9f354fc 247 /// Invalid drop function in vtable.
136023e0
XL
248 InvalidVtableDropFn(FnSig<'tcx>),
249 /// Invalid size in a vtable: too large.
250 InvalidVtableSize,
251 /// Invalid alignment in a vtable: too large, or not a power of 2.
252 InvalidVtableAlignment(String),
ba9703b0
XL
253 /// Reading a C string that does not end within its allocation.
254 UnterminatedCString(Pointer),
255 /// Dereferencing a dangling pointer after it got freed.
256 PointerUseAfterFree(AllocId),
257 /// Used a pointer outside the bounds it is valid for.
136023e0 258 /// (If `ptr_size > 0`, determines the size of the memory range that was expected to be in-bounds.)
ba9703b0 259 PointerOutOfBounds {
136023e0
XL
260 alloc_id: AllocId,
261 alloc_size: Size,
262 ptr_offset: i64,
263 ptr_size: Size,
ba9703b0 264 msg: CheckInAllocMsg,
ba9703b0 265 },
f9f354fc
XL
266 /// Using an integer as a pointer in the wrong way.
267 DanglingIntPointer(u64, CheckInAllocMsg),
ba9703b0
XL
268 /// Used a pointer with bad alignment.
269 AlignmentCheckFailed {
270 required: Align,
271 has: Align,
272 },
ba9703b0
XL
273 /// Writing to read-only memory.
274 WriteToReadOnly(AllocId),
ba9703b0
XL
275 // Trying to access the data behind a function pointer.
276 DerefFunctionPointer(AllocId),
277 /// The value validity check found a problem.
278 /// Should only be thrown by `validity.rs` and always point out which part of the value
279 /// is the problem.
136023e0
XL
280 ValidationFailure {
281 /// The "path" to the value in question, e.g. `.0[5].field` for a struct
282 /// field in the 6th element of an array that is the first element of a tuple.
283 path: Option<String>,
284 msg: String,
285 },
ba9703b0
XL
286 /// Using a non-boolean `u8` as bool.
287 InvalidBool(u8),
288 /// Using a non-character `u32` as character.
289 InvalidChar(u32),
f035d41b
XL
290 /// The tag of an enum does not encode an actual discriminant.
291 InvalidTag(Scalar),
f9f354fc
XL
292 /// Using a pointer-not-to-a-function as function pointer.
293 InvalidFunctionPointer(Pointer),
294 /// Using a string that is not valid UTF-8,
295 InvalidStr(std::str::Utf8Error),
ba9703b0 296 /// Using uninitialized data where it is not allowed.
17df50a5 297 InvalidUninitBytes(Option<(AllocId, UninitBytesAccess)>),
ba9703b0
XL
298 /// Working with a local that is not currently live.
299 DeadLocal,
f9f354fc
XL
300 /// Data size is not equal to target size.
301 ScalarSizeMismatch {
302 target_size: u64,
303 data_size: u64,
304 },
c295e0f8
XL
305 /// A discriminant of an uninhabited enum variant is written.
306 UninhabitedEnumVariantWritten,
416331ca 307}
48663c56 308
f9f354fc 309impl fmt::Display for UndefinedBehaviorInfo<'_> {
416331ca
XL
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 use UndefinedBehaviorInfo::*;
312 match self {
ba9703b0 313 Ub(msg) => write!(f, "{}", msg),
dfeec247 314 Unreachable => write!(f, "entering unreachable code"),
f9f354fc
XL
315 BoundsCheckFailed { ref len, ref index } => {
316 write!(f, "indexing out of bounds: the len is {} but the index is {}", len, index)
317 }
dfeec247
XL
318 DivisionByZero => write!(f, "dividing by zero"),
319 RemainderByZero => write!(f, "calculating the remainder with a divisor of zero"),
5e7ed085
FG
320 DivisionOverflow => write!(f, "overflow in signed division (dividing MIN by -1)"),
321 RemainderOverflow => write!(f, "overflow in signed remainder (dividing MIN by -1)"),
dfeec247 322 PointerArithOverflow => write!(f, "overflowing in-bounds pointer arithmetic"),
74b04a01 323 InvalidMeta(msg) => write!(f, "invalid metadata in wide pointer: {}", msg),
136023e0 324 InvalidVtableDropFn(sig) => write!(
f9f354fc
XL
325 f,
326 "invalid drop function signature: got {}, expected exactly one argument which must be a pointer type",
327 sig
328 ),
136023e0
XL
329 InvalidVtableSize => {
330 write!(f, "invalid vtable: size is bigger than largest supported object")
331 }
332 InvalidVtableAlignment(msg) => write!(f, "invalid vtable: alignment {}", msg),
ba9703b0
XL
333 UnterminatedCString(p) => write!(
334 f,
136023e0 335 "reading a null-terminated string starting at {:?} with no null found before end of allocation",
ba9703b0
XL
336 p,
337 ),
338 PointerUseAfterFree(a) => {
f9f354fc 339 write!(f, "pointer to {} was dereferenced after this allocation got freed", a)
ba9703b0 340 }
136023e0
XL
341 PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size: Size::ZERO, msg } => {
342 write!(
343 f,
344 "{}{alloc_id} has size {alloc_size}, so pointer at offset {ptr_offset} is out-of-bounds",
345 msg,
346 alloc_id = alloc_id,
347 alloc_size = alloc_size.bytes(),
348 ptr_offset = ptr_offset,
349 )
350 }
351 PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => write!(
ba9703b0 352 f,
136023e0 353 "{}{alloc_id} has size {alloc_size}, so pointer to {ptr_size} byte{ptr_size_p} starting at offset {ptr_offset} is out-of-bounds",
ba9703b0 354 msg,
136023e0
XL
355 alloc_id = alloc_id,
356 alloc_size = alloc_size.bytes(),
357 ptr_size = ptr_size.bytes(),
358 ptr_size_p = pluralize!(ptr_size.bytes()),
359 ptr_offset = ptr_offset,
ba9703b0 360 ),
17df50a5
XL
361 DanglingIntPointer(0, CheckInAllocMsg::InboundsTest) => {
362 write!(f, "null pointer is not a valid pointer for this operation")
f9f354fc 363 }
5e7ed085
FG
364 DanglingIntPointer(0, msg) => {
365 write!(f, "{}null pointer is not a valid pointer", msg)
366 }
f9f354fc 367 DanglingIntPointer(i, msg) => {
17df50a5 368 write!(f, "{}0x{:x} is not a valid pointer", msg, i)
f9f354fc 369 }
ba9703b0
XL
370 AlignmentCheckFailed { required, has } => write!(
371 f,
372 "accessing memory with alignment {}, but alignment {} is required",
373 has.bytes(),
374 required.bytes()
375 ),
f9f354fc
XL
376 WriteToReadOnly(a) => write!(f, "writing to {} which is read-only", a),
377 DerefFunctionPointer(a) => write!(f, "accessing {} which contains a function", a),
136023e0
XL
378 ValidationFailure { path: None, msg } => write!(f, "type validation failed: {}", msg),
379 ValidationFailure { path: Some(path), msg } => {
380 write!(f, "type validation failed at {}: {}", path, msg)
381 }
f9f354fc
XL
382 InvalidBool(b) => {
383 write!(f, "interpreting an invalid 8-bit value as a bool: 0x{:02x}", b)
384 }
385 InvalidChar(c) => {
386 write!(f, "interpreting an invalid 32-bit value as a char: 0x{:08x}", c)
387 }
5e7ed085 388 InvalidTag(val) => write!(f, "enum value has invalid tag: {:x}", val),
ba9703b0 389 InvalidFunctionPointer(p) => {
136023e0 390 write!(f, "using {:?} as function pointer but it does not point to a function", p)
ba9703b0 391 }
f9f354fc 392 InvalidStr(err) => write!(f, "this string is not valid UTF-8: {}", err),
17df50a5 393 InvalidUninitBytes(Some((alloc, access))) => write!(
ba9703b0 394 f,
136023e0
XL
395 "reading {} byte{} of memory starting at {:?}, \
396 but {} byte{} {} uninitialized starting at {:?}, \
f9f354fc
XL
397 and this operation requires initialized memory",
398 access.access_size.bytes(),
399 pluralize!(access.access_size.bytes()),
17df50a5 400 Pointer::new(*alloc, access.access_offset),
f9f354fc
XL
401 access.uninit_size.bytes(),
402 pluralize!(access.uninit_size.bytes()),
5e7ed085 403 pluralize!("is", access.uninit_size.bytes()),
17df50a5 404 Pointer::new(*alloc, access.uninit_offset),
ba9703b0 405 ),
f9f354fc 406 InvalidUninitBytes(None) => write!(
ba9703b0
XL
407 f,
408 "using uninitialized data, but this operation requires initialized memory"
409 ),
410 DeadLocal => write!(f, "accessing a dead local variable"),
f9f354fc
XL
411 ScalarSizeMismatch { target_size, data_size } => write!(
412 f,
413 "scalar size mismatch: expected {} bytes but got {} bytes instead",
414 target_size, data_size
415 ),
c295e0f8
XL
416 UninhabitedEnumVariantWritten => {
417 write!(f, "writing discriminant of an uninhabited enum")
418 }
416331ca
XL
419 }
420 }
421}
422
e1599b0c
XL
423/// Error information for when the program did something that might (or might not) be correct
424/// to do according to the Rust spec, but due to limitations in the interpreter, the
425/// operation could not be carried out. These limitations can differ between CTFE and the
f9f354fc 426/// Miri engine, e.g., CTFE does not support dereferencing pointers at integral addresses.
ba9703b0 427pub enum UnsupportedOpInfo {
416331ca
XL
428 /// Free-form case. Only for errors that are never caught!
429 Unsupported(String),
ba9703b0 430 /// Encountered a pointer where we needed raw bytes.
ea8adc8c 431 ReadPointerAsBytes,
94222f64
XL
432 /// Overwriting parts of a pointer; the resulting state cannot be represented in our
433 /// `Allocation` data structure.
434 PartialPointerOverwrite(Pointer<AllocId>),
f9f354fc
XL
435 //
436 // The variants below are only reachable from CTFE/const prop, miri will never emit them.
437 //
f9f354fc
XL
438 /// Accessing thread local statics
439 ThreadLocalStatic(DefId),
3dfed10e
XL
440 /// Accessing an unsupported extern static.
441 ReadExternStatic(DefId),
ea8adc8c
XL
442}
443
f9f354fc 444impl fmt::Display for UnsupportedOpInfo {
a1dfa0c6 445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416331ca
XL
446 use UnsupportedOpInfo::*;
447 match self {
dfeec247 448 Unsupported(ref msg) => write!(f, "{}", msg),
94222f64
XL
449 ReadPointerAsBytes => write!(f, "unable to turn pointer into raw bytes"),
450 PartialPointerOverwrite(ptr) => {
451 write!(f, "unable to overwrite parts of a pointer in memory at {:?}", ptr)
452 }
f9f354fc 453 ThreadLocalStatic(did) => write!(f, "cannot access thread local static ({:?})", did),
94222f64 454 ReadExternStatic(did) => write!(f, "cannot read from extern static ({:?})", did),
416331ca
XL
455 }
456 }
457}
458
e1599b0c
XL
459/// Error information for when the program exhausted the resources granted to it
460/// by the interpreter.
416331ca
XL
461pub enum ResourceExhaustionInfo {
462 /// The stack grew too big.
463 StackFrameLimitReached,
ba9703b0
XL
464 /// The program ran for too long.
465 ///
466 /// The exact limit is set by the `const_eval_limit` attribute.
467 StepLimitReached,
136023e0
XL
468 /// There is not enough memory to perform an allocation.
469 MemoryExhausted,
416331ca
XL
470}
471
f9f354fc 472impl fmt::Display for ResourceExhaustionInfo {
416331ca
XL
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 use ResourceExhaustionInfo::*;
475 match self {
dfeec247
XL
476 StackFrameLimitReached => {
477 write!(f, "reached the configured maximum number of stack frames")
478 }
ba9703b0
XL
479 StepLimitReached => {
480 write!(f, "exceeded interpreter step limit (see `#[const_eval_limit]`)")
481 }
136023e0
XL
482 MemoryExhausted => {
483 write!(f, "tried to allocate more memory than available to compiler")
484 }
416331ca
XL
485 }
486 }
487}
488
ba9703b0
XL
489/// A trait to work around not having trait object upcasting.
490pub trait AsAny: Any {
491 fn as_any(&self) -> &dyn Any;
492}
ba9703b0
XL
493impl<T: Any> AsAny for T {
494 #[inline(always)]
495 fn as_any(&self) -> &dyn Any {
496 self
497 }
498}
499
500/// A trait for machine-specific errors (or other "machine stop" conditions).
17df50a5
XL
501pub trait MachineStopType: AsAny + fmt::Display + Send {
502 /// If `true`, emit a hard error instead of going through the `CONST_ERR` lint
503 fn is_hard_err(&self) -> bool {
504 false
505 }
506}
ba9703b0
XL
507
508impl dyn MachineStopType {
509 #[inline(always)]
510 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
511 self.as_any().downcast_ref()
512 }
513}
514
416331ca 515pub enum InterpError<'tcx> {
416331ca 516 /// The program caused undefined behavior.
f9f354fc 517 UndefinedBehavior(UndefinedBehaviorInfo<'tcx>),
416331ca
XL
518 /// The program did something the interpreter does not support (some of these *might* be UB
519 /// but the interpreter is not sure).
ba9703b0 520 Unsupported(UnsupportedOpInfo),
60c5eb7d 521 /// The program was invalid (ill-typed, bad MIR, not sufficiently monomorphized, ...).
416331ca
XL
522 InvalidProgram(InvalidProgramInfo<'tcx>),
523 /// The program exhausted the interpreter's resources (stack/heap too big,
60c5eb7d 524 /// execution takes too long, ...).
416331ca 525 ResourceExhaustion(ResourceExhaustionInfo),
60c5eb7d
XL
526 /// Stop execution for a machine-controlled reason. This is never raised by
527 /// the core engine itself.
ba9703b0 528 MachineStop(Box<dyn MachineStopType>),
416331ca
XL
529}
530
531pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
532
533impl fmt::Display for InterpError<'_> {
534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f9f354fc
XL
535 use InterpError::*;
536 match *self {
537 Unsupported(ref msg) => write!(f, "{}", msg),
538 InvalidProgram(ref msg) => write!(f, "{}", msg),
539 UndefinedBehavior(ref msg) => write!(f, "{}", msg),
540 ResourceExhaustion(ref msg) => write!(f, "{}", msg),
541 MachineStop(ref msg) => write!(f, "{}", msg),
542 }
416331ca
XL
543 }
544}
545
f9f354fc 546// Forward `Debug` to `Display`, so it does not look awful.
416331ca
XL
547impl fmt::Debug for InterpError<'_> {
548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f9f354fc 549 fmt::Display::fmt(self, f)
74b04a01
XL
550 }
551}
552
553impl InterpError<'_> {
136023e0 554 /// Some errors do string formatting even if the error is never printed.
6a06907d
XL
555 /// To avoid performance issues, there are places where we want to be sure to never raise these formatting errors,
556 /// so this method lets us detect them and `bug!` on unexpected errors.
557 pub fn formatted_string(&self) -> bool {
3c0e092e
XL
558 matches!(
559 self,
ba9703b0 560 InterpError::Unsupported(UnsupportedOpInfo::Unsupported(_))
3c0e092e
XL
561 | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::ValidationFailure { .. })
562 | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_))
563 )
ea8adc8c 564 }
136023e0
XL
565
566 /// Should this error be reported as a hard error, preventing compilation, or a soft error,
567 /// causing a deny-by-default lint?
568 pub fn is_hard_err(&self) -> bool {
569 use InterpError::*;
570 match *self {
571 MachineStop(ref err) => err.is_hard_err(),
572 UndefinedBehavior(_) => true,
573 ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted) => true,
574 _ => false,
575 }
576 }
ea8adc8c 577}