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