Shorten span of panic failures in const context

Previously, we included a redundant prefix on the panic message and a postfix of the location of the panic. The prefix didn't carry any additional information beyond "something failed", and the location of the panic is redundant with the diagnostic's span, which gets printed out even if its code is not shown.

```
error[E0080]: evaluation of constant value failed
  --> $DIR/assert-type-intrinsics.rs:11:9
   |
LL |         MaybeUninit::<!>::uninit().assume_init();
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: aborted execution: attempted to instantiate uninhabited type `!`
```

```
error[E0080]: evaluation of `Fail::<i32>::C` failed
  --> $DIR/collect-in-dead-closure.rs:9:19
   |
LL |     const C: () = panic!();
   |                   ^^^^^^^^ evaluation panicked: explicit panic
   |
   = note: this error originates in the macro
`$crate::panic::panic_2015` which comes from the expansion of the macro
`panic` (in Nightly builds, run with -Z macro-backtrace for more info)
```

```
error[E0080]: evaluation of constant value failed
  --> $DIR/uninhabited.rs:41:9
   |
LL |         assert!(false);
   |         ^^^^^^^^^^^^^^ evaluation panicked: assertion failed: false
   |
   = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info)
```

---

When the primary span for a const error is the same as the first frame in the const error report, skip it.

```
error[E0080]: evaluation of constant value failed
  --> $DIR/issue-88434-removal-index-should-be-less.rs:3:24
   |
LL | const _CONST: &[u8] = &f(&[], |_| {});
   |                        ^^^^^^^^^^^^^^ evaluation panicked: explicit panic
   |
note: inside `f::<{closure@$DIR/issue-88434-removal-index-should-be-less.rs:3:31: 3:34}>`
  --> $DIR/issue-88434-removal-index-should-be-less.rs:10:5
   |
LL |     panic!()
   |     ^^^^^^^^ the failure occurred here
   = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
```
instead of
```
error[E0080]: evaluation of constant value failed
  --> $DIR/issue-88434-removal-index-should-be-less.rs:10:5
   |
LL |     panic!()
   |     ^^^^^^^^ explicit panic
   |
note: inside `f::<{closure@$DIR/issue-88434-removal-index-should-be-less.rs:3:31: 3:34}>`
  --> $DIR/issue-88434-removal-index-should-be-less.rs:10:5
   |
LL |     panic!()
   |     ^^^^^^^^
note: inside `_CONST`
  --> $DIR/issue-88434-removal-index-should-be-less.rs:3:24
   |
LL | const _CONST: &[u8] = &f(&[], |_| {});
   |                        ^^^^^^^^^^^^^^
   = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
```

---

Revert order of constant evaluation errors

Point at the code the user wrote first and std functions last.

