Skip to content

Commit 9ac8b36

Browse files
committed
don't point at const usage site for resolution-time errors
also share the code that emits the actual error
1 parent 89ac57d commit 9ac8b36

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+133
-171
lines changed

Diff for: compiler/rustc_codegen_cranelift/src/base.rs

+9-16
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
33
use rustc_ast::InlineAsmOptions;
44
use rustc_index::IndexVec;
5-
use rustc_middle::mir::interpret::ErrorHandled;
65
use rustc_middle::ty::adjustment::PointerCoercion;
76
use rustc_middle::ty::layout::FnAbiOf;
87
use rustc_middle::ty::print::with_no_trimmed_paths;
@@ -251,21 +250,15 @@ pub(crate) fn verify_func(
251250
}
252251

253252
fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
254-
match fx.mir.post_mono_checks(fx.tcx, ty::ParamEnv::reveal_all(), |c| Ok(fx.monomorphize(c))) {
255-
Ok(()) => {}
256-
Err(ErrorHandled::TooGeneric(span)) => {
257-
span_bug!(span, "codegen encountered polymorphic constant");
258-
}
259-
Err(ErrorHandled::Reported(info, span)) => {
260-
if !info.is_tainted_by_errors() {
261-
fx.tcx.sess.span_err(span, "erroneous constant encountered");
262-
}
263-
fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
264-
fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
265-
// compilation should have been aborted
266-
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
267-
return;
268-
}
253+
if let Err(err) =
254+
fx.mir.post_mono_checks(fx.tcx, ty::ParamEnv::reveal_all(), |c| Ok(fx.monomorphize(c)))
255+
{
256+
err.emit_err(fx.tcx);
257+
fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
258+
fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
259+
// compilation should have been aborted
260+
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
261+
return;
269262
}
270263

271264
let arg_uninhabited = fx

Diff for: compiler/rustc_codegen_ssa/messages.ftl

-4
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ codegen_ssa_copy_path_buf = unable to copy {$source_file} to {$output_path}: {$e
1919
2020
codegen_ssa_create_temp_dir = couldn't create a temp dir: {$error}
2121
22-
codegen_ssa_erroneous_constant = erroneous constant encountered
23-
2422
codegen_ssa_error_creating_remark_dir = failed to create remark directory: {$error}
2523
2624
codegen_ssa_expected_coverage_symbol = expected `coverage(off)` or `coverage(on)`
@@ -174,8 +172,6 @@ codegen_ssa_no_natvis_directory = error enumerating natvis directory: {$error}
174172
175173
codegen_ssa_option_gcc_only = option `-Z gcc-ld` is used even though linker flavor is not gcc
176174
177-
codegen_ssa_polymorphic_constant_too_generic = codegen encountered polymorphic constant: TooGeneric
178-
179175
codegen_ssa_processing_dymutil_failed = processing debug info with `dsymutil` failed: {$status}
180176
.note = {$output}
181177

Diff for: compiler/rustc_codegen_ssa/src/errors.rs

-14
Original file line numberDiff line numberDiff line change
@@ -595,20 +595,6 @@ pub struct InvalidWindowsSubsystem {
595595
pub subsystem: Symbol,
596596
}
597597

598-
#[derive(Diagnostic)]
599-
#[diag(codegen_ssa_erroneous_constant)]
600-
pub struct ErroneousConstant {
601-
#[primary_span]
602-
pub span: Span,
603-
}
604-
605-
#[derive(Diagnostic)]
606-
#[diag(codegen_ssa_polymorphic_constant_too_generic)]
607-
pub struct PolymorphicConstantTooGeneric {
608-
#[primary_span]
609-
pub span: Span,
610-
}
611-
612598
#[derive(Diagnostic)]
613599
#[diag(codegen_ssa_shuffle_indices_evaluation)]
614600
pub struct ShuffleIndicesEvaluation {

Diff for: compiler/rustc_codegen_ssa/src/mir/mod.rs

+8-16
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
use crate::base;
2-
use crate::errors;
32
use crate::traits::*;
43
use rustc_index::bit_set::BitSet;
54
use rustc_index::IndexVec;
65
use rustc_middle::mir;
7-
use rustc_middle::mir::interpret::ErrorHandled;
86
use rustc_middle::mir::traversal;
97
use rustc_middle::mir::UnwindTerminateReason;
108
use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout};
@@ -214,20 +212,14 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
214212
fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut start_bx);
215213

216214
// Rust post-monomorphization checks; we later rely on them.
217-
match mir.post_mono_checks(cx.tcx(), ty::ParamEnv::reveal_all(), |c| Ok(fx.monomorphize(c))) {
218-
Ok(()) => {}
219-
Err(ErrorHandled::TooGeneric(span)) => {
220-
cx.tcx().sess.diagnostic().emit_bug(errors::PolymorphicConstantTooGeneric { span });
221-
}
222-
Err(ErrorHandled::Reported(info, span)) => {
223-
if !info.is_tainted_by_errors() {
224-
cx.tcx().sess.emit_err(errors::ErroneousConstant { span });
225-
}
226-
// This IR shouldn't ever be emitted, but let's try to guard against any of this code
227-
// ever running.
228-
start_bx.abort();
229-
return;
230-
}
215+
if let Err(err) =
216+
mir.post_mono_checks(cx.tcx(), ty::ParamEnv::reveal_all(), |c| Ok(fx.monomorphize(c)))
217+
{
218+
err.emit_err(cx.tcx());
219+
// This IR shouldn't ever be emitted, but let's try to guard against any of this code
220+
// ever running.
221+
start_bx.abort();
222+
return;
231223
}
232224

233225
let memory_locals = analyze::non_ssa_locals(&fx);

Diff for: compiler/rustc_const_eval/messages.ftl

-3
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,6 @@ const_eval_dyn_call_vtable_mismatch =
8383
const_eval_dyn_star_call_vtable_mismatch =
8484
`dyn*` call on a pointer whose vtable does not match its type
8585
86-
const_eval_erroneous_constant =
87-
erroneous constant used
88-
8986
const_eval_error = {$error_kind ->
9087
[static] could not evaluate static initializer
9188
[const] evaluation of constant value failed

Diff for: compiler/rustc_const_eval/src/errors.rs

-7
Original file line numberDiff line numberDiff line change
@@ -239,13 +239,6 @@ pub struct LongRunningWarn {
239239
pub item_span: Span,
240240
}
241241

242-
#[derive(Diagnostic)]
243-
#[diag(const_eval_erroneous_constant)]
244-
pub(crate) struct ErroneousConstUsed {
245-
#[primary_span]
246-
pub span: Span,
247-
}
248-
249242
#[derive(Subdiagnostic)]
250243
#[note(const_eval_non_const_impl)]
251244
pub(crate) struct NonConstImplNote {

Diff for: compiler/rustc_const_eval/src/interpret/eval_context.rs

+2-12
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use super::{
2424
MemPlaceMeta, Memory, MemoryKind, OpTy, Operand, Place, PlaceTy, Pointer, PointerArithmetic,
2525
Projectable, Provenance, Scalar, StackPopJump,
2626
};
27-
use crate::errors::{self, ErroneousConstUsed};
27+
use crate::errors;
2828
use crate::util;
2929
use crate::{fluent_generated as fluent, ReportErrorExt};
3030

@@ -1063,17 +1063,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
10631063
) -> Result<T, ErrorHandled> {
10641064
// Use a precise span for better cycle errors.
10651065
query(self.tcx.at(span.unwrap_or_else(|| self.cur_span()))).map_err(|err| {
1066-
match err {
1067-
ErrorHandled::Reported(err, reported_span) => {
1068-
// We trust the provided span more than the one that came out of the query.
1069-
let span = span.unwrap_or(reported_span);
1070-
if !err.is_tainted_by_errors() {
1071-
// To make it easier to figure out where this error comes from, also add a note at the current location.
1072-
self.tcx.sess.emit_note(ErroneousConstUsed { span });
1073-
}
1074-
}
1075-
ErrorHandled::TooGeneric(_) => {}
1076-
}
1066+
err.emit_note(*self.tcx);
10771067
err
10781068
})
10791069
}

Diff for: compiler/rustc_middle/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ middle_drop_check_overflow =
5252
overflow while adding drop-check rules for {$ty}
5353
.note = overflowed on {$overflow_ty}
5454
55+
middle_erroneous_constant = erroneous constant encountered
56+
5557
middle_layout_references_error =
5658
the type has an unknown layout
5759

Diff for: compiler/rustc_middle/src/error.rs

+7
Original file line numberDiff line numberDiff line change
@@ -144,5 +144,12 @@ pub struct UnsupportedFnAbi {
144144
pub abi: &'static str,
145145
}
146146

147+
#[derive(Diagnostic)]
148+
#[diag(middle_erroneous_constant)]
149+
pub struct ErroneousConstant {
150+
#[primary_span]
151+
pub span: Span,
152+
}
153+
147154
/// Used by `rustc_const_eval`
148155
pub use crate::fluent_generated::middle_adjust_for_foreign_abi_error;

Diff for: compiler/rustc_middle/src/mir/interpret/error.rs

+28-7
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
use super::{AllocId, AllocRange, ConstAlloc, Pointer, Scalar};
22

3+
use crate::error;
34
use crate::mir::interpret::ConstValue;
45
use crate::query::TyCtxtAt;
5-
use crate::ty::{layout, tls, Ty, ValTree};
6+
use crate::ty::{layout, tls, Ty, TyCtxt, ValTree};
67

78
use rustc_data_structures::sync::Lock;
89
use rustc_errors::{
@@ -41,6 +42,32 @@ impl ErrorHandled {
4142
ErrorHandled::TooGeneric(_span) => ErrorHandled::TooGeneric(span),
4243
}
4344
}
45+
46+
pub fn emit_err(&self, tcx: TyCtxt<'_>) -> ErrorGuaranteed {
47+
match self {
48+
&ErrorHandled::Reported(err, span) => {
49+
if !err.is_tainted_by_errors && !span.is_dummy() {
50+
tcx.sess.emit_err(error::ErroneousConstant { span });
51+
}
52+
err.error
53+
}
54+
&ErrorHandled::TooGeneric(span) => tcx.sess.delay_span_bug(
55+
span,
56+
"encountered TooGeneric error when monomorphic data was expected",
57+
),
58+
}
59+
}
60+
61+
pub fn emit_note(&self, tcx: TyCtxt<'_>) {
62+
match self {
63+
&ErrorHandled::Reported(err, span) => {
64+
if !err.is_tainted_by_errors && !span.is_dummy() {
65+
tcx.sess.emit_note(error::ErroneousConstant { span });
66+
}
67+
}
68+
&ErrorHandled::TooGeneric(_) => {}
69+
}
70+
}
4471
}
4572

4673
#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
@@ -54,12 +81,6 @@ impl ReportedErrorInfo {
5481
pub fn tainted_by_errors(error: ErrorGuaranteed) -> ReportedErrorInfo {
5582
ReportedErrorInfo { is_tainted_by_errors: true, error }
5683
}
57-
58-
/// Returns true if evaluation failed because MIR was tainted by errors.
59-
#[inline]
60-
pub fn is_tainted_by_errors(self) -> bool {
61-
self.is_tainted_by_errors
62-
}
6384
}
6485

6586
impl From<ErrorGuaranteed> for ReportedErrorInfo {

Diff for: compiler/rustc_middle/src/mir/interpret/queries.rs

+12-6
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,10 @@ impl<'tcx> TyCtxt<'tcx> {
6161
let cid = GlobalId { instance, promoted: ct.promoted };
6262
self.const_eval_global_id(param_env, cid, span)
6363
}
64-
Ok(None) => Err(ErrorHandled::TooGeneric(span.unwrap_or(DUMMY_SP))),
65-
Err(err) => Err(ErrorHandled::Reported(err.into(), span.unwrap_or(DUMMY_SP))),
64+
// For errors during resolution, we deliberately do not point at the usage site of the constant,
65+
// since for these errors the place the constant is used shouldn't matter.
66+
Ok(None) => Err(ErrorHandled::TooGeneric(DUMMY_SP)),
67+
Err(err) => Err(ErrorHandled::Reported(err.into(), DUMMY_SP)),
6668
}
6769
}
6870

@@ -117,8 +119,10 @@ impl<'tcx> TyCtxt<'tcx> {
117119
}
118120
})
119121
}
120-
Ok(None) => Err(ErrorHandled::TooGeneric(span.unwrap_or(DUMMY_SP))),
121-
Err(err) => Err(ErrorHandled::Reported(err.into(), span.unwrap_or(DUMMY_SP))),
122+
// For errors during resolution, we deliberately do not point at the usage site of the constant,
123+
// since for these errors the place the constant is used shouldn't matter.
124+
Ok(None) => Err(ErrorHandled::TooGeneric(DUMMY_SP)),
125+
Err(err) => Err(ErrorHandled::Reported(err.into(), DUMMY_SP)),
122126
}
123127
}
124128

