Skip to main content

rustc_const_eval/const_eval/
error.rs

1use std::mem;
2
3use rustc_errors::{Diag, DiagArgName, DiagArgValue, DiagMessage, IntoDiagArg};
4use rustc_middle::mir::AssertKind;
5use rustc_middle::mir::interpret::{AllocId, Provenance, ReportedErrorInfo, UndefinedBehaviorInfo};
6use rustc_middle::query::TyCtxtAt;
7use rustc_middle::ty::ConstInt;
8use rustc_middle::ty::layout::LayoutError;
9use rustc_span::{Span, Symbol};
10
11use super::CompileTimeMachine;
12use crate::errors::{self, FrameNote, ReportErrorExt};
13use crate::interpret::{
14    CtfeProvenance, ErrorHandled, Frame, InterpCx, InterpErrorInfo, InterpErrorKind,
15    MachineStopType, Pointer, err_inval, err_machine_stop,
16};
17
18/// The CTFE machine has some custom error kinds.
19#[derive(#[automatically_derived]
impl ::core::clone::Clone for ConstEvalErrKind {
    #[inline]
    fn clone(&self) -> ConstEvalErrKind {
        match self {
            ConstEvalErrKind::ConstAccessesMutGlobal =>
                ConstEvalErrKind::ConstAccessesMutGlobal,
            ConstEvalErrKind::ModifiedGlobal =>
                ConstEvalErrKind::ModifiedGlobal,
            ConstEvalErrKind::RecursiveStatic =>
                ConstEvalErrKind::RecursiveStatic,
            ConstEvalErrKind::AssertFailure(__self_0) =>
                ConstEvalErrKind::AssertFailure(::core::clone::Clone::clone(__self_0)),
            ConstEvalErrKind::Panic {
                msg: __self_0, line: __self_1, col: __self_2, file: __self_3 }
                =>
                ConstEvalErrKind::Panic {
                    msg: ::core::clone::Clone::clone(__self_0),
                    line: ::core::clone::Clone::clone(__self_1),
                    col: ::core::clone::Clone::clone(__self_2),
                    file: ::core::clone::Clone::clone(__self_3),
                },
            ConstEvalErrKind::WriteThroughImmutablePointer =>
                ConstEvalErrKind::WriteThroughImmutablePointer,
            ConstEvalErrKind::ConstMakeGlobalPtrAlreadyMadeGlobal(__self_0) =>
                ConstEvalErrKind::ConstMakeGlobalPtrAlreadyMadeGlobal(::core::clone::Clone::clone(__self_0)),
            ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(__self_0) =>
                ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(::core::clone::Clone::clone(__self_0)),
            ConstEvalErrKind::ConstMakeGlobalWithDanglingPtr(__self_0) =>
                ConstEvalErrKind::ConstMakeGlobalWithDanglingPtr(::core::clone::Clone::clone(__self_0)),
            ConstEvalErrKind::ConstMakeGlobalWithOffset(__self_0) =>
                ConstEvalErrKind::ConstMakeGlobalWithOffset(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstEvalErrKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ConstEvalErrKind::ConstAccessesMutGlobal =>
                ::core::fmt::Formatter::write_str(f,
                    "ConstAccessesMutGlobal"),
            ConstEvalErrKind::ModifiedGlobal =>
                ::core::fmt::Formatter::write_str(f, "ModifiedGlobal"),
            ConstEvalErrKind::RecursiveStatic =>
                ::core::fmt::Formatter::write_str(f, "RecursiveStatic"),
            ConstEvalErrKind::AssertFailure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AssertFailure", &__self_0),
            ConstEvalErrKind::Panic {
                msg: __self_0, line: __self_1, col: __self_2, file: __self_3 }
                =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f, "Panic",
                    "msg", __self_0, "line", __self_1, "col", __self_2, "file",
                    &__self_3),
            ConstEvalErrKind::WriteThroughImmutablePointer =>
                ::core::fmt::Formatter::write_str(f,
                    "WriteThroughImmutablePointer"),
            ConstEvalErrKind::ConstMakeGlobalPtrAlreadyMadeGlobal(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConstMakeGlobalPtrAlreadyMadeGlobal", &__self_0),
            ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConstMakeGlobalPtrIsNonHeap", &__self_0),
            ConstEvalErrKind::ConstMakeGlobalWithDanglingPtr(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConstMakeGlobalWithDanglingPtr", &__self_0),
            ConstEvalErrKind::ConstMakeGlobalWithOffset(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConstMakeGlobalWithOffset", &__self_0),
        }
    }
}Debug)]
20pub enum ConstEvalErrKind {
21    ConstAccessesMutGlobal,
22    ModifiedGlobal,
23    RecursiveStatic,
24    AssertFailure(AssertKind<ConstInt>),
25    Panic {
26        msg: Symbol,
27        line: u32,
28        col: u32,
29        file: Symbol,
30    },
31    WriteThroughImmutablePointer,
32    /// Called `const_make_global` twice.
33    ConstMakeGlobalPtrAlreadyMadeGlobal(AllocId),
34    /// Called `const_make_global` on a non-heap pointer.
35    ConstMakeGlobalPtrIsNonHeap(Pointer<Option<CtfeProvenance>>),
36    /// Called `const_make_global` on a dangling pointer.
37    ConstMakeGlobalWithDanglingPtr(Pointer<Option<CtfeProvenance>>),
38    /// Called `const_make_global` on a pointer that does not start at the
39    /// beginning of an object.
40    ConstMakeGlobalWithOffset(Pointer<Option<CtfeProvenance>>),
41}
42
43impl MachineStopType for ConstEvalErrKind {
44    fn diagnostic_message(&self) -> DiagMessage {
45        use ConstEvalErrKind::*;
46        use rustc_errors::msg;
47
48        match self {
49            ConstAccessesMutGlobal => "constant accesses mutable global memory".into(),
50            ModifiedGlobal => {
51                "modifying a static's initial value from another static's initializer".into()
52            }
53            Panic { .. } => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("evaluation panicked: {$msg}"))msg!("evaluation panicked: {$msg}"),
54            RecursiveStatic => {
55                "encountered static that tried to access itself during initialization".into()
56            }
57            AssertFailure(x) => x.diagnostic_message(),
58            WriteThroughImmutablePointer => {
59                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("writing through a pointer that was derived from a shared (immutable) reference"))msg!(
60                    "writing through a pointer that was derived from a shared (immutable) reference"
61                )
62            }
63            ConstMakeGlobalPtrAlreadyMadeGlobal { .. } => {
64                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("attempting to call `const_make_global` twice on the same allocation {$alloc}"))msg!("attempting to call `const_make_global` twice on the same allocation {$alloc}")
65            }
66            ConstMakeGlobalPtrIsNonHeap(_) => {
67                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("pointer passed to `const_make_global` does not point to a heap allocation: {$ptr}"))msg!(
68                    "pointer passed to `const_make_global` does not point to a heap allocation: {$ptr}"
69                )
70            }
71            ConstMakeGlobalWithDanglingPtr(_) => {
72                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("pointer passed to `const_make_global` is dangling: {$ptr}"))msg!("pointer passed to `const_make_global` is dangling: {$ptr}")
73            }
74            ConstMakeGlobalWithOffset(_) => {
75                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("making {$ptr} global which does not point to the beginning of an object"))msg!("making {$ptr} global which does not point to the beginning of an object")
76            }
77        }
78    }
79    fn add_args(self: Box<Self>, adder: &mut dyn FnMut(DiagArgName, DiagArgValue)) {
80        use ConstEvalErrKind::*;
81        match *self {
82            RecursiveStatic
83            | ConstAccessesMutGlobal
84            | ModifiedGlobal
85            | WriteThroughImmutablePointer => {}
86            AssertFailure(kind) => kind.add_args(adder),
87            Panic { msg, .. } => {
88                adder("msg".into(), msg.into_diag_arg(&mut None));
89            }
90            ConstMakeGlobalPtrIsNonHeap(ptr)
91            | ConstMakeGlobalWithOffset(ptr)
92            | ConstMakeGlobalWithDanglingPtr(ptr) => {
93                adder("ptr".into(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", ptr))
    })format!("{ptr:?}").into_diag_arg(&mut None));
94            }
95            ConstMakeGlobalPtrAlreadyMadeGlobal(alloc) => {
96                adder("alloc".into(), alloc.into_diag_arg(&mut None));
97            }
98        }
99    }
100}
101
102/// The errors become [`InterpErrorKind::MachineStop`] when being raised.
103impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalErrKind {
104    fn into(self) -> InterpErrorInfo<'tcx> {
105        ::rustc_middle::mir::interpret::InterpErrorKind::MachineStop(Box::new(self))err_machine_stop!(self).into()
106    }
107}
108
109pub fn get_span_and_frames<'tcx>(
110    tcx: TyCtxtAt<'tcx>,
111    stack: &[Frame<'tcx, impl Provenance, impl Sized>],
112) -> (Span, Vec<errors::FrameNote>) {
113    let mut stacktrace = Frame::generate_stacktrace_from_stack(stack, *tcx);
114    // Filter out `requires_caller_location` frames.
115    stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*tcx));
116    let span = stacktrace.last().map(|f| f.span).unwrap_or(tcx.span);
117
118    let mut frames = Vec::new();
119
120    // Add notes to the backtrace. Don't print a single-line backtrace though.
121    if stacktrace.len() > 1 {
122        // Helper closure to print duplicated lines.
123        let mut add_frame = |mut frame: errors::FrameNote| {
124            frames.push(errors::FrameNote { times: 0, ..frame.clone() });
125            // Don't print [... additional calls ...] if the number of lines is small
126            if frame.times < 3 {
127                let times = frame.times;
128                frame.times = 0;
129                frames.extend(std::iter::repeat_n(frame, times as usize));
130            } else {
131                frames.push(frame);
132            }
133        };
134
135        let mut last_frame: Option<errors::FrameNote> = None;
136        for frame_info in &stacktrace {
137            let frame = frame_info.as_note(*tcx);
138            match last_frame.as_mut() {
139                Some(last_frame)
140                    if last_frame.span == frame.span
141                        && last_frame.where_ == frame.where_
142                        && last_frame.instance == frame.instance =>
143                {
144                    last_frame.times += 1;
145                }
146                Some(last_frame) => {
147                    add_frame(mem::replace(last_frame, frame));
148                }
149                None => {
150                    last_frame = Some(frame);
151                }
152            }
153        }
154        if let Some(frame) = last_frame {
155            add_frame(frame);
156        }
157    }
158
159    // In `rustc`, we present const-eval errors from the outer-most place first to the inner-most.
160    // So we reverse the frames here. The first frame will be the same as the span from the current
161    // `TyCtxtAt<'_>`, so we remove it as it would be redundant.
162    frames.reverse();
163    if frames.len() > 0 {
164        frames.remove(0);
165    }
166    if let Some(last) = frames.last_mut()
167        // If the span is not going to be printed, we don't want the span label for `is_last`.
168        && tcx.sess.source_map().span_to_snippet(last.span.source_callsite()).is_ok()
169    {
170        last.has_label = true;
171    }
172
173    (span, frames)
174}
175
176/// Create a diagnostic for a const eval error.
177///
178/// This will use the `mk` function for adding more information to the error.
179/// You can use it to add a stacktrace of current execution according to
180/// `get_span_and_frames` or just give context on where the const eval error happened.
181pub(super) fn report<'tcx, C, F>(
182    ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
183    error: InterpErrorKind<'tcx>,
184    span: Span,
185    get_span_and_frames: C,
186    mk: F,
187) -> ErrorHandled
188where
189    C: FnOnce() -> (Span, Vec<FrameNote>),
190    F: FnOnce(&mut Diag<'_>, Span, Vec<FrameNote>),
191{
192    let tcx = ecx.tcx.tcx;
193    // Special handling for certain errors
194    match error {
195        // Don't emit a new diagnostic for these errors, they are already reported elsewhere or
196        // should remain silent.
197        ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(info))err_inval!(AlreadyReported(info)) => ErrorHandled::Reported(info, span),
198        ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::Layout(LayoutError::TooGeneric(_)))err_inval!(Layout(LayoutError::TooGeneric(_))) | ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)err_inval!(TooGeneric) => {
199            ErrorHandled::TooGeneric(span)
200        }
201        ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::Layout(LayoutError::ReferencesError(guar)))err_inval!(Layout(LayoutError::ReferencesError(guar))) => {
202            // This can occur in infallible promoteds e.g. when a non-existent type or field is
203            // encountered.
204            ErrorHandled::Reported(ReportedErrorInfo::allowed_in_infallible(guar), span)
205        }
206        // Report remaining errors.
207        _ => {
208            let (our_span, frames) = get_span_and_frames();
209            let span = span.substitute_dummy(our_span);
210            let mut err = tcx.dcx().struct_span_err(our_span, error.diagnostic_message());
211            // We allow invalid programs in infallible promoteds since invalid layouts can occur
212            // anyway (e.g. due to size overflow). And we allow OOM as that can happen any time.
213            let allowed_in_infallible = #[allow(non_exhaustive_omitted_patterns)] match error {
    InterpErrorKind::ResourceExhaustion(_) |
        InterpErrorKind::InvalidProgram(_) => true,
    _ => false,
}matches!(
214                error,
215                InterpErrorKind::ResourceExhaustion(_) | InterpErrorKind::InvalidProgram(_)
216            );
217
218            if let InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(
219                Some((alloc_id, _access)),
220            )) = error
221            {
222                let bytes = ecx.print_alloc_bytes_for_diagnostics(alloc_id);
223                let info = ecx.get_alloc_info(alloc_id);
224                let raw_bytes = errors::RawBytesNote {
225                    size: info.size.bytes(),
226                    align: info.align.bytes(),
227                    bytes,
228                };
229                err.subdiagnostic(raw_bytes);
230            }
231
232            error.add_args(&mut err);
233
234            mk(&mut err, span, frames);
235            let g = err.emit();
236            let reported = if allowed_in_infallible {
237                ReportedErrorInfo::allowed_in_infallible(g)
238            } else {
239                ReportedErrorInfo::const_eval_error(g)
240            };
241            ErrorHandled::Reported(reported, span)
242        }
243    }
244}
245
246/// Emit a lint from a const-eval situation, with a backtrace.
247// Even if this is unused, please don't remove it -- chances are we will need to emit a lint during const-eval again in the future!
248#[allow(unused)]
249pub(super) fn lint<'tcx, L>(
250    tcx: TyCtxtAt<'tcx>,
251    machine: &CompileTimeMachine<'tcx>,
252    lint: &'static rustc_session::lint::Lint,
253    decorator: impl FnOnce(Vec<errors::FrameNote>) -> L,
254) where
255    L: for<'a> rustc_errors::Diagnostic<'a, ()>,
256{
257    let (span, frames) = get_span_and_frames(tcx, &machine.stack);
258
259    tcx.emit_node_span_lint(lint, machine.best_lint_scope(*tcx), span, decorator(frames));
260}