```
error[E0080]: evaluation of constant value failed
  --> $DIR/const-errs-dont-conflict-103369.rs:5:25
   |
LL | impl ConstGenericTrait<{my_fn(1)}> for () {}
   |                         ^^^^^^^^ evaluation panicked: Some error occurred
   |
note: called from `my_fn`
  --> $DIR/const-errs-dont-conflict-103369.rs:10:5
   |
LL |     panic!("Some error occurred");
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
```
instead of
```
error[E0080]: evaluation of constant value failed
  --> $DIR/const-errs-dont-conflict-103369.rs:10:5
   |
LL |     panic!("Some error occurred");
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Some error occurred
   |
note: called from `<() as ConstGenericTrait<{my_fn(1)}>>::{constant#0}`
  --> $DIR/const-errs-dont-conflict-103369.rs:5:25
   |
LL | impl ConstGenericTrait<{my_fn(1)}> for () {}
   |                         ^^^^^^^^
   = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
```
This commit is contained in:
Esteban Küber 2025-02-03 18:43:55 +00:00
parent f45d4acf1b
commit 7d4d09eeeb
127 changed files with 1798 additions and 2018 deletions

View file

@ -109,6 +109,8 @@ const_eval_frame_note_inner = inside {$where_ ->
*[other] {""}
}
const_eval_frame_note_last = the failure occurred here
const_eval_in_bounds_test = out-of-bounds pointer use
const_eval_incompatible_calling_conventions =
calling a function with calling convention {$callee_conv} using calling convention {$caller_conv}
@ -300,8 +302,7 @@ const_eval_overflow_arith =
const_eval_overflow_shift =
overflowing shift by {$shift_amount} in `{$intrinsic}`
const_eval_panic =
the evaluated program panicked at '{$msg}', {$file}:{$line}:{$col}
const_eval_panic = evaluation panicked: {$msg}
const_eval_panic_non_str = argument to `panic!()` in a const context must have type `&str`

View file

@ -48,11 +48,8 @@ impl MachineStopType for ConstEvalErrKind {
| ModifiedGlobal
| WriteThroughImmutablePointer => {}
AssertFailure(kind) => kind.add_args(adder),
Panic { msg, line, col, file } => {
Panic { msg, .. } => {
adder("msg".into(), msg.into_diag_arg(&mut None));
adder("file".into(), file.into_diag_arg(&mut None));
adder("line".into(), line.into_diag_arg(&mut None));
adder("col".into(), col.into_diag_arg(&mut None));
}
}
}
@ -72,7 +69,7 @@ pub fn get_span_and_frames<'tcx>(
let mut stacktrace = Frame::generate_stacktrace_from_stack(stack);
// Filter out `requires_caller_location` frames.
stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*tcx));
let span = stacktrace.first().map(|f| f.span).unwrap_or(tcx.span);
let span = stacktrace.last().map(|f| f.span).unwrap_or(tcx.span);
let mut frames = Vec::new();
@ -115,6 +112,20 @@ pub fn get_span_and_frames<'tcx>(
}
}
// In `rustc`, we present const-eval errors from the outer-most place first to the inner-most.
// So we reverse the frames here. The first frame will be the same as the span from the current
// `TyCtxtAt<'_>`, so we remove it as it would be redundant.
frames.reverse();
if frames.len() > 0 {
frames.remove(0);
}
if let Some(last) = frames.last_mut()
// If the span is not going to be printed, we don't want the span label for `is_last`.
&& tcx.sess.source_map().span_to_snippet(last.span.source_callsite()).is_ok()
{
last.has_label = true;
}
(span, frames)
}

View file

@ -6,6 +6,7 @@ use rustc_abi::WrappingRange;
use rustc_errors::codes::*;
use rustc_errors::{
Diag, DiagArgValue, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, Level,
MultiSpan, SubdiagMessageOp, Subdiagnostic,
};
use rustc_hir::ConstContext;
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
@ -17,6 +18,7 @@ use rustc_middle::mir::interpret::{
use rustc_middle::ty::{self, Mutability, Ty};
use rustc_span::{Span, Symbol};
use crate::fluent_generated as fluent;
use crate::interpret::InternKind;
#[derive(Diagnostic)]
@ -278,14 +280,31 @@ pub(crate) struct NonConstImplNote {
pub span: Span,
}
#[derive(Subdiagnostic, Clone)]
#[note(const_eval_frame_note)]
#[derive(Clone)]
pub struct FrameNote {
#[primary_span]
pub span: Span,
pub times: i32,
pub where_: &'static str,
pub instance: String,
pub has_label: bool,
}
impl Subdiagnostic for FrameNote {
fn add_to_diag_with<G: EmissionGuarantee, F: SubdiagMessageOp<G>>(
self,
diag: &mut Diag<'_, G>,
f: &F,
) {
diag.arg("times", self.times);
diag.arg("where_", self.where_);
diag.arg("instance", self.instance);
let mut span: MultiSpan = self.span.into();
if self.has_label && !self.span.is_dummy() {
span.push_span_label(self.span, fluent::const_eval_frame_note_last);
}
let msg = f(diag, fluent::const_eval_frame_note.into());
diag.span_note(span, msg);
}
}
#[derive(Subdiagnostic)]

View file

@ -231,13 +231,19 @@ impl<'tcx> FrameInfo<'tcx> {
pub fn as_note(&self, tcx: TyCtxt<'tcx>) -> errors::FrameNote {
let span = self.span;
if tcx.def_key(self.instance.def_id()).disambiguated_data.data == DefPathData::Closure {
errors::FrameNote { where_: "closure", span, instance: String::new(), times: 0 }
errors::FrameNote {
where_: "closure",
span,
instance: String::new(),
times: 0,
has_label: false,
}
} else {
let instance = format!("{}", self.instance);
// Note: this triggers a `must_produce_diag` state, which means that if we ever get
// here we must emit a diagnostic. We should never display a `FrameInfo` unless we
// actually want to emit a warning or error to the user.
errors::FrameNote { where_: "instance", span, instance, times: 0 }
errors::FrameNote { where_: "instance", span, instance, times: 0, has_label: false }
}
}
}