1use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, msg};
5use rustc_hir as hir;
6use rustc_hir::GenericBound::Trait;
7use rustc_hir::QPath::Resolved;
8use rustc_hir::WherePredicateKind::BoundPredicate;
9use rustc_hir::def::Res::Def;
10use rustc_hir::def_id::DefId;
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::{PolyTraitRef, TyKind, WhereBoundPredicate};
13use rustc_infer::infer::{NllRegionVariableOrigin, SubregionOrigin};
14use rustc_middle::bug;
15use rustc_middle::hir::place::PlaceBase;
16use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint};
17use rustc_middle::ty::{
18 self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor, fold_regions,
19};
20use rustc_span::{Ident, Span, kw};
21use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
22use rustc_trait_selection::error_reporting::infer::nice_region_error::{
23 self, HirTraitObjectVisitor, NiceRegionError, TraitObjectVisitor, find_anon_type,
24 find_param_with_region, suggest_adding_lifetime_params,
25};
26use rustc_trait_selection::infer::InferCtxtExt;
27use rustc_trait_selection::traits::{Obligation, ObligationCtxt};
28use tracing::{debug, instrument, trace};
29
30use super::{LIMITATION_NOTE, OutlivesSuggestionBuilder, RegionName, RegionNameSource};
31use crate::consumers::RegionInferenceContext;
32use crate::nll::ConstraintDescription;
33use crate::region_infer::{BlameConstraint, TypeTest};
34use crate::session_diagnostics::{
35 FnMutError, FnMutReturnTypeErr, GenericDoesNotLiveLongEnough, LifetimeOutliveErr,
36 LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote,
37};
38use crate::universal_regions::DefiningTy;
39use crate::{MirBorrowckCtxt, borrowck_errors};
40
41impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
42 fn description(&self) -> &'static str {
43 match self {
45 ConstraintCategory::Assignment => "assignment ",
46 ConstraintCategory::Return(_) => "returning this value ",
47 ConstraintCategory::Yield => "yielding this value ",
48 ConstraintCategory::UseAsConst => "using this value as a constant ",
49 ConstraintCategory::UseAsStatic => "using this value as a static ",
50 ConstraintCategory::Cast { is_implicit_coercion: false, .. } => "cast ",
51 ConstraintCategory::Cast { is_implicit_coercion: true, .. } => "coercion ",
52 ConstraintCategory::CallArgument(_) => "argument ",
53 ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => "generic argument ",
54 ConstraintCategory::TypeAnnotation(_) => "type annotation ",
55 ConstraintCategory::SizedBound => "proving this value is `Sized` ",
56 ConstraintCategory::CopyBound => "copying this value ",
57 ConstraintCategory::OpaqueType => "opaque type ",
58 ConstraintCategory::ClosureUpvar(_) => "closure capture ",
59 ConstraintCategory::Usage => "this usage ",
60 ConstraintCategory::SolverRegionConstraint(_)
61 | ConstraintCategory::Predicate(_)
62 | ConstraintCategory::Boring
63 | ConstraintCategory::BoringNoLocation
64 | ConstraintCategory::Internal
65 | ConstraintCategory::OutlivesUnnameablePlaceholder(..) => "",
66 }
67 }
68}
69
70pub(crate) struct RegionErrors<'tcx>(Vec<(RegionErrorKind<'tcx>, ErrorGuaranteed)>, TyCtxt<'tcx>);
76
77impl<'tcx> RegionErrors<'tcx> {
78 pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
79 Self(::alloc::vec::Vec::new()vec![], tcx)
80 }
81 #[track_caller]
82 pub(crate) fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) {
83 let val = val.into();
84 let guar = self.1.sess.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", val))
})format!("{val:?}"));
85 self.0.push((val, guar));
86 }
87 pub(crate) fn is_empty(&self) -> bool {
88 self.0.is_empty()
89 }
90 pub(crate) fn into_iter(
91 self,
92 ) -> impl Iterator<Item = (RegionErrorKind<'tcx>, ErrorGuaranteed)> {
93 self.0.into_iter()
94 }
95}
96
97impl std::fmt::Debug for RegionErrors<'_> {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 f.debug_tuple("RegionErrors").field(&self.0).finish()
100 }
101}
102
103#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for RegionErrorKind<'tcx> {
#[inline]
fn clone(&self) -> RegionErrorKind<'tcx> {
match self {
RegionErrorKind::TypeTestError { type_test: __self_0 } =>
RegionErrorKind::TypeTestError {
type_test: ::core::clone::Clone::clone(__self_0),
},
RegionErrorKind::PlaceholderOutlivesIllegalRegion {
longer_fr: __self_0, illegally_outlived_r: __self_1 } =>
RegionErrorKind::PlaceholderOutlivesIllegalRegion {
longer_fr: ::core::clone::Clone::clone(__self_0),
illegally_outlived_r: ::core::clone::Clone::clone(__self_1),
},
RegionErrorKind::RegionError {
fr_origin: __self_0,
longer_fr: __self_1,
shorter_fr: __self_2,
is_reported: __self_3 } =>
RegionErrorKind::RegionError {
fr_origin: ::core::clone::Clone::clone(__self_0),
longer_fr: ::core::clone::Clone::clone(__self_1),
shorter_fr: ::core::clone::Clone::clone(__self_2),
is_reported: ::core::clone::Clone::clone(__self_3),
},
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RegionErrorKind<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
RegionErrorKind::TypeTestError { type_test: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"TypeTestError", "type_test", &__self_0),
RegionErrorKind::PlaceholderOutlivesIllegalRegion {
longer_fr: __self_0, illegally_outlived_r: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"PlaceholderOutlivesIllegalRegion", "longer_fr", __self_0,
"illegally_outlived_r", &__self_1),
RegionErrorKind::RegionError {
fr_origin: __self_0,
longer_fr: __self_1,
shorter_fr: __self_2,
is_reported: __self_3 } =>
::core::fmt::Formatter::debug_struct_field4_finish(f,
"RegionError", "fr_origin", __self_0, "longer_fr", __self_1,
"shorter_fr", __self_2, "is_reported", &__self_3),
}
}
}Debug)]
104pub(crate) enum RegionErrorKind<'tcx> {
105 TypeTestError { type_test: TypeTest<'tcx> },
107
108 PlaceholderOutlivesIllegalRegion { longer_fr: RegionVid, illegally_outlived_r: RegionVid },
111
112 RegionError {
114 fr_origin: NllRegionVariableOrigin<'tcx>,
116 longer_fr: RegionVid,
118 shorter_fr: RegionVid,
120 is_reported: bool,
123 },
124}
125
126#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ErrorConstraintInfo<'tcx> {
#[inline]
fn clone(&self) -> ErrorConstraintInfo<'tcx> {
ErrorConstraintInfo {
fr: ::core::clone::Clone::clone(&self.fr),
outlived_fr: ::core::clone::Clone::clone(&self.outlived_fr),
category: ::core::clone::Clone::clone(&self.category),
span: ::core::clone::Clone::clone(&self.span),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ErrorConstraintInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ErrorConstraintInfo", "fr", &self.fr, "outlived_fr",
&self.outlived_fr, "category", &self.category, "span",
&&self.span)
}
}Debug)]
128pub(crate) struct ErrorConstraintInfo<'tcx> {
129 pub(super) fr: RegionVid,
131 pub(super) outlived_fr: RegionVid,
132
133 pub(super) category: ConstraintCategory<'tcx>,
135 pub(super) span: Span,
136}
137
138impl<'tcx> RegionInferenceContext<'tcx> {
139 pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
146 self.to_error_region_vid(r).and_then(|r| self.region_definition(r).external_name)
147 }
148
149 pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
152 if self.universal_regions().is_universal_region(r) {
153 Some(r)
154 } else {
155 let upper_bound = self.approx_universal_upper_bound(r);
158
159 if self.upper_bound_in_region_scc(r, upper_bound) {
160 self.to_error_region_vid(upper_bound)
161 } else {
162 None
163 }
164 }
165 }
166
167 fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
169 where
170 T: TypeFoldable<TyCtxt<'tcx>>,
171 {
172 fold_regions(tcx, ty, |region, _| match region.kind() {
173 ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
174 _ => region,
175 })
176 }
177
178 fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
180 if let Some(r) = self.to_error_region(fr)
181 && let ty::ReLateParam(late_param) = r.kind()
182 && let ty::LateParamRegionKind::ClosureEnv = late_param.kind
183 && let DefiningTy::Closure(_, args) = self.universal_regions().defining_ty
184 {
185 return args.as_closure().kind() == ty::ClosureKind::FnMut;
186 }
187
188 false
189 }
190}
191
192impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
193 fn suggest_static_lifetime_for_gat_from_hrtb(
197 &self,
198 diag: &mut Diag<'_>,
199 lower_bound: RegionVid,
200 ) {
201 let tcx = self.infcx.tcx;
202
203 let gat_id_and_generics = self
205 .regioncx
206 .placeholders_contained_in(lower_bound)
207 .map(|placeholder| {
208 if let Some(id) = placeholder.bound.kind.get_id()
209 && let Some(placeholder_id) = id.as_local()
210 && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
211 && let Some(generics_impl) =
212 tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
213 {
214 Some((gat_hir_id, generics_impl))
215 } else {
216 None
217 }
218 })
219 .collect::<Vec<_>>();
220 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:220",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(220u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["gat_id_and_generics"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&gat_id_and_generics)
as &dyn Value))])
});
} else { ; }
};debug!(?gat_id_and_generics);
221
222 let mut hrtb_bounds = ::alloc::vec::Vec::new()vec![];
226 gat_id_and_generics.iter().flatten().for_each(|&(gat_hir_id, generics)| {
227 for pred in generics.predicates {
228 let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) =
229 pred.kind
230 else {
231 continue;
232 };
233 if bound_generic_params
234 .iter()
235 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
236 .is_some()
237 {
238 for bound in *bounds {
239 hrtb_bounds.push(bound);
240 }
241 } else {
242 for bound in *bounds {
243 if let Trait(trait_bound) = bound {
244 if trait_bound
245 .bound_generic_params
246 .iter()
247 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
248 .is_some()
249 {
250 hrtb_bounds.push(bound);
251 return;
252 }
253 }
254 }
255 }
256 }
257 });
258 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:258",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(258u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["hrtb_bounds"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&hrtb_bounds)
as &dyn Value))])
});
} else { ; }
};debug!(?hrtb_bounds);
259
260 let mut suggestions = ::alloc::vec::Vec::new()vec![];
261 hrtb_bounds.iter().for_each(|bound| {
262 let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }) = bound else {
263 return;
264 };
265 diag.span_note(*trait_span, LIMITATION_NOTE);
266 let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
267 else {
268 return;
269 };
270 let Def(_, trait_res_defid) = trait_ref.path.res else {
271 return;
272 };
273 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:273",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(273u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["generics_fn"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&generics_fn)
as &dyn Value))])
});
} else { ; }
};debug!(?generics_fn);
274 generics_fn.predicates.iter().for_each(|predicate| {
275 let BoundPredicate(WhereBoundPredicate { bounded_ty, bounds, .. }) = predicate.kind
276 else {
277 return;
278 };
279 bounds.iter().for_each(|bd| {
280 if let Trait(PolyTraitRef { trait_ref: tr_ref, .. }) = bd
281 && let Def(_, res_defid) = tr_ref.path.res
282 && res_defid == trait_res_defid && let TyKind::Path(Resolved(_, path)) = bounded_ty.kind
284 && let Def(_, defid) = path.res
285 && generics_fn.params
286 .iter()
287 .rfind(|param| param.def_id.to_def_id() == defid)
288 .is_some()
289 {
290 suggestions.push((predicate.span.shrink_to_hi(), " + 'static".to_string()));
291 }
292 });
293 });
294 });
295 if suggestions.len() > 0 {
296 suggestions.dedup();
297 diag.multipart_suggestion(
298 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider restricting the type parameter to the `'static` lifetime"))msg!("consider restricting the type parameter to the `'static` lifetime"),
299 suggestions,
300 Applicability::MaybeIncorrect,
301 );
302 }
303 }
304
305 pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
307 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
310 for (nll_error, _) in nll_errors.into_iter() {
311 match nll_error {
312 RegionErrorKind::TypeTestError { type_test } => {
313 let lower_bound_region = self.regioncx.to_error_region(type_test.lower_bound);
316
317 let type_test_span = type_test.span;
318
319 if let Some(lower_bound_region) = lower_bound_region {
320 let generic_ty = self.regioncx.name_regions(
321 self.infcx.tcx,
322 type_test.generic_kind.to_ty(self.infcx.tcx),
323 );
324 let origin =
325 SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
326 self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
327 self.body.source.def_id().expect_local(),
328 type_test_span,
329 Some(origin),
330 self.regioncx.name_regions(self.infcx.tcx, type_test.generic_kind),
331 lower_bound_region,
332 ));
333 } else {
334 let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
344 kind: type_test.generic_kind.to_string(),
345 span: type_test_span,
346 });
347
348 self.suggest_static_lifetime_for_gat_from_hrtb(
352 &mut diag,
353 type_test.lower_bound,
354 );
355
356 self.buffer_error(diag);
357 }
358 }
359
360 RegionErrorKind::PlaceholderOutlivesIllegalRegion {
361 longer_fr,
362 illegally_outlived_r,
363 } => {
364 self.report_erroneous_rvid_reaches_placeholder(longer_fr, illegally_outlived_r)
365 }
366
367 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
368 if is_reported {
369 self.report_region_error(
370 longer_fr,
371 fr_origin,
372 shorter_fr,
373 &mut outlives_suggestion,
374 );
375 } else {
376 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:382",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(382u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Unreported region error: can\'t prove that {0:?}: {1:?}",
longer_fr, shorter_fr) as &dyn Value))])
});
} else { ; }
};debug!(
383 "Unreported region error: can't prove that {:?}: {:?}",
384 longer_fr, shorter_fr
385 );
386 }
387 }
388 }
389 }
390
391 outlives_suggestion.add_suggestion(self);
393 }
394
395 fn report_erroneous_rvid_reaches_placeholder(
398 &mut self,
399 longer_fr: RegionVid,
400 error_vid: RegionVid,
401 ) {
402 use NllRegionVariableOrigin::*;
403
404 let origin_longer = self.regioncx.definitions[longer_fr].origin;
405
406 let Placeholder(placeholder) = origin_longer else {
407 ::rustc_middle::util::bug::bug_fmt(format_args!("Expected {0:?} to come from placeholder!",
longer_fr));bug!("Expected {longer_fr:?} to come from placeholder!");
408 };
409
410 let error_region = match self.regioncx.definitions[error_vid].origin {
412 FreeRegion | Existential { .. } => None,
413 Placeholder(other_placeholder) => Some(other_placeholder),
414 };
415
416 let (blame_constraint, path) =
418 self.regioncx.best_blame_constraint(longer_fr, origin_longer, error_vid);
419 let cause = blame_constraint.to_obligation_cause_from_path(&path);
420
421 self.regioncx.universe_info(placeholder.universe).report_erroneous_element(
426 self,
427 placeholder,
428 error_region,
429 cause,
430 );
431 }
432
433 pub(crate) fn report_region_error(
442 &mut self,
443 fr: RegionVid,
444 fr_origin: NllRegionVariableOrigin<'tcx>,
445 outlived_fr: RegionVid,
446 outlives_suggestion: &mut OutlivesSuggestionBuilder,
447 ) {
448 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:448",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(448u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_region_error(fr={0:?}, outlived_fr={1:?})",
fr, outlived_fr) as &dyn Value))])
});
} else { ; }
};debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
449
450 let (blame_constraint, path) =
451 self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
452 let BlameConstraint { category, span, variance_info, .. } = blame_constraint;
453
454 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:454",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(454u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_region_error: category={0:?} {1:?} {2:?}",
category, span, variance_info) as &dyn Value))])
});
} else { ; }
};debug!("report_region_error: category={:?} {:?} {:?}", category, span, variance_info);
455
456 if let (Some(f), Some(o)) =
458 (self.regioncx.to_error_region(fr), self.regioncx.to_error_region(outlived_fr))
459 {
460 let infer_err = self.infcx.err_ctxt();
461 let nice = NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), span, o, f);
462 if let Some(diag) = nice.try_report_from_nll() {
463 self.buffer_error(diag);
464 return;
465 }
466 }
467
468 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
469 self.regioncx.universal_regions().is_local_free_region(fr),
470 self.regioncx.universal_regions().is_local_free_region(outlived_fr),
471 );
472
473 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:473",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(473u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_region_error: fr_is_local={0:?} outlived_fr_is_local={1:?} category={2:?}",
fr_is_local, outlived_fr_is_local, category) as
&dyn Value))])
});
} else { ; }
};debug!(
474 "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
475 fr_is_local, outlived_fr_is_local, category
476 );
477
478 let errci = ErrorConstraintInfo { fr, outlived_fr, category, span };
479
480 let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
481 (ConstraintCategory::SolverRegionConstraint(span), _, _) => {
482 let mut d = self.dcx().struct_span_err(
483 span,
484 "unsatisfied lifetime constraint from -Zassumptions-on-binders :3",
485 );
486 d.note("meoow :c");
487 d
488 }
489 (ConstraintCategory::Return(kind), true, false)
490 if self.regioncx.is_closure_fn_mut(fr) =>
491 {
492 self.report_fnmut_error(&errci, kind)
493 }
494 (ConstraintCategory::Assignment, true, false)
495 | (ConstraintCategory::CallArgument(_), true, false) => {
496 let mut db = self.report_escaping_data_error(&errci);
497
498 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
499 outlives_suggestion.collect_constraint(fr, outlived_fr);
500
501 db
502 }
503 _ => {
504 let mut db = self.report_general_error(&errci);
505
506 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
507 outlives_suggestion.collect_constraint(fr, outlived_fr);
508
509 db
510 }
511 };
512
513 match variance_info {
514 ty::VarianceDiagInfo::None => {}
515 ty::VarianceDiagInfo::Invariant { ty, param_index } => {
516 let (desc, note) = match ty.kind() {
517 ty::RawPtr(ty, mutbl) => {
518 {
match (&*mutbl, &hir::Mutability::Mut) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(*mutbl, hir::Mutability::Mut);
519 (
520 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a mutable pointer to `{0}`", ty))
})format!("a mutable pointer to `{}`", ty),
521 "mutable pointers are invariant over their type parameter".to_string(),
522 )
523 }
524 ty::Ref(_, inner_ty, mutbl) => {
525 {
match (&*mutbl, &hir::Mutability::Mut) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(*mutbl, hir::Mutability::Mut);
526 (
527 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a mutable reference to `{0}`",
inner_ty))
})format!("a mutable reference to `{inner_ty}`"),
528 "mutable references are invariant over their type parameter"
529 .to_string(),
530 )
531 }
532 ty::Adt(adt, args) => {
533 let generic_arg = args[param_index as usize];
534 let identity_args =
535 GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
536 let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
537 let base_generic_arg = identity_args[param_index as usize];
538 let adt_desc = adt.descr();
539
540 let desc = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the type `{0}`, which makes the generic argument `{1}` invariant",
ty, generic_arg))
})format!(
541 "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
542 );
543 let note = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} `{1}` is invariant over the parameter `{2}`",
adt_desc, base_ty, base_generic_arg))
})format!(
544 "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
545 );
546 (desc, note)
547 }
548 ty::FnDef(def_id, _) => {
549 let name = self.infcx.tcx.item_name(*def_id);
550 let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
551 let desc = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the function item type defined by `{0}`",
name))
})format!("the function item type defined by `{name}`");
552 let note = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the function `{1}` is invariant over the parameter `{0}`",
identity_args[param_index as usize], name))
})format!(
553 "the function `{name}` is invariant over the parameter `{}`",
554 identity_args[param_index as usize]
555 );
556 (desc, note)
557 }
558 _ => { ::core::panicking::panic_fmt(format_args!("Unexpected type {0:?}", ty)); }panic!("Unexpected type {ty:?}"),
559 };
560 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("requirement occurs because of {0}",
desc))
})format!("requirement occurs because of {desc}",));
561 diag.note(note);
562 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
563 }
564 }
565
566 self.add_placeholder_from_predicate_note(&mut diag, &path);
567 self.add_sized_or_copy_bound_info(&mut diag, category, &path);
568
569 for constraint in &path {
570 if let ConstraintCategory::Cast { is_raw_ptr_dyn_type_cast: true, .. } =
571 constraint.category
572 {
573 diag.span_note(
574 constraint.span,
575 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("raw pointer casts of trait objects cannot extend lifetimes"))
})format!("raw pointer casts of trait objects cannot extend lifetimes"),
576 );
577 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this was previously accepted by the compiler but was changed recently"))
})format!(
578 "this was previously accepted by the compiler but was changed recently"
579 ));
580 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("see <https://github.com/rust-lang/rust/issues/141402> for more information"))
})format!(
581 "see <https://github.com/rust-lang/rust/issues/141402> for more information"
582 ));
583 }
584 }
585
586 self.buffer_error(diag);
587 }
588
589 fn report_fnmut_error(
606 &self,
607 errci: &ErrorConstraintInfo<'tcx>,
608 kind: ReturnConstraint,
609 ) -> Diag<'infcx> {
610 let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
611
612 let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
613 if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) = *output_ty.kind() {
614 output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
615 };
616
617 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:617",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(617u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_fnmut_error: output_ty={0:?}",
output_ty) as &dyn Value))])
});
} else { ; }
};debug!("report_fnmut_error: output_ty={:?}", output_ty);
618
619 let err = FnMutError {
620 span: *span,
621 ty_err: match output_ty.kind() {
622 ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
623 FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
624 }
625 _ if output_ty.contains_closure() => {
626 FnMutReturnTypeErr::ReturnClosure { span: *span }
627 }
628 _ => FnMutReturnTypeErr::ReturnRef { span: *span },
629 },
630 };
631
632 let mut diag = self.dcx().create_err(err);
633
634 if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
635 let def_id = match self.regioncx.universal_regions().defining_ty {
636 DefiningTy::Closure(def_id, _) => def_id,
637 ty => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected DefiningTy {0:?}",
ty))bug!("unexpected DefiningTy {:?}", ty),
638 };
639
640 let captured_place = &self.upvars[upvar_field.index()].place;
641 let defined_hir = match captured_place.base {
642 PlaceBase::Local(hirid) => Some(hirid),
643 PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
644 _ => None,
645 };
646
647 if let Some(def_hir) = defined_hir {
648 let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
649 let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
650 let upvar_span = upvars_map.get(&def_hir).unwrap().span;
651 diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
652 diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
653 }
654 }
655
656 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
657 diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
658 }
659
660 self.suggest_move_on_borrowing_closure(&mut diag);
661
662 diag
663 }
664
665 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("report_escaping_data_error",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(677u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["errci"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errci)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Diag<'infcx> = loop {};
return __tracing_attr_fake_return;
}
{
let ErrorConstraintInfo { span, category, .. } = errci;
let fr_name_and_span =
self.regioncx.get_var_name_and_span_for_region(self.infcx.tcx,
self.body, &self.local_names(), &self.upvars, errci.fr);
let outlived_fr_name_and_span =
self.regioncx.get_var_name_and_span_for_region(self.infcx.tcx,
self.body, &self.local_names(), &self.upvars,
errci.outlived_fr);
let escapes_from =
self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
if (fr_name_and_span.is_none() &&
outlived_fr_name_and_span.is_none()) ||
(*category == ConstraintCategory::Assignment &&
self.regioncx.universal_regions().defining_ty.is_fn_def())
|| self.regioncx.universal_regions().defining_ty.is_const()
||
(fr_name_and_span.is_none() &&
self.regioncx.universal_regions().defining_ty.is_fn_def()) {
return self.report_general_error(errci);
}
let mut diag =
borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx,
*span, escapes_from);
if let Some((Some(outlived_fr_name), outlived_fr_span)) =
outlived_fr_name_and_span {
diag.span_label(outlived_fr_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` declared here, outside of the {1} body",
outlived_fr_name, escapes_from))
}));
}
if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
diag.span_label(fr_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a reference that is only valid in the {1} body",
fr_name, escapes_from))
}));
diag.span_label(*span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` escapes the {1} body here",
fr_name, escapes_from))
}));
} else {
diag.span_label(*span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a temporary borrow escapes the {0} body here",
escapes_from))
}));
if let Some((Some(outlived_name), _)) =
outlived_fr_name_and_span {
diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is declared outside the {1}, so any data borrowed inside the {1} cannot be stored into it",
outlived_name, escapes_from))
}));
}
}
match (self.regioncx.to_error_region(errci.fr),
self.regioncx.to_error_region(errci.outlived_fr)) {
(Some(f), Some(o)) => {
self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o,
category);
let fr_region_name =
self.give_region_a_name(errci.fr).unwrap();
fr_region_name.highlight_region_name(&mut diag);
let outlived_fr_region_name =
self.give_region_a_name(errci.outlived_fr).unwrap();
outlived_fr_region_name.highlight_region_name(&mut diag);
diag.span_label(*span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}requires that `{1}` must outlive `{2}`",
category.description(), fr_region_name,
outlived_fr_region_name))
}));
}
_ => {}
}
diag
}
}
}#[instrument(level = "debug", skip(self))]
678 fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
679 let ErrorConstraintInfo { span, category, .. } = errci;
680
681 let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
682 self.infcx.tcx,
683 self.body,
684 &self.local_names(),
685 &self.upvars,
686 errci.fr,
687 );
688 let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
689 self.infcx.tcx,
690 self.body,
691 &self.local_names(),
692 &self.upvars,
693 errci.outlived_fr,
694 );
695
696 let escapes_from =
697 self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
698
699 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
702 || (*category == ConstraintCategory::Assignment
703 && self.regioncx.universal_regions().defining_ty.is_fn_def())
704 || self.regioncx.universal_regions().defining_ty.is_const()
705 || (fr_name_and_span.is_none()
706 && self.regioncx.universal_regions().defining_ty.is_fn_def())
707 {
708 return self.report_general_error(errci);
709 }
710
711 let mut diag =
712 borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
713
714 if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
715 diag.span_label(
716 outlived_fr_span,
717 format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
718 );
719 }
720
721 if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
722 diag.span_label(
723 fr_span,
724 format!(
725 "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
726 ),
727 );
728
729 diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
730 } else {
731 diag.span_label(
732 *span,
733 format!("a temporary borrow escapes the {escapes_from} body here"),
734 );
735 if let Some((Some(outlived_name), _)) = outlived_fr_name_and_span {
736 diag.help(format!(
737 "`{outlived_name}` is declared outside the {escapes_from}, \
738 so any data borrowed inside the {escapes_from} cannot be stored into it"
739 ));
740 }
741 }
742
743 match (
747 self.regioncx.to_error_region(errci.fr),
748 self.regioncx.to_error_region(errci.outlived_fr),
749 ) {
750 (Some(f), Some(o)) => {
751 self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
752
753 let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
754 fr_region_name.highlight_region_name(&mut diag);
755 let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
756 outlived_fr_region_name.highlight_region_name(&mut diag);
757
758 diag.span_label(
759 *span,
760 format!(
761 "{}requires that `{}` must outlive `{}`",
762 category.description(),
763 fr_region_name,
764 outlived_fr_region_name,
765 ),
766 );
767 }
768 _ => {}
769 }
770
771 diag
772 }
773
774 fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
790 let ErrorConstraintInfo { fr, outlived_fr, span, category, .. } = errci;
791
792 let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
793
794 let err = LifetimeOutliveErr { span: *span };
795 let mut diag = self.dcx().create_err(err);
796
797 let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
802 name: kw::UnderscoreLifetime,
803 source: RegionNameSource::Static,
804 });
805 fr_name.highlight_region_name(&mut diag);
806 let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
807 outlived_fr_name.highlight_region_name(&mut diag);
808
809 let err_category = if #[allow(non_exhaustive_omitted_patterns)] match category {
ConstraintCategory::Return(_) => true,
_ => false,
}matches!(category, ConstraintCategory::Return(_))
810 && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
811 {
812 LifetimeReturnCategoryErr::WrongReturn {
813 span: *span,
814 mir_def_name,
815 outlived_fr_name,
816 fr_name: &fr_name,
817 }
818 } else {
819 LifetimeReturnCategoryErr::ShortReturn {
820 span: *span,
821 category_desc: category.description(),
822 free_region_name: &fr_name,
823 outlived_fr_name,
824 }
825 };
826
827 diag.subdiagnostic(err_category);
828
829 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
830 self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
831 self.suggest_move_on_borrowing_closure(&mut diag);
832 self.suggest_deref_closure_return(&mut diag);
833
834 diag
835 }
836
837 fn add_static_impl_trait_suggestion(
847 &self,
848 diag: &mut Diag<'_>,
849 fr: RegionVid,
850 fr_name: RegionName,
852 outlived_fr: RegionVid,
853 ) {
854 if let (Some(f), Some(outlived_f)) =
855 (self.regioncx.to_error_region(fr), self.regioncx.to_error_region(outlived_fr))
856 {
857 if outlived_f.kind() != ty::ReStatic {
858 return;
859 }
860 let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
861 let Some(suitable_region) = suitable_region else {
862 return;
863 };
864
865 let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
866
867 let Some(param) =
868 find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
869 else {
870 return;
871 };
872
873 let lifetime =
874 if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
875
876 let arg = match param.param.pat.simple_ident() {
877 Some(simple_ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument `{0}`", simple_ident))
})format!("argument `{simple_ident}`"),
878 None => "the argument".to_string(),
879 };
880 let captures = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("captures data from {0}", arg))
})format!("captures data from {arg}");
881
882 if !fn_returns.is_empty() {
883 nice_region_error::suggest_new_region_bound(
884 self.infcx.tcx,
885 diag,
886 fn_returns,
887 lifetime.to_string(),
888 Some(arg),
889 captures,
890 Some((param.param_ty_span, param.param_ty.to_string())),
891 Some(suitable_region.scope),
892 );
893 return;
894 }
895
896 let Some((alias_tys, alias_span, lt_addition_span)) = self
897 .infcx
898 .tcx
899 .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
900 else {
901 return;
902 };
903
904 let mut spans_suggs: Vec<_> = Vec::new();
906 for alias_ty in alias_tys {
907 if alias_ty.span.desugaring_kind().is_some() {
908 continue;
910 }
911 if let TyKind::TraitObject(_, lt) = alias_ty.kind {
912 if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
913 spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
914 } else {
915 spans_suggs.push((lt.ident.span, "'a".to_string()));
916 }
917 }
918 }
919
920 if let Some(lt_addition_span) = lt_addition_span {
921 spans_suggs.push((lt_addition_span, "'a, ".to_string()));
922 } else {
923 spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
924 }
925
926 diag.multipart_suggestion(
927 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to declare that the trait object {0}, you can add a lifetime parameter `\'a` in the type alias",
captures))
})format!(
928 "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
929 ),
930 spans_suggs,
931 Applicability::MaybeIncorrect,
932 );
933 }
934 }
935
936 fn maybe_suggest_constrain_dyn_trait_impl(
937 &self,
938 diag: &mut Diag<'_>,
939 f: Region<'tcx>,
940 o: Region<'tcx>,
941 category: &ConstraintCategory<'tcx>,
942 ) {
943 if !o.is_static() {
944 return;
945 }
946
947 let tcx = self.infcx.tcx;
948
949 let ConstraintCategory::CallArgument(Some(func_ty)) = category else { return };
950 let ty::FnDef(fn_did, args) = *func_ty.kind() else { return };
951 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:951",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(951u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["fn_did", "args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&fn_did) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&args) as
&dyn Value))])
});
} else { ; }
};debug!(?fn_did, ?args);
952
953 let ty = tcx.type_of(fn_did).instantiate_identity().skip_norm_wip();
955 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:955",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(955u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ty: {0:?}, ty.kind: {1:?}",
ty, ty.kind()) as &dyn Value))])
});
} else { ; }
};debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
956 if let ty::Closure(_, _) = ty.kind() {
957 return;
958 }
959 let Ok(Some(instance)) = ty::Instance::try_resolve(
960 tcx,
961 self.infcx.typing_env(self.infcx.param_env),
962 fn_did,
963 self.infcx.resolve_vars_if_possible(args),
964 ) else {
965 return;
966 };
967
968 let Some(param) = find_param_with_region(tcx, self.mir_def_id(), f, o) else {
969 return;
970 };
971 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:971",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(971u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["param"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m) as
&dyn Value))])
});
} else { ; }
};debug!(?param);
972
973 let mut visitor = TraitObjectVisitor(FxIndexSet::default());
974 visitor.visit_ty(param.param_ty);
975
976 let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
977 tcx,
978 instance.def_id(),
979 &visitor.0,
980 ) else {
981 return;
982 };
983
984 self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
985 }
986
987 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_constrain_dyn_trait_in_impl",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(987u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["found_dids",
"ident", "self_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found_dids)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:995",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(995u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("err: {0:#?}",
err) as &dyn Value))])
});
} else { ; }
};
let mut suggested = false;
for found_did in found_dids {
let mut traits = ::alloc::vec::Vec::new();
let mut hir_v =
HirTraitObjectVisitor(&mut traits, *found_did);
hir_v.visit_ty_unambig(self_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1001",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(1001u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("trait spans found: {0:?}",
traits) as &dyn Value))])
});
} else { ; }
};
for span in &traits {
let mut multi_span: MultiSpan =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[*span])).into();
multi_span.push_span_label(*span,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this has an implicit `'static` lifetime requirement")));
multi_span.push_span_label(ident.span,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("calling this method introduces the `impl`'s `'static` requirement")));
err.subdiagnostic(RequireStaticErr::UsedImpl {
multi_span,
});
err.span_suggestion_verbose(span.shrink_to_hi(),
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider relaxing the implicit `'static` requirement")),
" + '_", Applicability::MaybeIncorrect);
suggested = true;
}
}
suggested
}
}
}#[instrument(skip(self, err), level = "debug")]
988 fn suggest_constrain_dyn_trait_in_impl(
989 &self,
990 err: &mut Diag<'_>,
991 found_dids: &FxIndexSet<DefId>,
992 ident: Ident,
993 self_ty: &hir::Ty<'_>,
994 ) -> bool {
995 debug!("err: {:#?}", err);
996 let mut suggested = false;
997 for found_did in found_dids {
998 let mut traits = vec![];
999 let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
1000 hir_v.visit_ty_unambig(self_ty);
1001 debug!("trait spans found: {:?}", traits);
1002 for span in &traits {
1003 let mut multi_span: MultiSpan = vec![*span].into();
1004 multi_span.push_span_label(
1005 *span,
1006 msg!("this has an implicit `'static` lifetime requirement"),
1007 );
1008 multi_span.push_span_label(
1009 ident.span,
1010 msg!("calling this method introduces the `impl`'s `'static` requirement"),
1011 );
1012 err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
1013 err.span_suggestion_verbose(
1014 span.shrink_to_hi(),
1015 msg!("consider relaxing the implicit `'static` requirement"),
1016 " + '_",
1017 Applicability::MaybeIncorrect,
1018 );
1019 suggested = true;
1020 }
1021 }
1022 suggested
1023 }
1024
1025 fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
1026 let (Some(sub), Some(sup)) =
1027 (self.regioncx.to_error_region(sub), self.regioncx.to_error_region(sup))
1028 else {
1029 return;
1030 };
1031
1032 let Some((ty_sub, _)) = self
1033 .infcx
1034 .tcx
1035 .is_suitable_region(self.mir_def_id(), sub)
1036 .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
1037 else {
1038 return;
1039 };
1040
1041 let Some((ty_sup, _)) = self
1042 .infcx
1043 .tcx
1044 .is_suitable_region(self.mir_def_id(), sup)
1045 .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1046 else {
1047 return;
1048 };
1049
1050 suggest_adding_lifetime_params(
1051 self.infcx.tcx,
1052 diag,
1053 self.mir_def_id(),
1054 sub,
1055 ty_sup,
1056 ty_sub,
1057 );
1058 }
1059
1060 fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1064 let tcx = self.infcx.tcx;
1065
1066 let closure_def_id = self.mir_def_id();
1068 let hir::Node::Expr(
1069 closure_expr @ hir::Expr {
1070 kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1071 },
1072 ) = tcx.hir_node_by_def_id(closure_def_id)
1073 else {
1074 return;
1075 };
1076 let ty::Closure(_, args) =
1077 *tcx.type_of(closure_def_id).instantiate_identity().skip_norm_wip().kind()
1078 else {
1079 return;
1080 };
1081 let args = args.as_closure();
1082
1083 let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1085 let hir::Node::Expr(
1086 parent_expr @ hir::Expr {
1087 kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1088 },
1089 ) = tcx.hir_node(parent_expr_id)
1090 else {
1091 return;
1092 };
1093 let typeck_results = tcx.typeck(self.mir_def_id());
1094
1095 let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1097 let mut peeled_ty = liberated_sig.output();
1098 let mut count = 0;
1099 while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1100 peeled_ty = ref_ty;
1101 count += 1;
1102 }
1103 if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1104 return;
1105 }
1106
1107 let fn_sig_kind = liberated_sig.fn_sig_kind.set_safety(hir::Safety::Safe);
1110 let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1111 tcx,
1112 ty::Binder::dummy(tcx.mk_fn_sig(
1113 liberated_sig.inputs().iter().copied(),
1114 peeled_ty,
1115 fn_sig_kind,
1116 )),
1117 );
1118 let closure_ty = Ty::new_closure(
1119 tcx,
1120 closure_def_id.to_def_id(),
1121 ty::ClosureArgs::new(
1122 tcx,
1123 ty::ClosureArgsParts {
1124 parent_args: args.parent_args(),
1125 closure_kind_ty: args.kind_ty(),
1126 tupled_upvars_ty: args.tupled_upvars_ty(),
1127 closure_sig_as_fn_ptr_ty,
1128 },
1129 )
1130 .args,
1131 );
1132
1133 let Some((closure_arg_pos, _)) =
1134 call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1135 else {
1136 return;
1137 };
1138 let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1141 return;
1142 };
1143 let Some(input_arg) = tcx
1144 .fn_sig(method_def_id)
1145 .skip_binder()
1146 .inputs()
1147 .skip_binder()
1148 .get(closure_arg_pos + 1)
1150 else {
1151 return;
1152 };
1153 let ty::Param(closure_param) = input_arg.kind() else { return };
1155
1156 let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1158 let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1159 if let ty::GenericParamDefKind::Lifetime = param.kind {
1160 tcx.lifetimes.re_erased.into()
1161 } else if param.index == 0 && param.name == kw::SelfUpper {
1162 possible_rcvr_ty.into()
1163 } else if param.index == closure_param.index {
1164 closure_ty.into()
1165 } else {
1166 self.infcx.var_for_def(parent_expr.span, param)
1167 }
1168 });
1169
1170 let preds = tcx.predicates_of(method_def_id).instantiate(tcx, args);
1171
1172 let ocx = ObligationCtxt::new(&self.infcx);
1173 ocx.register_obligations(preds.iter().map(|(pred, span)| {
1174 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1174",
"rustc_borrowck::diagnostics::region_errors",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
::tracing_core::__macro_support::Option::Some(1174u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
::tracing_core::field::FieldSet::new(&["pred"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&pred) as
&dyn Value))])
});
} else { ; }
};trace!(?pred);
1175 Obligation::misc(
1176 tcx,
1177 span,
1178 self.mir_def_id(),
1179 self.infcx.param_env,
1180 pred.skip_norm_wip(),
1181 )
1182 }));
1183
1184 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() && count > 0 {
1185 diag.span_suggestion_verbose(
1186 tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1187 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("dereference the return value"))msg!("dereference the return value"),
1188 "*".repeat(count),
1189 Applicability::MachineApplicable,
1190 );
1191 }
1192 }
1193
1194 fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1195 let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1196 let expr = &body.value.peel_blocks();
1197 let mut closure_span = None::<rustc_span::Span>;
1198 match expr.kind {
1199 hir::ExprKind::MethodCall(.., args, _) => {
1200 for arg in args {
1201 if let hir::ExprKind::Closure(hir::Closure {
1202 capture_clause: hir::CaptureBy::Ref,
1203 ..
1204 }) = arg.kind
1205 {
1206 closure_span = Some(arg.span.shrink_to_lo());
1207 break;
1208 }
1209 }
1210 }
1211 hir::ExprKind::Closure(hir::Closure {
1212 capture_clause: hir::CaptureBy::Ref,
1213 kind,
1214 ..
1215 }) => {
1216 if !#[allow(non_exhaustive_omitted_patterns)] match kind {
hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
_)) => true,
_ => false,
}matches!(
1217 kind,
1218 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1219 hir::CoroutineDesugaring::Async,
1220 _
1221 ),)
1222 ) {
1223 closure_span = Some(expr.span.shrink_to_lo());
1224 }
1225 }
1226 _ => {}
1227 }
1228 if let Some(closure_span) = closure_span {
1229 diag.span_suggestion_verbose(
1230 closure_span,
1231 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider adding 'move' keyword before the nested closure"))msg!("consider adding 'move' keyword before the nested closure"),
1232 "move ",
1233 Applicability::MaybeIncorrect,
1234 );
1235 }
1236 }
1237}