@@ -143,7 +147,8 @@ impl<'tcx> TyCtxt<'tcx> {
143147
// improve caching of queries.
144148
let inputs = self.erase_regions(param_env.and(cid));
145149
if let Some(span) = span {
146-
self.at(span).eval_to_const_value_raw(inputs)
150+
// The query doesn't know where it is being invoked, so we need to fix the span.
151+
self.at(span).eval_to_const_value_raw(inputs).map_err(|e| e.with_span(span))
147152
} else {
148153
self.eval_to_const_value_raw(inputs)
149154
}
@@ -162,7 +167,8 @@ impl<'tcx> TyCtxt<'tcx> {
162167
let inputs = self.erase_regions(param_env.and(cid));
163168
debug!(?inputs);
164169
if let Some(span) = span {
165-
self.at(span).eval_to_valtree(inputs)
170+
// The query doesn't know where it is being invoked, so we need to fix the span.
171+
self.at(span).eval_to_valtree(inputs).map_err(|e| e.with_span(span))
166172
} else {
167173
self.eval_to_valtree(inputs)
168174
}

Diff for: compiler/rustc_middle/src/mir/mod.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -588,10 +588,7 @@ impl<'tcx> Body<'tcx> {
588588
// the body successfully evaluate.
589589
for &const_ in &self.required_consts {
590590
let c = normalize_const(const_.literal)?;
591-
c.eval(tcx, param_env, Some(const_.span)).map_err(|e| {
592-
// The query results don't always have the span we want.
593-
e.with_span(const_.span)
594-
})?;
591+
c.eval(tcx, param_env, Some(const_.span))?;
595592
}
596593

597594
Ok(())

Diff for: src/tools/clippy/tests/ui-toml/suppress_lint_in_const/test.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ error[E0080]: evaluation of `main::{constant#3}` failed
44
LL | const { &ARR[idx4()] }; // Ok, should not produce stderr, since `suppress-restriction-lint-in-const` is set true.
55
| ^^^^^^^^^^^ index out of bounds: the length is 2 but the index is 4
66

7-
note: erroneous constant used
7+
note: erroneous constant encountered
88
--> $DIR/test.rs:37:5
99
|
1010
LL | const { &ARR[idx4()] }; // Ok, should not produce stderr, since `suppress-restriction-lint-in-const` is set true.

Diff for: src/tools/clippy/tests/ui/indexing_slicing_index.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ error[E0080]: evaluation of `main::{constant#3}` failed
2424
LL | const { &ARR[idx4()] };
2525
| ^^^^^^^^^^^ index out of bounds: the length is 2 but the index is 4
2626

27-
note: erroneous constant used
27+
note: erroneous constant encountered
2828
--> $DIR/indexing_slicing_index.rs:48:5
2929
|
3030
LL | const { &ARR[idx4()] };

Diff for: src/tools/miri/tests/fail/const-ub-checks.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed
44
LL | ptr.read();
55
| ^^^^^^^^^^ accessing memory with alignment ALIGN, but alignment ALIGN is required
66

7-
note: erroneous constant used
7+
note: erroneous constant encountered
88
--> $DIR/const-ub-checks.rs:LL:CC
99
|
1010
LL | let _x = UNALIGNED_READ;

Diff for: src/tools/miri/tests/fail/erroneous_const.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ LL | const VOID: ! = panic!();
66
|
77
= note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
88

9-
note: erroneous constant used
9+
note: erroneous constant encountered
1010
--> $DIR/erroneous_const.rs:LL:CC
1111
|
1212
LL | let _ = PrintName::<T>::VOID;

Diff for: src/tools/miri/tests/fail/erroneous_const2.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ error[E0080]: evaluation of constant value failed
44
LL | const FOO: u32 = [X - Y, Y - X][(X < Y) as usize];
55
| ^^^^^ attempt to compute `5_u32 - 6_u32`, which would overflow
66

7-
note: erroneous constant used
7+
note: erroneous constant encountered
88
--> $DIR/erroneous_const2.rs:LL:CC
99
|
1010
LL | println!("{}", FOO);
1111
| ^^^
1212

13-
note: erroneous constant used
13+
note: erroneous constant encountered
1414
--> $DIR/erroneous_const2.rs:LL:CC
1515
|
1616
LL | println!("{}", FOO);

Diff for: tests/ui/associated-consts/defaults-not-assumed-fail.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,21 @@ error[E0080]: evaluation of `<() as Tr>::B` failed
44
LL | const B: u8 = Self::A + 1;
55
| ^^^^^^^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow
66

7-
note: erroneous constant used
7+
note: erroneous constant encountered
88
--> $DIR/defaults-not-assumed-fail.rs:33:16
99
|
1010
LL | assert_eq!(<() as Tr>::B, 0); // causes the error above
1111
| ^^^^^^^^^^^^^
1212

13-
note: erroneous constant used
13+
note: erroneous constant encountered
1414
--> $DIR/defaults-not-assumed-fail.rs:33:5
1515
|
1616
LL | assert_eq!(<() as Tr>::B, 0); // causes the error above
1717
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1818
|
1919
= note: this note originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
2020

21-
note: erroneous constant used
21+
note: erroneous constant encountered
2222
--> $DIR/defaults-not-assumed-fail.rs:33:5
2323
|
2424
LL | assert_eq!(<() as Tr>::B, 0); // causes the error above

Diff for: tests/ui/borrowck/issue-81899.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ LL | const _CONST: &[u8] = &f(&[], |_| {});
1616
| ^^^^^^^^^^^^^^
1717
= 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)
1818

19-
note: erroneous constant used
19+
note: erroneous constant encountered
2020
--> $DIR/issue-81899.rs:4:23
2121
|
2222
LL | const _CONST: &[u8] = &f(&[], |_| {});

0 commit comments

Comments
 (0)