4 use crate::hir::map::definitions::DefPathData;
6 use crate::ty::{self, Ty, layout};
7 use crate::ty::layout::{Size, Align, LayoutError};
8 use rustc_target::spec::abi::Abi;
9 use rustc_macros::HashStable;
11 use super::{RawConst, Pointer, CheckInAllocMsg, ScalarMaybeUndef};
13 use backtrace::Backtrace;
15 use crate::ty::query::TyCtxtAt;
16 use errors::DiagnosticBuilder;
18 use syntax_pos::{Pos, Span};
19 use syntax::symbol::Symbol;
21 #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable)]
22 pub enum ErrorHandled {
23 /// Already reported a lint or an error for this evaluation.
25 /// Don't emit an error, the evaluation failed because the MIR was generic
26 /// and the substs didn't fully monomorphize it.
31 pub fn assert_reported(self) {
33 ErrorHandled::Reported => {},
34 ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \
35 even though it was fully monomorphized"),
40 CloneTypeFoldableImpls! {
44 pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
45 pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
47 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
48 pub struct ConstEvalErr<'tcx> {
50 pub error: crate::mir::interpret::InterpError<'tcx, u64>,
51 pub stacktrace: Vec<FrameInfo<'tcx>>,
54 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
55 pub struct FrameInfo<'tcx> {
56 /// This span is in the caller.
58 pub instance: ty::Instance<'tcx>,
59 pub lint_root: Option<hir::HirId>,
62 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 if tcx.def_key(self.instance.def_id()).disambiguated_data.data
66 == DefPathData::ClosureExpr
68 write!(f, "inside call to closure")?;
70 write!(f, "inside call to `{}`", self.instance)?;
72 if !self.call_site.is_dummy() {
73 let lo = tcx.sess.source_map().lookup_char_pos(self.call_site.lo());
74 write!(f, " at {}:{}:{}", lo.file.name, lo.line, lo.col.to_usize() + 1)?;
81 impl<'tcx> ConstEvalErr<'tcx> {
86 ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
87 self.struct_generic(tcx, message, None)
90 pub fn report_as_error(&self, tcx: TyCtxtAt<'tcx>, message: &str) -> ErrorHandled {
91 let err = self.struct_error(tcx, message);
95 ErrorHandled::Reported
101 pub fn report_as_lint(
105 lint_root: hir::HirId,
108 let lint = self.struct_generic(
115 if let Some(span) = span {
116 let primary_spans = lint.span.primary_spans().to_vec();
117 // point at the actual error as the primary span
118 lint.replace_span_with(span);
119 // point to the `const` statement as a secondary span
120 // they don't have any label
121 for sp in primary_spans {
123 lint.span_label(sp, "");
128 ErrorHandled::Reported
138 lint_root: Option<hir::HirId>,
139 ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
141 InterpError::Layout(LayoutError::Unknown(_)) |
142 InterpError::TooGeneric => return Err(ErrorHandled::TooGeneric),
143 InterpError::Layout(LayoutError::SizeOverflow(_)) |
144 InterpError::TypeckError => return Err(ErrorHandled::Reported),
147 trace!("reporting const eval failure at {:?}", self.span);
148 let mut err = if let Some(lint_root) = lint_root {
149 let hir_id = self.stacktrace
152 .filter_map(|frame| frame.lint_root)
154 .unwrap_or(lint_root);
155 tcx.struct_span_lint_hir(
156 crate::rustc::lint::builtin::CONST_ERR,
162 struct_error(tcx, message)
164 err.span_label(self.span, self.error.to_string());
165 // Skip the last, which is just the environment of the constant. The stacktrace
166 // is sometimes empty because we create "fake" eval contexts in CTFE to do work
167 // on constant values.
168 if self.stacktrace.len() > 0 {
169 for frame_info in &self.stacktrace[..self.stacktrace.len()-1] {
170 err.span_label(frame_info.call_site, frame_info.to_string());
177 pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'tcx> {
178 struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
181 /// Packages the kind of error we got from the const code interpreter
182 /// up with a Rust-level backtrace of where the error occured.
183 /// Thsese should always be constructed by calling `.into()` on
184 /// a `InterpError`. In `librustc_mir::interpret`, we have the `err!`
186 #[derive(Debug, Clone)]
187 pub struct InterpErrorInfo<'tcx> {
188 pub kind: InterpError<'tcx, u64>,
189 backtrace: Option<Box<Backtrace>>,
192 impl<'tcx> InterpErrorInfo<'tcx> {
193 pub fn print_backtrace(&mut self) {
194 if let Some(ref mut backtrace) = self.backtrace {
195 print_backtrace(&mut *backtrace);
200 fn print_backtrace(backtrace: &mut Backtrace) {
202 eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
205 impl<'tcx> From<InterpError<'tcx, u64>> for InterpErrorInfo<'tcx> {
206 fn from(kind: InterpError<'tcx, u64>) -> Self {
207 let backtrace = match env::var("RUST_CTFE_BACKTRACE") {
208 // Matching `RUST_BACKTRACE` -- we treat "0" the same as "not present".
209 Ok(ref val) if val != "0" => {
210 let mut backtrace = Backtrace::new_unresolved();
212 if val == "immediate" {
214 print_backtrace(&mut backtrace);
217 Some(Box::new(backtrace))
229 pub type AssertMessage<'tcx> = InterpError<'tcx, mir::Operand<'tcx>>;
231 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
232 pub enum EvalErrorPanic<O> {
243 Overflow(mir::BinOp),
249 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
250 pub enum InterpError<'tcx, O> {
251 /// This variant is used by machines to signal their own errors that do not
252 /// match an existing variant.
253 MachineError(String),
255 /// Not actually an interpreter error -- used to signal that execution has exited
256 /// with the given status code. Used by Miri, but not by CTFE.
259 FunctionAbiMismatch(Abi, Abi),
260 FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
261 FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
262 FunctionArgCountMismatch,
264 UnterminatedCString(Pointer),
265 DanglingPointerDeref,
268 InvalidFunctionPointer,
270 InvalidDiscriminant(ScalarMaybeUndef),
273 msg: CheckInAllocMsg,
274 allocation_size: Size,
276 InvalidNullPointerUsage,
281 ReadUndefBytes(Size),
283 InvalidBoolOp(mir::BinOp),
284 Unimplemented(String),
285 DerefFunctionPointer,
287 BoundsCheck { len: O, index: O },
288 Overflow(mir::BinOp),
294 StackFrameLimitReached,
297 AbiViolation(String),
298 AlignmentCheckFailed {
302 ValidationFailure(String),
303 CalledClosureAsFunction,
304 VtableForArgumentlessMethod,
305 ModifiedConstantMemory,
309 TypeNotPrimitive(Ty<'tcx>),
310 ReallocatedWrongMemoryKind(String, String),
311 DeallocatedWrongMemoryKind(String, String),
312 ReallocateNonBasePtr,
313 DeallocateNonBasePtr,
314 IncorrectAllocationInformation(Size, Size, Align, Align),
315 Layout(layout::LayoutError<'tcx>),
317 HeapAllocNonPowerOfTwoAlignment(u64),
319 Panic(EvalErrorPanic<O>),
320 ReadFromReturnPointer,
321 PathNotFound(Vec<String>),
322 UnimplementedTraitSelection,
323 /// Abort in case type errors are reached
325 /// Resolution can fail if we are in a too generic context
327 /// Cannot compute this constant because it depends on another one
328 /// which already produced an error
330 GeneratorResumedAfterReturn,
331 GeneratorResumedAfterPanic,
336 pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
338 impl<'tcx, O> InterpError<'tcx, O> {
339 pub fn description(&self) -> &str {
340 use self::InterpError::*;
342 MachineError(ref inner) => inner,
345 FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
346 | FunctionArgCountMismatch =>
347 "tried to call a function through a function pointer of incompatible type",
348 InvalidMemoryAccess =>
349 "tried to access memory through an invalid pointer",
350 DanglingPointerDeref =>
351 "dangling pointer was dereferenced",
353 "tried to deallocate dangling pointer",
354 InvalidFunctionPointer =>
355 "tried to use a function pointer after offsetting it",
357 "invalid boolean value read",
358 InvalidDiscriminant(..) =>
359 "invalid enum discriminant value read",
360 PointerOutOfBounds { .. } =>
361 "pointer offset outside bounds of allocation",
362 InvalidNullPointerUsage =>
363 "invalid use of NULL pointer",
364 ValidationFailure(..) =>
365 "type validation failed",
366 ReadPointerAsBytes =>
367 "a raw memory access tried to access part of a pointer value as raw bytes",
368 ReadBytesAsPointer =>
369 "a memory access tried to interpret some bytes as a pointer",
371 "tried to read from foreign (extern) static",
372 InvalidPointerMath =>
373 "attempted to do invalid arithmetic on pointers that would leak base addresses, \
374 e.g., comparing pointers into different allocations",
376 "attempted to read undefined bytes",
378 "tried to access a dead local variable",
380 "invalid boolean operation",
381 Unimplemented(ref msg) => msg,
382 DerefFunctionPointer =>
383 "tried to dereference a function pointer",
385 "tried to treat a memory pointer as a function pointer",
387 "array index out of bounds",
393 "tried to interpret an invalid 32-bit value as a char",
394 StackFrameLimitReached =>
395 "reached the configured maximum number of stack frames",
397 "reached the maximum number of representable TLS keys",
399 "accessed an invalid (unallocated) TLS key",
400 AbiViolation(ref msg) => msg,
401 AlignmentCheckFailed{..} =>
402 "tried to execute a misaligned read or write",
403 CalledClosureAsFunction =>
404 "tried to call a closure through a function pointer",
405 VtableForArgumentlessMethod =>
406 "tried to call a vtable function without arguments",
407 ModifiedConstantMemory =>
408 "tried to modify constant memory",
410 "tried to modify a static's initial value from another static's initializer",
412 "`assume` argument was false",
414 "miri does not support inline assembly",
415 TypeNotPrimitive(_) =>
416 "expected primitive type, got nonprimitive",
417 ReallocatedWrongMemoryKind(_, _) =>
418 "tried to reallocate memory from one kind to another",
419 DeallocatedWrongMemoryKind(_, _) =>
420 "tried to deallocate memory of the wrong kind",
421 ReallocateNonBasePtr =>
422 "tried to reallocate with a pointer not to the beginning of an existing object",
423 DeallocateNonBasePtr =>
424 "tried to deallocate with a pointer not to the beginning of an existing object",
425 IncorrectAllocationInformation(..) =>
426 "tried to deallocate or reallocate using incorrect alignment or size",
428 "rustc layout computation failed",
429 UnterminatedCString(_) =>
430 "attempted to get length of a null terminated string, but no null found before end \
432 HeapAllocZeroBytes =>
433 "tried to re-, de- or allocate zero bytes on the heap",
434 HeapAllocNonPowerOfTwoAlignment(_) =>
435 "tried to re-, de-, or allocate heap memory with alignment that is not a power of \
438 "entered unreachable code",
440 "the evaluated program panicked",
441 ReadFromReturnPointer =>
442 "tried to read from the return pointer",
444 "a path could not be resolved, maybe the crate is not loaded",
445 UnimplementedTraitSelection =>
446 "there were unresolved type arguments during trait selection",
448 "encountered constants with type errors, stopping evaluation",
450 "encountered overly generic constant",
451 ReferencedConstant =>
452 "referenced constant has errors",
453 Overflow(mir::BinOp::Add) => "attempt to add with overflow",
454 Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow",
455 Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow",
456 Overflow(mir::BinOp::Div) => "attempt to divide with overflow",
457 Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow",
458 OverflowNeg => "attempt to negate with overflow",
459 Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow",
460 Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow",
461 Overflow(op) => bug!("{:?} cannot overflow", op),
462 DivisionByZero => "attempt to divide by zero",
463 RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
464 GeneratorResumedAfterReturn => "generator resumed after completion",
465 GeneratorResumedAfterPanic => "generator resumed after panicking",
467 "duplicate interpreter state observed here, const evaluation will never terminate",
472 impl<'tcx> fmt::Display for InterpErrorInfo<'tcx> {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 write!(f, "{}", self.kind)
478 impl<'tcx> fmt::Display for InterpError<'tcx, u64> {
479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480 write!(f, "{:?}", self)
484 impl<'tcx, O: fmt::Debug> fmt::Debug for InterpError<'tcx, O> {
485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486 use self::InterpError::*;
488 PointerOutOfBounds { ptr, msg, allocation_size } => {
489 write!(f, "{} failed: pointer must be in-bounds at offset {}, \
490 but is outside bounds of allocation {} which has size {}",
491 msg, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
493 ValidationFailure(ref err) => {
494 write!(f, "type validation failed: {}", err)
496 NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
497 FunctionAbiMismatch(caller_abi, callee_abi) =>
498 write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
499 callee_abi, caller_abi),
500 FunctionArgMismatch(caller_ty, callee_ty) =>
501 write!(f, "tried to call a function with argument of type {:?} \
502 passing data of type {:?}",
503 callee_ty, caller_ty),
504 FunctionRetMismatch(caller_ty, callee_ty) =>
505 write!(f, "tried to call a function with return type {:?} \
506 passing return place of type {:?}",
507 callee_ty, caller_ty),
508 FunctionArgCountMismatch =>
509 write!(f, "tried to call a function with incorrect number of arguments"),
510 BoundsCheck { ref len, ref index } =>
511 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
512 ReallocatedWrongMemoryKind(ref old, ref new) =>
513 write!(f, "tried to reallocate memory from {} to {}", old, new),
514 DeallocatedWrongMemoryKind(ref old, ref new) =>
515 write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
516 Intrinsic(ref err) =>
517 write!(f, "{}", err),
519 write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
520 AlignmentCheckFailed { required, has } =>
521 write!(f, "tried to access memory with alignment {}, but alignment {} is required",
522 has.bytes(), required.bytes()),
523 TypeNotPrimitive(ty) =>
524 write!(f, "expected primitive type, got {}", ty),
526 write!(f, "rustc layout computation failed: {:?}", err),
527 PathNotFound(ref path) =>
528 write!(f, "Cannot find path {:?}", path),
529 MachineError(ref inner) =>
530 write!(f, "{}", inner),
531 IncorrectAllocationInformation(size, size2, align, align2) =>
532 write!(f, "incorrect alloc info: expected size {} and align {}, \
533 got size {} and align {}",
534 size.bytes(), align.bytes(), size2.bytes(), align2.bytes()),
536 write!(f, "the evaluated program panicked"),
537 InvalidDiscriminant(val) =>
538 write!(f, "encountered invalid enum discriminant {}", val),
540 write!(f, "exited with status code {}", code),
541 _ => write!(f, "{}", self.description()),