Rollup merge of #152226 - fmease:modernize-indeterminate-object-lifetime-diag, r=chenyukang

Modernize diagnostic for indeterminate trait object lifetime bounds

* remove suggestion from the diagnostic message (bad style, too long) and turn it into a structured suggestion
* replace *object type* with *trait object type* since the former is an outdated term
This commit is contained in:
Jonathan Brouwer 2026-02-10 13:00:46 +01:00 committed by GitHub
commit 2af7bc0e17
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 63 additions and 27 deletions

View file

@ -22,9 +22,7 @@ use rustc_abi::{ExternAbi, Size};
use rustc_ast::Recovered;
use rustc_data_structures::assert_matches;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::{
Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey, struct_span_code_err,
};
use rustc_errors::{Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey};
use rustc_hir::attrs::AttributeKind;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId};
@ -318,16 +316,24 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
}
fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
if let RegionInferReason::ObjectLifetimeDefault = reason {
let e = struct_span_code_err!(
self.dcx(),
span,
E0228,
"the lifetime bound for this object type cannot be deduced \
from context; please supply an explicit bound"
)
.emit();
ty::Region::new_error(self.tcx(), e)
if let RegionInferReason::ObjectLifetimeDefault(sugg_sp) = reason {
// FIXME: Account for trailing plus `dyn Trait+`, the need of parens in
// `*const dyn Trait` and `Fn() -> *const dyn Trait`.
let guar = self
.dcx()
.struct_span_err(
span,
"cannot deduce the lifetime bound for this trait object type from context",
)
.with_code(E0228)
.with_span_suggestion_verbose(
sugg_sp,
"please supply an explicit bound",
" + /* 'a */",
Applicability::HasPlaceholders,
)
.emit();
ty::Region::new_error(self.tcx(), guar)
} else {
// This indicates an illegal lifetime in a non-assoc-trait position
ty::Region::new_error_with_message(self.tcx(), span, "unelided lifetime in signature")

View file

@ -460,7 +460,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// Parent lifetime must have failed to resolve. Don't emit a redundant error.
RegionInferReason::ExplicitObjectLifetime
} else {
RegionInferReason::ObjectLifetimeDefault
RegionInferReason::ObjectLifetimeDefault(span.shrink_to_hi())
}
} else {
RegionInferReason::ExplicitObjectLifetime

View file

@ -104,7 +104,7 @@ pub enum RegionInferReason<'a> {
/// Lifetime on a trait object that is spelled explicitly, e.g. `+ 'a` or `+ '_`.
ExplicitObjectLifetime,
/// A trait object's lifetime when it is elided, e.g. `dyn Any`.
ObjectLifetimeDefault,
ObjectLifetimeDefault(Span),
/// Generic lifetime parameter
Param(&'a ty::GenericParamDef),
RegionPredicate,