rustc_const_eval/const_eval/
error.rs1use std::mem;
2
3use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, Diagnostic, IntoDiagArg};
4use rustc_middle::mir::AssertKind;
5use rustc_middle::mir::interpret::{Provenance, ReportedErrorInfo};
6use rustc_middle::query::TyCtxtAt;
7use rustc_middle::ty::layout::LayoutError;
8use rustc_middle::ty::{ConstInt, TyCtxt};
9use rustc_span::{Span, Symbol};
10
11use super::CompileTimeMachine;
12use crate::errors::{self, FrameNote, ReportErrorExt};
13use crate::interpret::{
14 ErrorHandled, Frame, InterpErrorInfo, InterpErrorKind, MachineStopType, err_inval,
15 err_machine_stop,
16};
17
18#[derive(Clone, Debug)]
20pub enum ConstEvalErrKind {
21 ConstAccessesMutGlobal,
22 ModifiedGlobal,
23 RecursiveStatic,
24 AssertFailure(AssertKind<ConstInt>),
25 Panic { msg: Symbol, line: u32, col: u32, file: Symbol },
26 WriteThroughImmutablePointer,
27}
28
29impl MachineStopType for ConstEvalErrKind {
30 fn diagnostic_message(&self) -> DiagMessage {
31 use ConstEvalErrKind::*;
32
33 use crate::fluent_generated::*;
34 match self {
35 ConstAccessesMutGlobal => const_eval_const_accesses_mut_global,
36 ModifiedGlobal => const_eval_modified_global,
37 Panic { .. } => const_eval_panic,
38 RecursiveStatic => const_eval_recursive_static,
39 AssertFailure(x) => x.diagnostic_message(),
40 WriteThroughImmutablePointer => const_eval_write_through_immutable_pointer,
41 }
42 }
43 fn add_args(self: Box<Self>, adder: &mut dyn FnMut(DiagArgName, DiagArgValue)) {
44 use ConstEvalErrKind::*;
45 match *self {
46 RecursiveStatic
47 | ConstAccessesMutGlobal
48 | ModifiedGlobal
49 | WriteThroughImmutablePointer => {}
50 AssertFailure(kind) => kind.add_args(adder),
51 Panic { msg, line, col, file } => {
52 adder("msg".into(), msg.into_diag_arg());
53 adder("file".into(), file.into_diag_arg());
54 adder("line".into(), line.into_diag_arg());
55 adder("col".into(), col.into_diag_arg());
56 }
57 }
58 }
59}
60
61impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalErrKind {
63 fn into(self) -> InterpErrorInfo<'tcx> {
64 err_machine_stop!(self).into()
65 }
66}
67
68pub fn get_span_and_frames<'tcx>(
69 tcx: TyCtxtAt<'tcx>,
70 stack: &[Frame<'tcx, impl Provenance, impl Sized>],
71) -> (Span, Vec<errors::FrameNote>) {
72 let mut stacktrace = Frame::generate_stacktrace_from_stack(stack);
73 stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*tcx));
75 let span = stacktrace.first().map(|f| f.span).unwrap_or(tcx.span);
76
77 let mut frames = Vec::new();
78
79 if stacktrace.len() > 1 {
81 let mut add_frame = |mut frame: errors::FrameNote| {
83 frames.push(errors::FrameNote { times: 0, ..frame.clone() });
84 if frame.times < 3 {
86 let times = frame.times;
87 frame.times = 0;
88 frames.extend(std::iter::repeat(frame).take(times as usize));
89 } else {
90 frames.push(frame);
91 }
92 };
93
94 let mut last_frame: Option<errors::FrameNote> = None;
95 for frame_info in &stacktrace {
96 let frame = frame_info.as_note(*tcx);
97 match last_frame.as_mut() {
98 Some(last_frame)
99 if last_frame.span == frame.span
100 && last_frame.where_ == frame.where_
101 && last_frame.instance == frame.instance =>
102 {
103 last_frame.times += 1;
104 }
105 Some(last_frame) => {
106 add_frame(mem::replace(last_frame, frame));
107 }
108 None => {
109 last_frame = Some(frame);
110 }
111 }
112 }
113 if let Some(frame) = last_frame {
114 add_frame(frame);
115 }
116 }
117
118 (span, frames)
119}
120
121pub(super) fn report<'tcx, C, F, E>(
127 tcx: TyCtxt<'tcx>,
128 error: InterpErrorKind<'tcx>,
129 span: Span,
130 get_span_and_frames: C,
131 mk: F,
132) -> ErrorHandled
133where
134 C: FnOnce() -> (Span, Vec<FrameNote>),
135 F: FnOnce(Span, Vec<FrameNote>) -> E,
136 E: Diagnostic<'tcx>,
137{
138 match error {
140 err_inval!(AlreadyReported(info)) => ErrorHandled::Reported(info, span),
143 err_inval!(Layout(LayoutError::TooGeneric(_))) | err_inval!(TooGeneric) => {
144 ErrorHandled::TooGeneric(span)
145 }
146 err_inval!(Layout(LayoutError::ReferencesError(guar))) => {
147 ErrorHandled::Reported(ReportedErrorInfo::allowed_in_infallible(guar), span)
150 }
151 _ => {
153 let (our_span, frames) = get_span_and_frames();
154 let span = span.substitute_dummy(our_span);
155 let err = mk(span, frames);
156 let mut err = tcx.dcx().create_err(err);
157 let allowed_in_infallible = matches!(
160 error,
161 InterpErrorKind::ResourceExhaustion(_) | InterpErrorKind::InvalidProgram(_)
162 );
163
164 let msg = error.diagnostic_message();
165 error.add_args(&mut err);
166
167 err.span_label(our_span, msg);
169 let g = err.emit();
170 let reported = if allowed_in_infallible {
171 ReportedErrorInfo::allowed_in_infallible(g)
172 } else {
173 ReportedErrorInfo::const_eval_error(g)
174 };
175 ErrorHandled::Reported(reported, span)
176 }
177 }
178}
179
180#[allow(unused)]
183pub(super) fn lint<'tcx, L>(
184 tcx: TyCtxtAt<'tcx>,
185 machine: &CompileTimeMachine<'tcx>,
186 lint: &'static rustc_session::lint::Lint,
187 decorator: impl FnOnce(Vec<errors::FrameNote>) -> L,
188) where
189 L: for<'a> rustc_errors::LintDiagnostic<'a, ()>,
190{
191 let (span, frames) = get_span_and_frames(tcx, &machine.stack);
192
193 tcx.emit_node_span_lint(lint, machine.best_lint_scope(*tcx), span, decorator(frames));
194}