1use std::any::Any;
2use std::backtrace::Backtrace;
3use std::borrow::Cow;
4use std::{convert, fmt, mem, ops};
56use either::Either;
7use rustc_abi::{Align, Size, VariantIdx};
8use rustc_data_structures::sync::Lock;
9use rustc_errors::{DiagArgValue, ErrorGuaranteed, IntoDiagArg};
10use rustc_macros::{StableHash, TyDecodable, TyEncodable};
11use rustc_session::CtfeBacktrace;
12use rustc_span::def_id::DefId;
13use rustc_span::{DUMMY_SP, Span, Symbol};
1415use super::{AllocId, AllocRange, ConstAllocation, Pointer, Scalar};
16use crate::error;
17use crate::mir::interpret::CtfeProvenance;
18use crate::mir::{ConstAlloc, ConstValue};
19use crate::ty::{self, Ty, TyCtxt, ValTree, layout, tls};
2021#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ErrorHandled {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ErrorHandled::Reported(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Reported", __self_0, &__self_1),
ErrorHandled::TooGeneric(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TooGeneric", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ErrorHandled { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ErrorHandled {
#[inline]
fn clone(&self) -> ErrorHandled {
let _: ::core::clone::AssertParamIsClone<ReportedErrorInfo>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ErrorHandled {
#[inline]
fn eq(&self, other: &ErrorHandled) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ErrorHandled::Reported(__self_0, __self_1),
ErrorHandled::Reported(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(ErrorHandled::TooGeneric(__self_0),
ErrorHandled::TooGeneric(__arg1_0)) => __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ErrorHandled {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ReportedErrorInfo>;
let _: ::core::cmp::AssertParamIsEq<Span>;
}
}Eq, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for ErrorHandled
{
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
ErrorHandled::Reported(ref __binding_0, ref __binding_1) =>
{
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
ErrorHandled::TooGeneric(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for ErrorHandled {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
ErrorHandled::Reported(ref __binding_0, ref __binding_1) =>
{
0usize
}
ErrorHandled::TooGeneric(ref __binding_0) => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
ErrorHandled::Reported(ref __binding_0, ref __binding_1) =>
{
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
ErrorHandled::TooGeneric(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for ErrorHandled {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
ErrorHandled::Reported(::rustc_serialize::Decodable::decode(__decoder),
::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
ErrorHandled::TooGeneric(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `ErrorHandled`, expected 0..2, actual {0}",
n));
}
}
}
}
};TyDecodable)]
22pub enum ErrorHandled {
23/// Already reported an error for this evaluation, and the compilation is
24 /// *guaranteed* to fail. Warnings/lints *must not* produce `Reported`.
25Reported(ReportedErrorInfo, Span),
26/// Don't emit an error, the evaluation failed because the MIR was generic
27 /// and the args didn't fully monomorphize it.
28TooGeneric(Span),
29}
3031impl From<ReportedErrorInfo> for ErrorHandled {
32#[inline]
33fn from(error: ReportedErrorInfo) -> ErrorHandled {
34 ErrorHandled::Reported(error, DUMMY_SP)
35 }
36}
3738impl ErrorHandled {
39pub(crate) fn with_span(self, span: Span) -> Self {
40match self {
41 ErrorHandled::Reported(err, _span) => ErrorHandled::Reported(err, span),
42 ErrorHandled::TooGeneric(_span) => ErrorHandled::TooGeneric(span),
43 }
44 }
4546pub fn emit_note(&self, tcx: TyCtxt<'_>) {
47match self {
48&ErrorHandled::Reported(err, span) => {
49if !err.allowed_in_infallible && !span.is_dummy() {
50tcx.dcx().emit_note(error::ErroneousConstant { span });
51 }
52 }
53&ErrorHandled::TooGeneric(_) => {}
54 }
55 }
56}
5758#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ReportedErrorInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ReportedErrorInfo", "error", &self.error,
"allowed_in_infallible", &&self.allowed_in_infallible)
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReportedErrorInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReportedErrorInfo {
#[inline]
fn clone(&self) -> ReportedErrorInfo {
let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReportedErrorInfo {
#[inline]
fn eq(&self, other: &ReportedErrorInfo) -> bool {
self.allowed_in_infallible == other.allowed_in_infallible &&
self.error == other.error
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReportedErrorInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ErrorGuaranteed>;
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
ReportedErrorInfo {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
ReportedErrorInfo {
error: ref __binding_0,
allowed_in_infallible: ref __binding_1 } => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for ReportedErrorInfo {
fn encode(&self, __encoder: &mut __E) {
match *self {
ReportedErrorInfo {
error: ref __binding_0,
allowed_in_infallible: ref __binding_1 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for ReportedErrorInfo {
fn decode(__decoder: &mut __D) -> Self {
ReportedErrorInfo {
error: ::rustc_serialize::Decodable::decode(__decoder),
allowed_in_infallible: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};TyDecodable)]
59pub struct ReportedErrorInfo {
60 error: ErrorGuaranteed,
61/// Whether this error is allowed to show up even in otherwise "infallible" promoteds.
62 /// This is for things like overflows during size computation or resource exhaustion.
63allowed_in_infallible: bool,
64}
6566impl ReportedErrorInfo {
67#[inline]
68pub fn const_eval_error(error: ErrorGuaranteed) -> ReportedErrorInfo {
69ReportedErrorInfo { allowed_in_infallible: false, error }
70 }
7172/// Use this when the error that led to this is *not* a const-eval error
73 /// (e.g., a layout or type checking error).
74#[inline]
75pub fn non_const_eval_error(error: ErrorGuaranteed) -> ReportedErrorInfo {
76ReportedErrorInfo { allowed_in_infallible: true, error }
77 }
7879/// Use this when the error that led to this *is* a const-eval error, but
80 /// we do allow it to occur in infallible constants (e.g., resource exhaustion).
81#[inline]
82pub fn allowed_in_infallible(error: ErrorGuaranteed) -> ReportedErrorInfo {
83ReportedErrorInfo { allowed_in_infallible: true, error }
84 }
8586pub fn is_allowed_in_infallible(&self) -> bool {
87self.allowed_in_infallible
88 }
89}
9091impl From<ReportedErrorInfo> for ErrorGuaranteed {
92#[inline]
93fn from(val: ReportedErrorInfo) -> Self {
94val.error
95 }
96}
9798/// An error type for the `const_to_valtree` query. Some error should be reported with a "use-site span",
99/// which means the query cannot emit the error, so those errors are represented as dedicated variants here.
100#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ValTreeCreationError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ValTreeCreationError::NodesOverflow =>
::core::fmt::Formatter::write_str(f, "NodesOverflow"),
ValTreeCreationError::InvalidConst =>
::core::fmt::Formatter::write_str(f, "InvalidConst"),
ValTreeCreationError::NonSupportedType(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonSupportedType", &__self_0),
ValTreeCreationError::CyclicConst =>
::core::fmt::Formatter::write_str(f, "CyclicConst"),
ValTreeCreationError::ErrorHandled(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ErrorHandled", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ValTreeCreationError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ValTreeCreationError<'tcx> {
#[inline]
fn clone(&self) -> ValTreeCreationError<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ErrorHandled>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ValTreeCreationError<'tcx> {
#[inline]
fn eq(&self, other: &ValTreeCreationError<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ValTreeCreationError::NonSupportedType(__self_0),
ValTreeCreationError::NonSupportedType(__arg1_0)) =>
__self_0 == __arg1_0,
(ValTreeCreationError::ErrorHandled(__self_0),
ValTreeCreationError::ErrorHandled(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for ValTreeCreationError<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
let _: ::core::cmp::AssertParamIsEq<ErrorHandled>;
}
}Eq, const _: () =
{
impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
ValTreeCreationError<'tcx> {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
ValTreeCreationError::NodesOverflow => {}
ValTreeCreationError::InvalidConst => {}
ValTreeCreationError::NonSupportedType(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
ValTreeCreationError::CyclicConst => {}
ValTreeCreationError::ErrorHandled(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for ValTreeCreationError<'tcx> {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
ValTreeCreationError::NodesOverflow => { 0usize }
ValTreeCreationError::InvalidConst => { 1usize }
ValTreeCreationError::NonSupportedType(ref __binding_0) => {
2usize
}
ValTreeCreationError::CyclicConst => { 3usize }
ValTreeCreationError::ErrorHandled(ref __binding_0) => {
4usize
}
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
ValTreeCreationError::NodesOverflow => {}
ValTreeCreationError::InvalidConst => {}
ValTreeCreationError::NonSupportedType(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
ValTreeCreationError::CyclicConst => {}
ValTreeCreationError::ErrorHandled(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for ValTreeCreationError<'tcx> {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { ValTreeCreationError::NodesOverflow }
1usize => { ValTreeCreationError::InvalidConst }
2usize => {
ValTreeCreationError::NonSupportedType(::rustc_serialize::Decodable::decode(__decoder))
}
3usize => { ValTreeCreationError::CyclicConst }
4usize => {
ValTreeCreationError::ErrorHandled(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `ValTreeCreationError`, expected 0..5, actual {0}",
n));
}
}
}
}
};TyDecodable)]
101pub enum ValTreeCreationError<'tcx> {
102/// The constant is too big to be valtree'd.
103NodesOverflow,
104/// The constant references mutable or external memory, so it cannot be valtree'd.
105InvalidConst,
106/// Values of this type, or this particular value, are not supported as valtrees.
107NonSupportedType(Ty<'tcx>),
108/// Trying to valtree this constant would cause the valtree to have cycles.
109CyclicConst,
110/// The error has already been handled by const evaluation.
111ErrorHandled(ErrorHandled),
112}
113114impl<'tcx> From<ErrorHandled> for ValTreeCreationError<'tcx> {
115fn from(err: ErrorHandled) -> Self {
116 ValTreeCreationError::ErrorHandled(err)
117 }
118}
119120impl<'tcx> From<InterpErrorInfo<'tcx>> for ValTreeCreationError<'tcx> {
121fn from(err: InterpErrorInfo<'tcx>) -> Self {
122// An error occurred outside the const-eval query, as part of constructing the valtree. We
123 // don't currently preserve the details of this error, since `InterpErrorInfo` cannot be put
124 // into a query result and it can only be access of some mutable or external memory.
125let (_kind, backtrace) = err.into_parts();
126backtrace.print_backtrace();
127 ValTreeCreationError::InvalidConst128 }
129}
130131impl<'tcx> ValTreeCreationError<'tcx> {
132pub(crate) fn with_span(self, span: Span) -> Self {
133use ValTreeCreationError::*;
134match self {
135ErrorHandled(handled) => ErrorHandled(handled.with_span(span)),
136 other => other,
137 }
138 }
139}
140141pub type EvalToAllocationRawResult<'tcx> = Result<ConstAlloc<'tcx>, ErrorHandled>;
142pub type EvalStaticInitializerRawResult<'tcx> = Result<ConstAllocation<'tcx>, ErrorHandled>;
143pub type EvalToConstValueResult<'tcx> = Result<ConstValue, ErrorHandled>;
144pub type EvalToValTreeResult<'tcx> = Result<ValTree<'tcx>, ValTreeCreationError<'tcx>>;
145146#[cfg(target_pointer_width = "64")]
147const _: [(); 8] = [(); ::std::mem::size_of::<InterpErrorInfo<'_>>()];rustc_data_structures::static_assert_size!(InterpErrorInfo<'_>, 8);
148149/// Packages the kind of error we got from the const code interpreter
150/// up with a Rust-level backtrace of where the error occurred.
151/// These should always be constructed by calling `.into()` on
152/// an `InterpError`. In `rustc_mir::interpret`, we have `throw_err_*`
153/// macros for this.
154///
155/// Interpreter errors must *not* be silently discarded (that will lead to a panic). Instead,
156/// explicitly call `discard_err` if this is really the right thing to do. Note that if
157/// this happens during const-eval or in Miri, it could lead to a UB error being lost!
158#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InterpErrorInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InterpErrorInfo", &&self.0)
}
}Debug)]
159pub struct InterpErrorInfo<'tcx>(Box<InterpErrorInfoInner<'tcx>>);
160161#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InterpErrorInfoInner<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InterpErrorInfoInner", "kind", &self.kind, "backtrace",
&&self.backtrace)
}
}Debug)]
162struct InterpErrorInfoInner<'tcx> {
163 kind: InterpErrorKind<'tcx>,
164 backtrace: InterpErrorBacktrace,
165}
166167#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InterpErrorBacktrace {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InterpErrorBacktrace", "backtrace", &&self.backtrace)
}
}Debug)]
168pub struct InterpErrorBacktrace {
169 backtrace: Option<Box<Backtrace>>,
170}
171172impl InterpErrorBacktrace {
173pub fn new() -> InterpErrorBacktrace {
174let capture_backtrace = tls::with_opt(|tcx| {
175if let Some(tcx) = tcx {
176*Lock::borrow(&tcx.sess.ctfe_backtrace)
177 } else {
178 CtfeBacktrace::Disabled179 }
180 });
181182let backtrace = match capture_backtrace {
183 CtfeBacktrace::Disabled => None,
184 CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())),
185 CtfeBacktrace::Immediate => {
186// Print it now.
187let backtrace = Backtrace::force_capture();
188print_backtrace(&backtrace);
189None190 }
191 };
192193InterpErrorBacktrace { backtrace }
194 }
195196pub fn print_backtrace(&self) {
197if let Some(backtrace) = self.backtrace.as_ref() {
198print_backtrace(backtrace);
199 }
200 }
201}
202203impl<'tcx> InterpErrorInfo<'tcx> {
204pub fn into_parts(self) -> (InterpErrorKind<'tcx>, InterpErrorBacktrace) {
205let InterpErrorInfo(InterpErrorInfoInner { kind, backtrace }) = self;
206 (kind, backtrace)
207 }
208209pub fn into_kind(self) -> InterpErrorKind<'tcx> {
210self.0.kind
211 }
212213pub fn from_parts(kind: InterpErrorKind<'tcx>, backtrace: InterpErrorBacktrace) -> Self {
214Self(Box::new(InterpErrorInfoInner { kind, backtrace }))
215 }
216217#[inline]
218pub fn kind(&self) -> &InterpErrorKind<'tcx> {
219&self.0.kind
220 }
221}
222223fn print_backtrace(backtrace: &Backtrace) {
224{
::std::io::_eprint(format_args!("\n\nAn error occurred in the MIR interpreter:\n{0}\n",
backtrace));
};eprintln!("\n\nAn error occurred in the MIR interpreter:\n{backtrace}");
225}
226227impl From<ErrorHandled> for InterpErrorInfo<'_> {
228fn from(err: ErrorHandled) -> Self {
229 InterpErrorKind::InvalidProgram(match err {
230 ErrorHandled::Reported(r, _span) => InvalidProgramInfo::AlreadyReported(r),
231 ErrorHandled::TooGeneric(_span) => InvalidProgramInfo::TooGeneric,
232 })
233 .into()
234 }
235}
236237impl<'tcx> From<InterpErrorKind<'tcx>> for InterpErrorInfo<'tcx> {
238fn from(kind: InterpErrorKind<'tcx>) -> Self {
239InterpErrorInfo(Box::new(InterpErrorInfoInner {
240kind,
241 backtrace: InterpErrorBacktrace::new(),
242 }))
243 }
244}
245246/// Details of why a pointer had to be in-bounds.
247#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CheckInAllocMsg {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CheckInAllocMsg::MemoryAccess => "MemoryAccess",
CheckInAllocMsg::InboundsPointerArithmetic =>
"InboundsPointerArithmetic",
CheckInAllocMsg::Dereferenceable => "Dereferenceable",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for CheckInAllocMsg { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CheckInAllocMsg {
#[inline]
fn clone(&self) -> CheckInAllocMsg { *self }
}Clone)]
248pub enum CheckInAllocMsg {
249/// We are accessing memory.
250MemoryAccess,
251/// We are doing pointer arithmetic.
252InboundsPointerArithmetic,
253/// None of the above -- generic/unspecific inbounds test.
254Dereferenceable,
255}
256257impl fmt::Displayfor CheckInAllocMsg {
258fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259use CheckInAllocMsg::*;
260match self {
261MemoryAccess => f.write_fmt(format_args!("memory access failed"))write!(f, "memory access failed"),
262InboundsPointerArithmetic => f.write_fmt(format_args!("in-bounds pointer arithmetic failed"))write!(f, "in-bounds pointer arithmetic failed"),
263Dereferenceable => f.write_fmt(format_args!("pointer not dereferenceable"))write!(f, "pointer not dereferenceable"),
264 }
265 }
266}
267268/// Details of which pointer is not aligned.
269#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CheckAlignMsg {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CheckAlignMsg::AccessedPtr => "AccessedPtr",
CheckAlignMsg::BasedOn => "BasedOn",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for CheckAlignMsg { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CheckAlignMsg {
#[inline]
fn clone(&self) -> CheckAlignMsg { *self }
}Clone)]
270pub enum CheckAlignMsg {
271/// The accessed pointer did not have proper alignment.
272AccessedPtr,
273/// The access occurred with a place that was based on a misaligned pointer.
274BasedOn,
275}
276277#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InvalidMetaKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
InvalidMetaKind::SliceTooBig => "SliceTooBig",
InvalidMetaKind::TooBig => "TooBig",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for InvalidMetaKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InvalidMetaKind {
#[inline]
fn clone(&self) -> InvalidMetaKind { *self }
}Clone)]
278pub enum InvalidMetaKind {
279/// Size of a `[T]` is too big
280SliceTooBig,
281/// Size of a DST is too big
282TooBig,
283}
284285impl IntoDiagArgfor InvalidMetaKind {
286fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
287 DiagArgValue::Str(Cow::Borrowed(match self {
288 InvalidMetaKind::SliceTooBig => "slice_too_big",
289 InvalidMetaKind::TooBig => "too_big",
290 }))
291 }
292}
293294/// Details of an access to uninitialized bytes / bad pointer bytes where it is not allowed.
295#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BadBytesAccess {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"BadBytesAccess", "access", &self.access, "bad", &&self.bad)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for BadBytesAccess {
#[inline]
fn clone(&self) -> BadBytesAccess {
let _: ::core::clone::AssertParamIsClone<AllocRange>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BadBytesAccess { }Copy)]
296pub struct BadBytesAccess {
297/// Range of the original memory access.
298pub access: AllocRange,
299/// Range of the bad memory that was encountered. (Might not be maximal.)
300pub bad: AllocRange,
301}
302303/// Information about a size mismatch.
304#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ScalarSizeMismatch {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ScalarSizeMismatch", "target_size", &self.target_size,
"data_size", &&self.data_size)
}
}Debug)]
305pub struct ScalarSizeMismatch {
306pub target_size: u64,
307pub data_size: u64,
308}
309310/// Information about a misaligned pointer.
311#[derive(#[automatically_derived]
impl ::core::marker::Copy for Misalignment { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Misalignment {
#[inline]
fn clone(&self) -> Misalignment {
let _: ::core::clone::AssertParamIsClone<Align>;
*self
}
}Clone, #[automatically_derived]
impl ::core::hash::Hash for Misalignment {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.has, state);
::core::hash::Hash::hash(&self.required, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialEq for Misalignment {
#[inline]
fn eq(&self, other: &Misalignment) -> bool {
self.has == other.has && self.required == other.required
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Misalignment {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Align>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for Misalignment {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Misalignment",
"has", &self.has, "required", &&self.required)
}
}Debug)]
312pub struct Misalignment {
313pub has: Align,
314pub required: Align,
315}
316317/// Error information for when the program caused Undefined Behavior.
318#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UndefinedBehaviorInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
UndefinedBehaviorInfo::Ub(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ub",
&__self_0),
UndefinedBehaviorInfo::ValidationError {
orig_ty: __self_0,
path: __self_1,
msg: __self_2,
ptr_bytes_warning: __self_3 } =>
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ValidationError", "orig_ty", __self_0, "path", __self_1,
"msg", __self_2, "ptr_bytes_warning", &__self_3),
UndefinedBehaviorInfo::Unreachable =>
::core::fmt::Formatter::write_str(f, "Unreachable"),
UndefinedBehaviorInfo::BoundsCheckFailed {
len: __self_0, index: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"BoundsCheckFailed", "len", __self_0, "index", &__self_1),
UndefinedBehaviorInfo::DivisionByZero =>
::core::fmt::Formatter::write_str(f, "DivisionByZero"),
UndefinedBehaviorInfo::RemainderByZero =>
::core::fmt::Formatter::write_str(f, "RemainderByZero"),
UndefinedBehaviorInfo::DivisionOverflow =>
::core::fmt::Formatter::write_str(f, "DivisionOverflow"),
UndefinedBehaviorInfo::RemainderOverflow =>
::core::fmt::Formatter::write_str(f, "RemainderOverflow"),
UndefinedBehaviorInfo::PointerArithOverflow =>
::core::fmt::Formatter::write_str(f, "PointerArithOverflow"),
UndefinedBehaviorInfo::ArithOverflow { intrinsic: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ArithOverflow", "intrinsic", &__self_0),
UndefinedBehaviorInfo::ShiftOverflow {
intrinsic: __self_0, shift_amount: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ShiftOverflow", "intrinsic", __self_0, "shift_amount",
&__self_1),
UndefinedBehaviorInfo::InvalidMeta(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidMeta", &__self_0),
UndefinedBehaviorInfo::UnterminatedCString(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"UnterminatedCString", &__self_0),
UndefinedBehaviorInfo::PointerUseAfterFree(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"PointerUseAfterFree", __self_0, &__self_1),
UndefinedBehaviorInfo::PointerOutOfBounds {
alloc_id: __self_0,
alloc_size: __self_1,
ptr_offset: __self_2,
inbounds_size: __self_3,
msg: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"PointerOutOfBounds", "alloc_id", __self_0, "alloc_size",
__self_1, "ptr_offset", __self_2, "inbounds_size", __self_3,
"msg", &__self_4),
UndefinedBehaviorInfo::DanglingIntPointer {
addr: __self_0, inbounds_size: __self_1, msg: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"DanglingIntPointer", "addr", __self_0, "inbounds_size",
__self_1, "msg", &__self_2),
UndefinedBehaviorInfo::AlignmentCheckFailed(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"AlignmentCheckFailed", __self_0, &__self_1),
UndefinedBehaviorInfo::WriteToReadOnly(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"WriteToReadOnly", &__self_0),
UndefinedBehaviorInfo::DerefFunctionPointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DerefFunctionPointer", &__self_0),
UndefinedBehaviorInfo::DerefVTablePointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DerefVTablePointer", &__self_0),
UndefinedBehaviorInfo::DerefVaListPointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DerefVaListPointer", &__self_0),
UndefinedBehaviorInfo::DerefTypeIdPointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DerefTypeIdPointer", &__self_0),
UndefinedBehaviorInfo::InvalidBool(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidBool", &__self_0),
UndefinedBehaviorInfo::InvalidChar(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidChar", &__self_0),
UndefinedBehaviorInfo::InvalidTag(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidTag", &__self_0),
UndefinedBehaviorInfo::InvalidFunctionPointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidFunctionPointer", &__self_0),
UndefinedBehaviorInfo::InvalidVaListPointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidVaListPointer", &__self_0),
UndefinedBehaviorInfo::InvalidVTablePointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidVTablePointer", &__self_0),
UndefinedBehaviorInfo::InvalidVTableTrait {
vtable_dyn_type: __self_0, expected_dyn_type: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InvalidVTableTrait", "vtable_dyn_type", __self_0,
"expected_dyn_type", &__self_1),
UndefinedBehaviorInfo::InvalidStr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidStr", &__self_0),
UndefinedBehaviorInfo::InvalidUninitBytes(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidUninitBytes", &__self_0),
UndefinedBehaviorInfo::DeadLocal =>
::core::fmt::Formatter::write_str(f, "DeadLocal"),
UndefinedBehaviorInfo::ScalarSizeMismatch(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ScalarSizeMismatch", &__self_0),
UndefinedBehaviorInfo::UninhabitedEnumVariantWritten(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"UninhabitedEnumVariantWritten", &__self_0),
UndefinedBehaviorInfo::UninhabitedEnumVariantRead(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"UninhabitedEnumVariantRead", &__self_0),
UndefinedBehaviorInfo::InvalidNichedEnumVariantWritten {
enum_ty: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InvalidNichedEnumVariantWritten", "enum_ty", &__self_0),
UndefinedBehaviorInfo::AbiMismatchArgument {
arg_idx: __self_0, caller_ty: __self_1, callee_ty: __self_2 }
=>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"AbiMismatchArgument", "arg_idx", __self_0, "caller_ty",
__self_1, "callee_ty", &__self_2),
UndefinedBehaviorInfo::AbiMismatchReturn {
caller_ty: __self_0, callee_ty: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"AbiMismatchReturn", "caller_ty", __self_0, "callee_ty",
&__self_1),
UndefinedBehaviorInfo::VaArgOutOfBounds =>
::core::fmt::Formatter::write_str(f, "VaArgOutOfBounds"),
UndefinedBehaviorInfo::CVariadicMismatch {
caller_is_c_variadic: __self_0, callee_is_c_variadic: __self_1
} =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"CVariadicMismatch", "caller_is_c_variadic", __self_0,
"callee_is_c_variadic", &__self_1),
UndefinedBehaviorInfo::CVariadicFixedCountMismatch {
caller: __self_0, callee: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"CVariadicFixedCountMismatch", "caller", __self_0, "callee",
&__self_1),
}
}
}Debug)]
319pub enum UndefinedBehaviorInfo<'tcx> {
320/// Free-form case. Only for errors that are never caught! Used by miri
321Ub(String),
322/// Validation error.
323ValidationError {
324 orig_ty: Ty<'tcx>,
325 path: Option<String>,
326 msg: String,
327 ptr_bytes_warning: bool,
328 },
329330/// Unreachable code was executed.
331Unreachable,
332/// A slice/array index projection went out-of-bounds.
333BoundsCheckFailed { len: u64, index: u64 },
334/// Something was divided by 0 (x / 0).
335DivisionByZero,
336/// Something was "remainded" by 0 (x % 0).
337RemainderByZero,
338/// Signed division overflowed (INT_MIN / -1).
339DivisionOverflow,
340/// Signed remainder overflowed (INT_MIN % -1).
341RemainderOverflow,
342/// Overflowing inbounds pointer arithmetic.
343PointerArithOverflow,
344/// Overflow in arithmetic that may not overflow.
345ArithOverflow { intrinsic: Symbol },
346/// Shift by too much.
347ShiftOverflow { intrinsic: Symbol, shift_amount: Either<u128, i128> },
348/// Invalid metadata in a wide pointer
349InvalidMeta(InvalidMetaKind),
350/// Reading a C string that does not end within its allocation.
351UnterminatedCString(Pointer<AllocId>),
352/// Using a pointer after it got freed.
353PointerUseAfterFree(AllocId, CheckInAllocMsg),
354/// Used a pointer outside the bounds it is valid for.
355PointerOutOfBounds {
356 alloc_id: AllocId,
357 alloc_size: Size,
358 ptr_offset: i64,
359/// The size of the memory range that was expected to be in-bounds.
360inbounds_size: i64,
361 msg: CheckInAllocMsg,
362 },
363/// Using an integer as a pointer in the wrong way.
364DanglingIntPointer {
365 addr: u64,
366/// The size of the memory range that was expected to be in-bounds (or 0 if we need an
367 /// allocation but not any actual memory there, e.g. for function pointers).
368inbounds_size: i64,
369 msg: CheckInAllocMsg,
370 },
371/// Used a pointer with bad alignment.
372AlignmentCheckFailed(Misalignment, CheckAlignMsg),
373/// Writing to read-only memory.
374WriteToReadOnly(AllocId),
375/// Trying to access the data behind a function pointer.
376DerefFunctionPointer(AllocId),
377/// Trying to access the data behind a vtable pointer.
378DerefVTablePointer(AllocId),
379/// Trying to access the data behind a va_list pointer.
380DerefVaListPointer(AllocId),
381/// Trying to access the actual type id.
382DerefTypeIdPointer(AllocId),
383/// Using a non-boolean `u8` as bool.
384InvalidBool(u8),
385/// Using a non-character `u32` as character.
386InvalidChar(u32),
387/// The tag of an enum does not encode an actual discriminant.
388InvalidTag(Scalar<AllocId>),
389/// Using a pointer-not-to-a-function as function pointer.
390InvalidFunctionPointer(Pointer<AllocId>),
391/// Using a pointer-not-to-a-va-list as variable argument list pointer.
392InvalidVaListPointer(Pointer<AllocId>),
393/// Using a pointer-not-to-a-vtable as vtable pointer.
394InvalidVTablePointer(Pointer<AllocId>),
395/// Using a vtable for the wrong trait.
396InvalidVTableTrait {
397/// The vtable that was actually referenced by the wide pointer metadata.
398vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
399/// The vtable that was expected at the point in MIR that it was accessed.
400expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
401 },
402/// Using a string that is not valid UTF-8,
403InvalidStr(std::str::Utf8Error),
404/// Using uninitialized data where it is not allowed.
405InvalidUninitBytes(Option<(AllocId, BadBytesAccess)>),
406/// Working with a local that is not currently live.
407DeadLocal,
408/// Data size is not equal to target size.
409ScalarSizeMismatch(ScalarSizeMismatch),
410/// A discriminant of an uninhabited enum variant is written.
411UninhabitedEnumVariantWritten(VariantIdx),
412/// An uninhabited enum variant is projected.
413UninhabitedEnumVariantRead(Option<VariantIdx>),
414/// Trying to set discriminant to the niched variant, but the value does not match.
415InvalidNichedEnumVariantWritten { enum_ty: Ty<'tcx> },
416/// ABI-incompatible argument types.
417AbiMismatchArgument {
418/// The index of the argument whose type is wrong.
419arg_idx: usize,
420 caller_ty: Ty<'tcx>,
421 callee_ty: Ty<'tcx>,
422 },
423/// ABI-incompatible return types.
424AbiMismatchReturn { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> },
425/// `va_arg` was called on an exhausted `VaList`.
426VaArgOutOfBounds,
427/// The caller and callee disagree on whether they are c-variadic or not.
428CVariadicMismatch { caller_is_c_variadic: bool, callee_is_c_variadic: bool },
429/// The caller and callee disagree on the number of fixed (i.e. non-c-variadic) arguments.
430CVariadicFixedCountMismatch { caller: u32, callee: u32 },
431}
432433impl<'tcx> fmt::Displayfor UndefinedBehaviorInfo<'tcx> {
434fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435use UndefinedBehaviorInfo::*;
436437fn fmt_in_alloc_attempt(
438 f: &mut fmt::Formatter<'_>,
439 msg: CheckInAllocMsg,
440 inbounds_size: i64,
441 ) -> fmt::Result {
442let inbounds_size_fmt = if inbounds_size == 1 {
443format_args!("1 byte")format_args!("1 byte")444 } else {
445format_args!("{0} bytes", inbounds_size)format_args!("{inbounds_size} bytes")446 };
447f.write_fmt(format_args!("{0}: ", msg))write!(f, "{msg}: ")?;
448match msg {
449 CheckInAllocMsg::MemoryAccess => {
450f.write_fmt(format_args!("attempting to access {0}", inbounds_size_fmt))write!(f, "attempting to access {inbounds_size_fmt}")451 }
452 CheckInAllocMsg::InboundsPointerArithmetic => {
453f.write_fmt(format_args!("attempting to offset pointer by {0}",
inbounds_size_fmt))write!(f, "attempting to offset pointer by {inbounds_size_fmt}")454 }
455 CheckInAllocMsg::Dereferenceableif inbounds_size == 0 => {
456f.write_fmt(format_args!("pointer must point to some allocation"))write!(f, "pointer must point to some allocation")457 }
458 CheckInAllocMsg::Dereferenceable => {
459f.write_fmt(format_args!("pointer must be dereferenceable for {0}",
inbounds_size_fmt))write!(f, "pointer must be dereferenceable for {inbounds_size_fmt}")460 }
461 }
462 }
463464match self {
465Ub(msg) => f.write_fmt(format_args!("{0}", msg))write!(f, "{msg}"),
466467ValidationError { orig_ty, path: None, msg, .. } => {
468f.write_fmt(format_args!("constructing invalid value of type {0}: {1}",
orig_ty, msg))write!(f, "constructing invalid value of type {orig_ty}: {msg}")469 }
470ValidationError { orig_ty, path: Some(path), msg, .. } => {
471f.write_fmt(format_args!("constructing invalid value of type {0}: at {1}, {2}",
orig_ty, path, msg))write!(f, "constructing invalid value of type {orig_ty}: at {path}, {msg}")472 }
473474Unreachable => f.write_fmt(format_args!("entering unreachable code"))write!(f, "entering unreachable code"),
475BoundsCheckFailed { len, index } => {
476f.write_fmt(format_args!("indexing out of bounds: the len is {0} but the index is {1}",
len, index))write!(f, "indexing out of bounds: the len is {len} but the index is {index}")477 }
478DivisionByZero => f.write_fmt(format_args!("dividing by zero"))write!(f, "dividing by zero"),
479RemainderByZero => f.write_fmt(format_args!("calculating the remainder with a divisor of zero"))write!(f, "calculating the remainder with a divisor of zero"),
480DivisionOverflow => f.write_fmt(format_args!("overflow in signed division (dividing MIN by -1)"))write!(f, "overflow in signed division (dividing MIN by -1)"),
481RemainderOverflow => f.write_fmt(format_args!("overflow in signed remainder (dividing MIN by -1)"))write!(f, "overflow in signed remainder (dividing MIN by -1)"),
482PointerArithOverflow => f.write_fmt(format_args!("overflowing pointer arithmetic: the total offset in bytes does not fit in an `isize`"))write!(
483f,
484"overflowing pointer arithmetic: the total offset in bytes does not fit in an `isize`"
485),
486ArithOverflow { intrinsic } => f.write_fmt(format_args!("arithmetic overflow in `{0}`", intrinsic))write!(f, "arithmetic overflow in `{intrinsic}`"),
487ShiftOverflow { shift_amount, intrinsic } => {
488f.write_fmt(format_args!("overflowing shift by {0} in `{1}`", shift_amount,
intrinsic))write!(f, "overflowing shift by {shift_amount} in `{intrinsic}`")489 }
490InvalidMeta(InvalidMetaKind::SliceTooBig) => f.write_fmt(format_args!("invalid metadata in wide pointer: slice is bigger than largest supported object"))write!(
491f,
492"invalid metadata in wide pointer: slice is bigger than largest supported object"
493),
494InvalidMeta(InvalidMetaKind::TooBig) => f.write_fmt(format_args!("invalid metadata in wide pointer: total size is bigger than largest supported object"))write!(
495f,
496"invalid metadata in wide pointer: total size is bigger than largest supported object"
497),
498UnterminatedCString(ptr) => f.write_fmt(format_args!("reading a null-terminated string starting at {0} with no null found before end of allocation",
ptr))write!(
499f,
500"reading a null-terminated string starting at {ptr} with no null found before end of allocation"
501),
502PointerUseAfterFree(alloc_id, msg) => {
503f.write_fmt(format_args!("{0}: {1} has been freed, so this pointer is dangling",
msg, alloc_id))write!(f, "{msg}: {alloc_id} has been freed, so this pointer is dangling")504 }
505&PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, inbounds_size, msg } => {
506 fmt_in_alloc_attempt(f, msg, inbounds_size)?;
507f.write_fmt(format_args!(", but got "))write!(f, ", but got ")?;
508// Write pointer. Offset might be negative so we cannot use the normal `impl Display
509 // for Pointer`.
510f.write_fmt(format_args!("{0}", alloc_id))write!(f, "{}", alloc_id)?;
511if ptr_offset > 0 {
512f.write_fmt(format_args!("+{0:#x}", ptr_offset))write!(f, "+{:#x}", ptr_offset)?;
513 } else if ptr_offset < 0 {
514f.write_fmt(format_args!("-{0:#x}", ptr_offset.unsigned_abs()))write!(f, "-{:#x}", ptr_offset.unsigned_abs())?;
515 }
516// Write why it is invalid.
517f.write_fmt(format_args!(" which "))write!(f, " which ")?;
518if ptr_offset < 0 {
519f.write_fmt(format_args!("points to before the beginning of the allocation"))write!(f, "points to before the beginning of the allocation")520 } else if inbounds_size < 0 {
521// We expected the ptr to have memory to its left, but it does not.
522if ptr_offset == 0 {
523f.write_fmt(format_args!("is at the beginning of the allocation"))write!(f, "is at the beginning of the allocation")524 } else {
525f.write_fmt(format_args!("is only {0} bytes from the beginning of the allocation",
ptr_offset))write!(f, "is only {ptr_offset} bytes from the beginning of the allocation")526 }
527 } else {
528let ptr_offset = ptr_offsetas u64;
529let alloc_size = alloc_size.bytes();
530if ptr_offset >= alloc_size {
531let size = if alloc_size == 1 {
532format_args!("1 byte")format_args!("1 byte")533 } else {
534format_args!("{0} bytes", alloc_size)format_args!("{alloc_size} bytes")535 };
536f.write_fmt(format_args!("is at or beyond the end of the allocation of size {0}",
size))write!(f, "is at or beyond the end of the allocation of size {size}",)537 } else {
538let dist_to_end = alloc_size - ptr_offset;
539let dist = if dist_to_end == 1 {
540format_args!("1 byte")format_args!("1 byte")541 } else {
542format_args!("{0} bytes", dist_to_end)format_args!("{dist_to_end} bytes")543 };
544f.write_fmt(format_args!("is only {0} from the end of the allocation", dist))write!(f, "is only {dist} from the end of the allocation",)545 }
546 }
547 }
548&DanglingIntPointer { addr: 0, inbounds_size, msg } => {
549 fmt_in_alloc_attempt(f, msg, inbounds_size)?;
550f.write_fmt(format_args!(", but got null pointer"))write!(f, ", but got null pointer")551 }
552&DanglingIntPointer { addr, inbounds_size, msg } => {
553 fmt_in_alloc_attempt(f, msg, inbounds_size)?;
554f.write_fmt(format_args!(", but got {0} which is a dangling pointer (it has no provenance)",
Pointer::<Option<CtfeProvenance>>::without_provenance(addr)))write!(
555f,
556", but got {ptr} which is a dangling pointer (it has no provenance)",
557 ptr = Pointer::<Option<CtfeProvenance>>::without_provenance(addr),
558 )559 }
560AlignmentCheckFailed(misalign, msg) => {
561f.write_fmt(format_args!("{0} with alignment {1}, but alignment {2} is required",
match msg {
CheckAlignMsg::AccessedPtr => "accessing memory",
CheckAlignMsg::BasedOn => "accessing memory based on pointer",
}, misalign.has.bytes(), misalign.required.bytes()))write!(
562f,
563"{acc} with alignment {has}, but alignment {required} is required",
564 acc = match msg {
565 CheckAlignMsg::AccessedPtr => "accessing memory",
566 CheckAlignMsg::BasedOn => "accessing memory based on pointer",
567 },
568 has = misalign.has.bytes(),
569 required = misalign.required.bytes(),
570 )571 }
572WriteToReadOnly(alloc) => f.write_fmt(format_args!("writing to {0} which is read-only", alloc))write!(f, "writing to {alloc} which is read-only"),
573DerefFunctionPointer(alloc) => {
574f.write_fmt(format_args!("accessing {0} which contains a function", alloc))write!(f, "accessing {alloc} which contains a function")575 }
576DerefVTablePointer(alloc) => f.write_fmt(format_args!("accessing {0} which contains a vtable", alloc))write!(f, "accessing {alloc} which contains a vtable"),
577DerefVaListPointer(alloc) => {
578f.write_fmt(format_args!("accessing {0} which contains a variable argument list",
alloc))write!(f, "accessing {alloc} which contains a variable argument list")579 }
580DerefTypeIdPointer(alloc) => f.write_fmt(format_args!("accessing {0} which contains a `TypeId`", alloc))write!(f, "accessing {alloc} which contains a `TypeId`"),
581InvalidBool(value) => {
582f.write_fmt(format_args!("interpreting an invalid 8-bit value as a bool: 0x{0:02x}",
value))write!(f, "interpreting an invalid 8-bit value as a bool: 0x{value:02x}")583 }
584InvalidChar(value) => {
585f.write_fmt(format_args!("interpreting an invalid 32-bit value as a char: 0x{0:08x}",
value))write!(f, "interpreting an invalid 32-bit value as a char: 0x{value:08x}")586 }
587InvalidTag(tag) => f.write_fmt(format_args!("enum value has invalid tag: {0:x}", tag))write!(f, "enum value has invalid tag: {tag:x}"),
588InvalidFunctionPointer(ptr) => {
589f.write_fmt(format_args!("using {0} as function pointer but it does not point to a function",
ptr))write!(f, "using {ptr} as function pointer but it does not point to a function")590 }
591InvalidVaListPointer(ptr) => f.write_fmt(format_args!("using {0} as variable argument list pointer but it does not point to a variable argument list",
ptr))write!(
592f,
593"using {ptr} as variable argument list pointer but it does not point to a variable argument list"
594),
595InvalidVTablePointer(ptr) => {
596f.write_fmt(format_args!("using {0} as vtable pointer but it does not point to a vtable",
ptr))write!(f, "using {ptr} as vtable pointer but it does not point to a vtable")597 }
598InvalidVTableTrait { vtable_dyn_type, expected_dyn_type } => f.write_fmt(format_args!("using vtable for `{0}` but `{1}` was expected",
vtable_dyn_type, expected_dyn_type))write!(
599f,
600"using vtable for `{vtable_dyn_type}` but `{expected_dyn_type}` was expected"
601),
602InvalidStr(err) => f.write_fmt(format_args!("this string is not valid UTF-8: {0}", err))write!(f, "this string is not valid UTF-8: {err}"),
603InvalidUninitBytes(None) => {
604f.write_fmt(format_args!("using uninitialized data, but this operation requires initialized memory"))write!(
605f,
606"using uninitialized data, but this operation requires initialized memory"
607)608 }
609InvalidUninitBytes(Some((alloc, info))) => f.write_fmt(format_args!("reading memory at {2}{0}, but memory is uninitialized at {1}, and this operation requires initialized memory",
info.access, info.bad, alloc))write!(
610f,
611"reading memory at {alloc}{access}, but memory is uninitialized at {uninit}, and this operation requires initialized memory",
612 access = info.access,
613 uninit = info.bad,
614 ),
615DeadLocal => f.write_fmt(format_args!("accessing a dead local variable"))write!(f, "accessing a dead local variable"),
616ScalarSizeMismatch(mismatch) => f.write_fmt(format_args!("scalar size mismatch: expected {0} bytes but got {1} bytes instead",
mismatch.target_size, mismatch.data_size))write!(
617f,
618"scalar size mismatch: expected {target_size} bytes but got {data_size} bytes instead",
619 target_size = mismatch.target_size,
620 data_size = mismatch.data_size,
621 ),
622UninhabitedEnumVariantWritten(_) => {
623f.write_fmt(format_args!("writing discriminant of an uninhabited enum variant"))write!(f, "writing discriminant of an uninhabited enum variant")624 }
625UninhabitedEnumVariantRead(_) => {
626f.write_fmt(format_args!("read discriminant of an uninhabited enum variant"))write!(f, "read discriminant of an uninhabited enum variant")627 }
628InvalidNichedEnumVariantWritten { enum_ty } => {
629f.write_fmt(format_args!("trying to set discriminant of a {0} to the niched variant, but the value does not match",
enum_ty))write!(
630f,
631"trying to set discriminant of a {enum_ty} to the niched variant, but the value does not match"
632)633 }
634AbiMismatchArgument { arg_idx, caller_ty, callee_ty } => f.write_fmt(format_args!("calling a function whose parameter #{0} has type {1} passing argument of type {2}",
arg_idx + 1, callee_ty, caller_ty))write!(
635f,
636"calling a function whose parameter #{arg_idx} has type {callee_ty} passing argument of type {caller_ty}",
637 arg_idx = arg_idx + 1, // adjust for 1-indexed lists in output
638),
639AbiMismatchReturn { caller_ty, callee_ty } => f.write_fmt(format_args!("calling a function with return type {0} passing return place of type {1}",
callee_ty, caller_ty))write!(
640f,
641"calling a function with return type {callee_ty} passing return place of type {caller_ty}"
642),
643VaArgOutOfBounds => f.write_fmt(format_args!("more C-variadic arguments read than were passed"))write!(f, "more C-variadic arguments read than were passed"),
644CVariadicMismatch { .. } => f.write_fmt(format_args!("calling a function where the caller and callee disagree on whether the function is C-variadic"))write!(
645f,
646"calling a function where the caller and callee disagree on whether the function is C-variadic"
647),
648CVariadicFixedCountMismatch { caller, callee } => f.write_fmt(format_args!("calling a C-variadic function with {0} fixed arguments, but the function expects {1}",
caller, callee))write!(
649f,
650"calling a C-variadic function with {caller} fixed arguments, but the function expects {callee}"
651),
652 }
653 }
654}
655656/// Error information for when the program we executed turned out not to actually be a valid
657/// program. This cannot happen in stand-alone Miri (except for layout errors that are only detect
658/// during monomorphization), but it can happen during CTFE/ConstProp where we work on generic code
659/// or execution does not have all information available.
660#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InvalidProgramInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
InvalidProgramInfo::TooGeneric =>
::core::fmt::Formatter::write_str(f, "TooGeneric"),
InvalidProgramInfo::AlreadyReported(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AlreadyReported", &__self_0),
InvalidProgramInfo::Layout(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Layout",
&__self_0),
}
}
}Debug)]
661pub enum InvalidProgramInfo<'tcx> {
662/// Resolution can fail if we are in a too generic context.
663TooGeneric,
664/// Abort in case errors are already reported.
665AlreadyReported(ReportedErrorInfo),
666/// An error occurred during layout computation.
667Layout(layout::LayoutError<'tcx>),
668}
669670impl<'tcx> fmt::Displayfor InvalidProgramInfo<'tcx> {
671fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672use InvalidProgramInfo::*;
673match self {
674TooGeneric => f.write_fmt(format_args!("encountered overly generic constant"))write!(f, "encountered overly generic constant"),
675AlreadyReported(_) => {
676f.write_fmt(format_args!("an error has already been reported elsewhere (this should not usually be printed)"))write!(
677f,
678"an error has already been reported elsewhere (this should not usually be printed)"
679)680 }
681Layout(e) => f.write_fmt(format_args!("{0}", e))write!(f, "{e}"),
682 }
683 }
684}
685686/// Error information for when the program did something that might (or might not) be correct
687/// to do according to the Rust spec, but due to limitations in the interpreter, the
688/// operation could not be carried out. These limitations can differ between CTFE and the
689/// Miri engine, e.g., CTFE does not support dereferencing pointers at integral addresses.
690#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UnsupportedOpInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
UnsupportedOpInfo::Unsupported(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Unsupported", &__self_0),
UnsupportedOpInfo::UnsizedLocal =>
::core::fmt::Formatter::write_str(f, "UnsizedLocal"),
UnsupportedOpInfo::ExternTypeField =>
::core::fmt::Formatter::write_str(f, "ExternTypeField"),
UnsupportedOpInfo::ReadPartialPointer(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ReadPartialPointer", &__self_0),
UnsupportedOpInfo::ReadPointerAsInt(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ReadPointerAsInt", &__self_0),
UnsupportedOpInfo::ThreadLocalStatic(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ThreadLocalStatic", &__self_0),
UnsupportedOpInfo::ExternStatic(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ExternStatic", &__self_0),
}
}
}Debug)]
691pub enum UnsupportedOpInfo {
692/// Free-form case. Only for errors that are never caught! Used by Miri.
693// FIXME still use translatable diagnostics
694Unsupported(String),
695/// Unsized local variables.
696UnsizedLocal,
697/// Extern type field with an indeterminate offset.
698ExternTypeField,
699//
700 // The variants below are only reachable from CTFE/const prop, miri will never emit them.
701 //
702/// Attempting to read or copy parts of a pointer to somewhere else; without knowing absolute
703 /// addresses, the resulting state cannot be represented by the CTFE interpreter.
704ReadPartialPointer(Pointer<AllocId>),
705/// Encountered a pointer where we needed an integer.
706ReadPointerAsInt(Option<(AllocId, BadBytesAccess)>),
707/// Accessing thread local statics
708ThreadLocalStatic(DefId),
709/// Accessing an unsupported extern static.
710ExternStatic(DefId),
711}
712713impl fmt::Displayfor UnsupportedOpInfo {
714fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715use UnsupportedOpInfo::*;
716match self {
717Unsupported(s) => f.write_fmt(format_args!("{0}", s))write!(f, "{s}"),
718ExternTypeField => {
719f.write_fmt(format_args!("`extern type` field does not have a known offset"))write!(f, "`extern type` field does not have a known offset")720 }
721UnsizedLocal => f.write_fmt(format_args!("unsized locals are not supported"))write!(f, "unsized locals are not supported"),
722ReadPartialPointer(ptr) => {
723f.write_fmt(format_args!("unable to read parts of a pointer from memory at {0}",
ptr))write!(f, "unable to read parts of a pointer from memory at {ptr}")724 }
725ReadPointerAsInt(_) => f.write_fmt(format_args!("unable to turn pointer into integer"))write!(f, "unable to turn pointer into integer"),
726&ThreadLocalStatic(did) => {
727f.write_fmt(format_args!("cannot access thread local static `{0}`",
ty::tls::with(|tcx| tcx.def_path_str(did))))write!(
728f,
729"cannot access thread local static `{did}`",
730 did = ty::tls::with(|tcx| tcx.def_path_str(did))
731 )732 }
733&ExternStatic(did) => {
734f.write_fmt(format_args!("cannot access extern static `{0}`",
ty::tls::with(|tcx| tcx.def_path_str(did))))write!(
735f,
736"cannot access extern static `{did}`",
737 did = ty::tls::with(|tcx| tcx.def_path_str(did))
738 )739 }
740 }
741 }
742}
743744/// Error information for when the program exhausted the resources granted to it
745/// by the interpreter.
746#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ResourceExhaustionInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ResourceExhaustionInfo::StackFrameLimitReached =>
"StackFrameLimitReached",
ResourceExhaustionInfo::MemoryExhausted => "MemoryExhausted",
ResourceExhaustionInfo::AddressSpaceFull =>
"AddressSpaceFull",
ResourceExhaustionInfo::Interrupted => "Interrupted",
})
}
}Debug)]
747pub enum ResourceExhaustionInfo {
748/// The stack grew too big.
749StackFrameLimitReached,
750/// There is not enough memory (on the host) to perform an allocation.
751MemoryExhausted,
752/// The address space (of the target) is full.
753AddressSpaceFull,
754/// The compiler got an interrupt signal (a user ran out of patience).
755Interrupted,
756}
757758impl fmt::Displayfor ResourceExhaustionInfo {
759fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760use ResourceExhaustionInfo::*;
761match self {
762StackFrameLimitReached => {
763f.write_fmt(format_args!("reached the configured maximum number of stack frames"))write!(f, "reached the configured maximum number of stack frames")764 }
765MemoryExhausted => {
766f.write_fmt(format_args!("tried to allocate more memory than available to compiler"))write!(f, "tried to allocate more memory than available to compiler")767 }
768AddressSpaceFull => {
769f.write_fmt(format_args!("there are no more free addresses in the address space"))write!(f, "there are no more free addresses in the address space")770 }
771Interrupted => f.write_fmt(format_args!("compilation was interrupted"))write!(f, "compilation was interrupted"),
772 }
773 }
774}
775776/// A trait for machine-specific errors (or other "machine stop" conditions).
777pub trait MachineStopType: Any + fmt::Display + fmt::Debug + Send {
778/// This error occurred during validation, inside a value at the given path.
779fn with_validation_path(&mut self, _path: String) {}
780}
781782impl dyn MachineStopType {
783#[inline(always)]
784pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
785let x: &dyn Any = self;
786x.downcast_ref()
787 }
788}
789790#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InterpErrorKind<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
InterpErrorKind::UndefinedBehavior(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"UndefinedBehavior", &__self_0),
InterpErrorKind::InvalidProgram(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidProgram", &__self_0),
InterpErrorKind::Unsupported(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Unsupported", &__self_0),
InterpErrorKind::ResourceExhaustion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ResourceExhaustion", &__self_0),
InterpErrorKind::MachineStop(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MachineStop", &__self_0),
}
}
}Debug)]
791pub enum InterpErrorKind<'tcx> {
792/// The program caused undefined behavior.
793UndefinedBehavior(UndefinedBehaviorInfo<'tcx>),
794/// The program was invalid (ill-typed, bad MIR, not sufficiently monomorphized, ...).
795InvalidProgram(InvalidProgramInfo<'tcx>),
796/// The program did something the interpreter does not support (some of these *might* be UB
797 /// but the interpreter is not sure).
798Unsupported(UnsupportedOpInfo),
799/// The program exhausted the interpreter's resources (stack/heap too big,
800 /// execution takes too long, ...).
801ResourceExhaustion(ResourceExhaustionInfo),
802/// Stop execution for a machine-controlled reason. This is never raised by
803 /// the core engine itself.
804MachineStop(Box<dyn MachineStopType>),
805}
806807impl<'tcx> fmt::Displayfor InterpErrorKind<'tcx> {
808fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809use InterpErrorKind::*;
810match self {
811Unsupported(msg) => f.write_fmt(format_args!("{0}", msg))write!(f, "{msg}"),
812InvalidProgram(msg) => f.write_fmt(format_args!("{0}", msg))write!(f, "{msg}"),
813UndefinedBehavior(msg) => f.write_fmt(format_args!("{0}", msg))write!(f, "{msg}"),
814ResourceExhaustion(msg) => f.write_fmt(format_args!("{0}", msg))write!(f, "{msg}"),
815MachineStop(msg) => f.write_fmt(format_args!("{0}", msg))write!(f, "{msg}"),
816 }
817 }
818}
819820impl InterpErrorKind<'_> {
821/// Some errors do string formatting even if the error is never printed.
822 /// To avoid performance issues, there are places where we want to be sure to never raise these formatting errors,
823 /// so this method lets us detect them and `bug!` on unexpected errors.
824pub fn formatted_string(&self) -> bool {
825#[allow(non_exhaustive_omitted_patterns)] match self {
InterpErrorKind::Unsupported(UnsupportedOpInfo::Unsupported(_)) |
InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::ValidationError {
.. }) |
InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_)) =>
true,
_ => false,
}matches!(
826self,
827 InterpErrorKind::Unsupported(UnsupportedOpInfo::Unsupported(_))
828 | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::ValidationError { .. })
829 | InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_))
830 )831 }
832}
833834// Macros for constructing / throwing `InterpErrorKind`
835#[macro_export]
836macro_rules!err_unsup {
837 ($($tt:tt)*) => {
838$crate::mir::interpret::InterpErrorKind::Unsupported(
839$crate::mir::interpret::UnsupportedOpInfo::$($tt)*
840 )
841 };
842}
843844#[macro_export]
845macro_rules!err_unsup_format {
846 ($($tt:tt)*) => { $crate::err_unsup!(Unsupported(format!($($tt)*))) };
847}
848849#[macro_export]
850macro_rules!err_inval {
851 ($($tt:tt)*) => {
852$crate::mir::interpret::InterpErrorKind::InvalidProgram(
853$crate::mir::interpret::InvalidProgramInfo::$($tt)*
854 )
855 };
856}
857858#[macro_export]
859macro_rules!err_ub {
860 ($($tt:tt)*) => {
861$crate::mir::interpret::InterpErrorKind::UndefinedBehavior(
862$crate::mir::interpret::UndefinedBehaviorInfo::$($tt)*
863 )
864 };
865}
866867#[macro_export]
868macro_rules!err_ub_format {
869 ($($tt:tt)*) => { $crate::err_ub!(Ub(format!($($tt)*))) };
870}
871872#[macro_export]
873macro_rules!err_exhaust {
874 ($($tt:tt)*) => {
875$crate::mir::interpret::InterpErrorKind::ResourceExhaustion(
876$crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
877 )
878 };
879}
880881#[macro_export]
882macro_rules!err_machine_stop {
883 ($($tt:tt)*) => {
884$crate::mir::interpret::InterpErrorKind::MachineStop(Box::new($($tt)*))
885 };
886}
887888// In the `throw_*` macros, avoid `return` to make them work with `try {}`.
889#[macro_export]
890macro_rules!throw_unsup {
891 ($($tt:tt)*) => { do yeet $crate::err_unsup!($($tt)*) };
892}
893894#[macro_export]
895macro_rules!throw_unsup_format {
896 ($($tt:tt)*) => { do yeet $crate::err_unsup_format!($($tt)*) };
897}
898899#[macro_export]
900macro_rules!throw_inval {
901 ($($tt:tt)*) => { do yeet $crate::err_inval!($($tt)*) };
902}
903904#[macro_export]
905macro_rules!throw_ub {
906 ($($tt:tt)*) => { do yeet $crate::err_ub!($($tt)*) };
907}
908909#[macro_export]
910macro_rules!throw_ub_format {
911 ($($tt:tt)*) => { do yeet $crate::err_ub_format!($($tt)*) };
912}
913914#[macro_export]
915macro_rules!throw_exhaust {
916 ($($tt:tt)*) => { do yeet $crate::err_exhaust!($($tt)*) };
917}
918919#[macro_export]
920macro_rules!throw_machine_stop {
921 ($($tt:tt)*) => { do yeet $crate::err_machine_stop!($($tt)*) };
922}
923924/// Guard type that panics on drop.
925#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Guard {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "Guard")
}
}Debug)]
926struct Guard;
927928impl Dropfor Guard {
929fn drop(&mut self) {
930// We silence the guard if we are already panicking, to avoid double-panics.
931if !std::thread::panicking() {
932{
::core::panicking::panic_fmt(format_args!("an interpreter error got improperly discarded; use `discard_err()` if this is intentional"));
};panic!(
933"an interpreter error got improperly discarded; use `discard_err()` if this is intentional"
934);
935 }
936 }
937}
938939/// The result type used by the interpreter. This is a newtype around `Result`
940/// to block access to operations like `ok()` that discard UB errors.
941///
942/// We also make things panic if this type is ever implicitly dropped.
943#[derive(#[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for InterpResult<'tcx, T>
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InterpResult",
"res", &self.res, "guard", &&self.guard)
}
}Debug)]
944#[must_use]
945pub struct InterpResult<'tcx, T = ()> {
946 res: Result<T, InterpErrorInfo<'tcx>>,
947 guard: Guard,
948}
949950impl<'tcx, T> ops::Tryfor InterpResult<'tcx, T> {
951type Output = T;
952type Residual = InterpResult<'tcx, convert::Infallible>;
953954#[inline]
955fn from_output(output: Self::Output) -> Self {
956InterpResult::new(Ok(output))
957 }
958959#[inline]
960fn branch(self) -> ops::ControlFlow<Self::Residual, Self::Output> {
961match self.disarm() {
962Ok(v) => ops::ControlFlow::Continue(v),
963Err(e) => ops::ControlFlow::Break(InterpResult::new(Err(e))),
964 }
965 }
966}
967968impl<'tcx, T> ops::Residual<T> for InterpResult<'tcx, convert::Infallible> {
969type TryType = InterpResult<'tcx, T>;
970}
971972impl<'tcx, T> ops::FromResidualfor InterpResult<'tcx, T> {
973#[inline]
974 #[track_caller]
975fn from_residual(residual: InterpResult<'tcx, convert::Infallible>) -> Self {
976match residual.disarm() {
977Err(e) => Self::new(Err(e)),
978 }
979 }
980}
981982// Allow `yeet`ing `InterpError` in functions returning `InterpResult_`.
983impl<'tcx, T> ops::FromResidual<ops::Yeet<InterpErrorKind<'tcx>>> for InterpResult<'tcx, T> {
984#[inline]
985fn from_residual(ops::Yeet(e): ops::Yeet<InterpErrorKind<'tcx>>) -> Self {
986Self::new(Err(e.into()))
987 }
988}
989990// Allow `?` on `Result<_, InterpError>` in functions returning `InterpResult_`.
991// This is useful e.g. for `option.ok_or_else(|| err_ub!(...))`.
992impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> ops::FromResidual<Result<convert::Infallible, E>>
993for InterpResult<'tcx, T>
994{
995#[inline]
996fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
997match residual {
998Err(e) => Self::new(Err(e.into())),
999 }
1000 }
1001}
10021003impl<'tcx, T, E: Into<InterpErrorInfo<'tcx>>> From<Result<T, E>> for InterpResult<'tcx, T> {
1004#[inline]
1005fn from(value: Result<T, E>) -> Self {
1006Self::new(value.map_err(|e| e.into()))
1007 }
1008}
10091010impl<'tcx, T, V: FromIterator<T>> FromIterator<InterpResult<'tcx, T>> for InterpResult<'tcx, V> {
1011fn from_iter<I: IntoIterator<Item = InterpResult<'tcx, T>>>(iter: I) -> Self {
1012Self::new(iter.into_iter().map(|x| x.disarm()).collect())
1013 }
1014}
10151016impl<'tcx, T> InterpResult<'tcx, T> {
1017#[inline(always)]
1018fn new(res: Result<T, InterpErrorInfo<'tcx>>) -> Self {
1019Self { res, guard: Guard }
1020 }
10211022#[inline(always)]
1023fn disarm(self) -> Result<T, InterpErrorInfo<'tcx>> {
1024 mem::forget(self.guard);
1025self.res
1026 }
10271028/// Discard the error information in this result. Only use this if ignoring Undefined Behavior is okay!
1029#[inline]
1030pub fn discard_err(self) -> Option<T> {
1031self.disarm().ok()
1032 }
10331034/// Look at the `Result` wrapped inside of this.
1035 /// Must only be used to report the error!
1036#[inline]
1037pub fn report_err(self) -> Result<T, InterpErrorInfo<'tcx>> {
1038self.disarm()
1039 }
10401041#[inline]
1042pub fn map<U>(self, f: impl FnOnce(T) -> U) -> InterpResult<'tcx, U> {
1043InterpResult::new(self.disarm().map(f))
1044 }
10451046#[inline]
1047pub fn map_err_info(
1048self,
1049 f: impl FnOnce(InterpErrorInfo<'tcx>) -> InterpErrorInfo<'tcx>,
1050 ) -> InterpResult<'tcx, T> {
1051InterpResult::new(self.disarm().map_err(f))
1052 }
10531054#[inline]
1055pub fn map_err_kind(
1056self,
1057 f: impl FnOnce(InterpErrorKind<'tcx>) -> InterpErrorKind<'tcx>,
1058 ) -> InterpResult<'tcx, T> {
1059InterpResult::new(self.disarm().map_err(|mut e| {
1060e.0.kind = f(e.0.kind);
1061e1062 }))
1063 }
10641065#[inline]
1066pub fn inspect_err_kind(self, f: impl FnOnce(&InterpErrorKind<'tcx>)) -> InterpResult<'tcx, T> {
1067InterpResult::new(self.disarm().inspect_err(|e| f(&e.0.kind)))
1068 }
10691070#[inline]
1071 #[track_caller]
1072pub fn unwrap(self) -> T {
1073self.disarm().unwrap()
1074 }
10751076#[inline]
1077 #[track_caller]
1078pub fn unwrap_or_else(self, f: impl FnOnce(InterpErrorInfo<'tcx>) -> T) -> T {
1079self.disarm().unwrap_or_else(f)
1080 }
10811082#[inline]
1083 #[track_caller]
1084pub fn expect(self, msg: &str) -> T {
1085self.disarm().expect(msg)
1086 }
10871088#[inline]
1089pub fn and_then<U>(self, f: impl FnOnce(T) -> InterpResult<'tcx, U>) -> InterpResult<'tcx, U> {
1090InterpResult::new(self.disarm().and_then(|t| f(t).disarm()))
1091 }
10921093/// Returns success if both `self` and `other` succeed, while ensuring we don't
1094 /// accidentally drop an error.
1095 ///
1096 /// If both are an error, `self` will be reported.
1097#[inline]
1098pub fn and<U>(self, other: InterpResult<'tcx, U>) -> InterpResult<'tcx, (T, U)> {
1099match self.disarm() {
1100Ok(t) => interp_ok((t, other?)),
1101Err(e) => {
1102// Discard the other error.
1103drop(other.disarm());
1104// Return `self`.
1105InterpResult::new(Err(e))
1106 }
1107 }
1108 }
1109}
11101111#[inline(always)]
1112pub fn interp_ok<'tcx, T>(x: T) -> InterpResult<'tcx, T> {
1113InterpResult::new(Ok(x))
1114}