1use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
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::{OutlivesSuggestionBuilder, RegionName, RegionNameSource};
31use crate::nll::ConstraintDescription;
32use crate::region_infer::values::RegionElement;
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, fluent_generated as fluent};
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::Predicate(_)
61 | ConstraintCategory::Boring
62 | ConstraintCategory::BoringNoLocation
63 | ConstraintCategory::Internal
64 | ConstraintCategory::OutlivesUnnameablePlaceholder(..) => "",
65 }
66 }
67}
68
69pub(crate) struct RegionErrors<'tcx>(Vec<(RegionErrorKind<'tcx>, ErrorGuaranteed)>, TyCtxt<'tcx>);
75
76impl<'tcx> RegionErrors<'tcx> {
77 pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
78 Self(vec![], tcx)
79 }
80 #[track_caller]
81 pub(crate) fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) {
82 let val = val.into();
83 let guar = self.1.sess.dcx().delayed_bug(format!("{val:?}"));
84 self.0.push((val, guar));
85 }
86 pub(crate) fn is_empty(&self) -> bool {
87 self.0.is_empty()
88 }
89 pub(crate) fn into_iter(
90 self,
91 ) -> impl Iterator<Item = (RegionErrorKind<'tcx>, ErrorGuaranteed)> {
92 self.0.into_iter()
93 }
94}
95
96impl std::fmt::Debug for RegionErrors<'_> {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_tuple("RegionErrors").field(&self.0).finish()
99 }
100}
101
102#[derive(Clone, Debug)]
103pub(crate) enum RegionErrorKind<'tcx> {
104 TypeTestError { type_test: TypeTest<'tcx> },
106
107 BoundUniversalRegionError {
109 longer_fr: RegionVid,
111 error_element: RegionElement,
113 placeholder: ty::PlaceholderRegion,
115 },
116
117 RegionError {
119 fr_origin: NllRegionVariableOrigin,
121 longer_fr: RegionVid,
123 shorter_fr: RegionVid,
125 is_reported: bool,
128 },
129}
130
131#[derive(Clone, Debug)]
133pub(crate) struct ErrorConstraintInfo<'tcx> {
134 pub(super) fr: RegionVid,
136 pub(super) outlived_fr: RegionVid,
137
138 pub(super) category: ConstraintCategory<'tcx>,
140 pub(super) span: Span,
141}
142
143impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
144 pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
151 self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
152 }
153
154 pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
157 if self.regioncx.universal_regions().is_universal_region(r) {
158 Some(r)
159 } else {
160 let upper_bound = self.regioncx.approx_universal_upper_bound(r);
163
164 if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
165 self.to_error_region_vid(upper_bound)
166 } else {
167 None
168 }
169 }
170 }
171
172 fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
174 where
175 T: TypeFoldable<TyCtxt<'tcx>>,
176 {
177 fold_regions(tcx, ty, |region, _| match region.kind() {
178 ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
179 _ => region,
180 })
181 }
182
183 fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
185 if let Some(r) = self.to_error_region(fr)
186 && let ty::ReLateParam(late_param) = r.kind()
187 && let ty::LateParamRegionKind::ClosureEnv = late_param.kind
188 && let DefiningTy::Closure(_, args) = self.regioncx.universal_regions().defining_ty
189 {
190 return args.as_closure().kind() == ty::ClosureKind::FnMut;
191 }
192
193 false
194 }
195
196 #[allow(rustc::diagnostic_outside_of_impl)]
200 fn suggest_static_lifetime_for_gat_from_hrtb(
201 &self,
202 diag: &mut Diag<'_>,
203 lower_bound: RegionVid,
204 ) {
205 let tcx = self.infcx.tcx;
206
207 let gat_id_and_generics = self
209 .regioncx
210 .placeholders_contained_in(lower_bound)
211 .map(|placeholder| {
212 if let Some(id) = placeholder.bound.kind.get_id()
213 && let Some(placeholder_id) = id.as_local()
214 && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
215 && let Some(generics_impl) =
216 tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
217 {
218 Some((gat_hir_id, generics_impl))
219 } else {
220 None
221 }
222 })
223 .collect::<Vec<_>>();
224 debug!(?gat_id_and_generics);
225
226 let mut hrtb_bounds = vec![];
230 gat_id_and_generics.iter().flatten().for_each(|&(gat_hir_id, generics)| {
231 for pred in generics.predicates {
232 let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) =
233 pred.kind
234 else {
235 continue;
236 };
237 if bound_generic_params
238 .iter()
239 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
240 .is_some()
241 {
242 for bound in *bounds {
243 hrtb_bounds.push(bound);
244 }
245 } else {
246 for bound in *bounds {
247 if let Trait(trait_bound) = bound {
248 if trait_bound
249 .bound_generic_params
250 .iter()
251 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
252 .is_some()
253 {
254 hrtb_bounds.push(bound);
255 return;
256 }
257 }
258 }
259 }
260 }
261 });
262 debug!(?hrtb_bounds);
263
264 let mut suggestions = vec![];
265 hrtb_bounds.iter().for_each(|bound| {
266 let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }) = bound else {
267 return;
268 };
269 diag.span_note(*trait_span, fluent::borrowck_limitations_implies_static);
270 let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
271 else {
272 return;
273 };
274 let Def(_, trait_res_defid) = trait_ref.path.res else {
275 return;
276 };
277 debug!(?generics_fn);
278 generics_fn.predicates.iter().for_each(|predicate| {
279 let BoundPredicate(WhereBoundPredicate { bounded_ty, bounds, .. }) = predicate.kind
280 else {
281 return;
282 };
283 bounds.iter().for_each(|bd| {
284 if let Trait(PolyTraitRef { trait_ref: tr_ref, .. }) = bd
285 && let Def(_, res_defid) = tr_ref.path.res
286 && res_defid == trait_res_defid && let TyKind::Path(Resolved(_, path)) = bounded_ty.kind
288 && let Def(_, defid) = path.res
289 && generics_fn.params
290 .iter()
291 .rfind(|param| param.def_id.to_def_id() == defid)
292 .is_some()
293 {
294 suggestions.push((predicate.span.shrink_to_hi(), " + 'static".to_string()));
295 }
296 });
297 });
298 });
299 if suggestions.len() > 0 {
300 suggestions.dedup();
301 diag.multipart_suggestion_verbose(
302 fluent::borrowck_restrict_to_static,
303 suggestions,
304 Applicability::MaybeIncorrect,
305 );
306 }
307 }
308
309 pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
311 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
314 for (nll_error, _) in nll_errors.into_iter() {
315 match nll_error {
316 RegionErrorKind::TypeTestError { type_test } => {
317 let lower_bound_region = self.to_error_region(type_test.lower_bound);
320
321 let type_test_span = type_test.span;
322
323 if let Some(lower_bound_region) = lower_bound_region {
324 let generic_ty = self.name_regions(
325 self.infcx.tcx,
326 type_test.generic_kind.to_ty(self.infcx.tcx),
327 );
328 let origin =
329 SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
330 self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
331 self.body.source.def_id().expect_local(),
332 type_test_span,
333 Some(origin),
334 self.name_regions(self.infcx.tcx, type_test.generic_kind),
335 lower_bound_region,
336 ));
337 } else {
338 let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
348 kind: type_test.generic_kind.to_string(),
349 span: type_test_span,
350 });
351
352 self.suggest_static_lifetime_for_gat_from_hrtb(
356 &mut diag,
357 type_test.lower_bound,
358 );
359
360 self.buffer_error(diag);
361 }
362 }
363
364 RegionErrorKind::BoundUniversalRegionError {
365 longer_fr,
366 placeholder,
367 error_element,
368 } => {
369 let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
370
371 let cause = self
373 .regioncx
374 .best_blame_constraint(
375 longer_fr,
376 NllRegionVariableOrigin::Placeholder(placeholder),
377 error_vid,
378 )
379 .0
380 .cause;
381
382 let universe = placeholder.universe;
383 let universe_info = self.regioncx.universe_info(universe);
384
385 universe_info.report_erroneous_element(self, placeholder, error_element, cause);
386 }
387
388 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
389 if is_reported {
390 self.report_region_error(
391 longer_fr,
392 fr_origin,
393 shorter_fr,
394 &mut outlives_suggestion,
395 );
396 } else {
397 debug!(
404 "Unreported region error: can't prove that {:?}: {:?}",
405 longer_fr, shorter_fr
406 );
407 }
408 }
409 }
410 }
411
412 outlives_suggestion.add_suggestion(self);
414 }
415
416 #[allow(rustc::diagnostic_outside_of_impl)]
426 #[allow(rustc::untranslatable_diagnostic)]
427 pub(crate) fn report_region_error(
428 &mut self,
429 fr: RegionVid,
430 fr_origin: NllRegionVariableOrigin,
431 outlived_fr: RegionVid,
432 outlives_suggestion: &mut OutlivesSuggestionBuilder,
433 ) {
434 debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
435
436 let (blame_constraint, path) =
437 self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
438 let BlameConstraint { category, cause, variance_info, .. } = blame_constraint;
439
440 debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
441
442 if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
444 let infer_err = self.infcx.err_ctxt();
445 let nice =
446 NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), cause.span, o, f);
447 if let Some(diag) = nice.try_report_from_nll() {
448 self.buffer_error(diag);
449 return;
450 }
451 }
452
453 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
454 self.regioncx.universal_regions().is_local_free_region(fr),
455 self.regioncx.universal_regions().is_local_free_region(outlived_fr),
456 );
457
458 debug!(
459 "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
460 fr_is_local, outlived_fr_is_local, category
461 );
462
463 let errci = ErrorConstraintInfo { fr, outlived_fr, category, span: cause.span };
464
465 let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
466 (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
467 self.report_fnmut_error(&errci, kind)
468 }
469 (ConstraintCategory::Assignment, true, false)
470 | (ConstraintCategory::CallArgument(_), true, false) => {
471 let mut db = self.report_escaping_data_error(&errci);
472
473 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
474 outlives_suggestion.collect_constraint(fr, outlived_fr);
475
476 db
477 }
478 _ => {
479 let mut db = self.report_general_error(&errci);
480
481 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
482 outlives_suggestion.collect_constraint(fr, outlived_fr);
483
484 db
485 }
486 };
487
488 match variance_info {
489 ty::VarianceDiagInfo::None => {}
490 ty::VarianceDiagInfo::Invariant { ty, param_index } => {
491 let (desc, note) = match ty.kind() {
492 ty::RawPtr(ty, mutbl) => {
493 assert_eq!(*mutbl, hir::Mutability::Mut);
494 (
495 format!("a mutable pointer to `{}`", ty),
496 "mutable pointers are invariant over their type parameter".to_string(),
497 )
498 }
499 ty::Ref(_, inner_ty, mutbl) => {
500 assert_eq!(*mutbl, hir::Mutability::Mut);
501 (
502 format!("a mutable reference to `{inner_ty}`"),
503 "mutable references are invariant over their type parameter"
504 .to_string(),
505 )
506 }
507 ty::Adt(adt, args) => {
508 let generic_arg = args[param_index as usize];
509 let identity_args =
510 GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
511 let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
512 let base_generic_arg = identity_args[param_index as usize];
513 let adt_desc = adt.descr();
514
515 let desc = format!(
516 "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
517 );
518 let note = format!(
519 "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
520 );
521 (desc, note)
522 }
523 ty::FnDef(def_id, _) => {
524 let name = self.infcx.tcx.item_name(*def_id);
525 let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
526 let desc = format!("a function pointer to `{name}`");
527 let note = format!(
528 "the function `{name}` is invariant over the parameter `{}`",
529 identity_args[param_index as usize]
530 );
531 (desc, note)
532 }
533 _ => panic!("Unexpected type {ty:?}"),
534 };
535 diag.note(format!("requirement occurs because of {desc}",));
536 diag.note(note);
537 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
538 }
539 }
540
541 self.add_placeholder_from_predicate_note(&mut diag, &path);
542 self.add_sized_or_copy_bound_info(&mut diag, category, &path);
543
544 self.buffer_error(diag);
545 }
546
547 #[allow(rustc::diagnostic_outside_of_impl)] fn report_fnmut_error(
565 &self,
566 errci: &ErrorConstraintInfo<'tcx>,
567 kind: ReturnConstraint,
568 ) -> Diag<'infcx> {
569 let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
570
571 let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
572 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *output_ty.kind() {
573 output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity()
574 };
575
576 debug!("report_fnmut_error: output_ty={:?}", output_ty);
577
578 let err = FnMutError {
579 span: *span,
580 ty_err: match output_ty.kind() {
581 ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
582 FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
583 }
584 _ if output_ty.contains_closure() => {
585 FnMutReturnTypeErr::ReturnClosure { span: *span }
586 }
587 _ => FnMutReturnTypeErr::ReturnRef { span: *span },
588 },
589 };
590
591 let mut diag = self.dcx().create_err(err);
592
593 if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
594 let def_id = match self.regioncx.universal_regions().defining_ty {
595 DefiningTy::Closure(def_id, _) => def_id,
596 ty => bug!("unexpected DefiningTy {:?}", ty),
597 };
598
599 let captured_place = &self.upvars[upvar_field.index()].place;
600 let defined_hir = match captured_place.base {
601 PlaceBase::Local(hirid) => Some(hirid),
602 PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
603 _ => None,
604 };
605
606 if let Some(def_hir) = defined_hir {
607 let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
608 let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
609 let upvar_span = upvars_map.get(&def_hir).unwrap().span;
610 diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
611 diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
612 }
613 }
614
615 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
616 diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
617 }
618
619 self.suggest_move_on_borrowing_closure(&mut diag);
620
621 diag
622 }
623
624 #[instrument(level = "debug", skip(self))]
637 fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
638 let ErrorConstraintInfo { span, category, .. } = errci;
639
640 let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
641 self.infcx.tcx,
642 self.body,
643 &self.local_names(),
644 &self.upvars,
645 errci.fr,
646 );
647 let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
648 self.infcx.tcx,
649 self.body,
650 &self.local_names(),
651 &self.upvars,
652 errci.outlived_fr,
653 );
654
655 let escapes_from =
656 self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
657
658 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
661 || (*category == ConstraintCategory::Assignment
662 && self.regioncx.universal_regions().defining_ty.is_fn_def())
663 || self.regioncx.universal_regions().defining_ty.is_const()
664 {
665 return self.report_general_error(errci);
666 }
667
668 let mut diag =
669 borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
670
671 if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
672 #[allow(rustc::diagnostic_outside_of_impl)]
674 #[allow(rustc::untranslatable_diagnostic)]
675 diag.span_label(
676 outlived_fr_span,
677 format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
678 );
679 }
680
681 #[allow(rustc::diagnostic_outside_of_impl)]
683 #[allow(rustc::untranslatable_diagnostic)]
684 if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
685 diag.span_label(
686 fr_span,
687 format!(
688 "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
689 ),
690 );
691
692 diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
693 } else {
694 diag.span_label(
695 *span,
696 format!("a temporary borrow escapes the {escapes_from} body here"),
697 );
698 if let Some((Some(outlived_name), _)) = outlived_fr_name_and_span {
699 diag.help(format!(
700 "`{outlived_name}` is declared outside the {escapes_from}, \
701 so any data borrowed inside the {escapes_from} cannot be stored into it"
702 ));
703 }
704 }
705
706 match (self.to_error_region(errci.fr), self.to_error_region(errci.outlived_fr)) {
710 (Some(f), Some(o)) => {
711 self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
712
713 let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
714 fr_region_name.highlight_region_name(&mut diag);
715 let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
716 outlived_fr_region_name.highlight_region_name(&mut diag);
717
718 #[allow(rustc::diagnostic_outside_of_impl)]
720 #[allow(rustc::untranslatable_diagnostic)]
721 diag.span_label(
722 *span,
723 format!(
724 "{}requires that `{}` must outlive `{}`",
725 category.description(),
726 fr_region_name,
727 outlived_fr_region_name,
728 ),
729 );
730 }
731 _ => {}
732 }
733
734 diag
735 }
736
737 #[allow(rustc::diagnostic_outside_of_impl)] fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
754 let ErrorConstraintInfo { fr, outlived_fr, span, category, .. } = errci;
755
756 let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
757
758 let err = LifetimeOutliveErr { span: *span };
759 let mut diag = self.dcx().create_err(err);
760
761 let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
766 name: kw::UnderscoreLifetime,
767 source: RegionNameSource::Static,
768 });
769 fr_name.highlight_region_name(&mut diag);
770 let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
771 outlived_fr_name.highlight_region_name(&mut diag);
772
773 let err_category = if matches!(category, ConstraintCategory::Return(_))
774 && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
775 {
776 LifetimeReturnCategoryErr::WrongReturn {
777 span: *span,
778 mir_def_name,
779 outlived_fr_name,
780 fr_name: &fr_name,
781 }
782 } else {
783 LifetimeReturnCategoryErr::ShortReturn {
784 span: *span,
785 category_desc: category.description(),
786 free_region_name: &fr_name,
787 outlived_fr_name,
788 }
789 };
790
791 diag.subdiagnostic(err_category);
792
793 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
794 self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
795 self.suggest_move_on_borrowing_closure(&mut diag);
796 self.suggest_deref_closure_return(&mut diag);
797
798 diag
799 }
800
801 #[allow(rustc::diagnostic_outside_of_impl)]
811 #[allow(rustc::untranslatable_diagnostic)] fn add_static_impl_trait_suggestion(
813 &self,
814 diag: &mut Diag<'_>,
815 fr: RegionVid,
816 fr_name: RegionName,
818 outlived_fr: RegionVid,
819 ) {
820 if let (Some(f), Some(outlived_f)) =
821 (self.to_error_region(fr), self.to_error_region(outlived_fr))
822 {
823 if outlived_f.kind() != ty::ReStatic {
824 return;
825 }
826 let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
827 let Some(suitable_region) = suitable_region else {
828 return;
829 };
830
831 let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
832
833 let param = if let Some(param) =
834 find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
835 {
836 param
837 } else {
838 return;
839 };
840
841 let lifetime =
842 if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
843
844 let arg = match param.param.pat.simple_ident() {
845 Some(simple_ident) => format!("argument `{simple_ident}`"),
846 None => "the argument".to_string(),
847 };
848 let captures = format!("captures data from {arg}");
849
850 if !fn_returns.is_empty() {
851 nice_region_error::suggest_new_region_bound(
852 self.infcx.tcx,
853 diag,
854 fn_returns,
855 lifetime.to_string(),
856 Some(arg),
857 captures,
858 Some((param.param_ty_span, param.param_ty.to_string())),
859 Some(suitable_region.scope),
860 );
861 return;
862 }
863
864 let Some((alias_tys, alias_span, lt_addition_span)) = self
865 .infcx
866 .tcx
867 .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
868 else {
869 return;
870 };
871
872 let mut spans_suggs: Vec<_> = Vec::new();
874 for alias_ty in alias_tys {
875 if alias_ty.span.desugaring_kind().is_some() {
876 }
878 if let TyKind::TraitObject(_, lt) = alias_ty.kind {
879 if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
880 spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
881 } else {
882 spans_suggs.push((lt.ident.span, "'a".to_string()));
883 }
884 }
885 }
886
887 if let Some(lt_addition_span) = lt_addition_span {
888 spans_suggs.push((lt_addition_span, "'a, ".to_string()));
889 } else {
890 spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
891 }
892
893 diag.multipart_suggestion_verbose(
894 format!(
895 "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
896 ),
897 spans_suggs,
898 Applicability::MaybeIncorrect,
899 );
900 }
901 }
902
903 fn maybe_suggest_constrain_dyn_trait_impl(
904 &self,
905 diag: &mut Diag<'_>,
906 f: Region<'tcx>,
907 o: Region<'tcx>,
908 category: &ConstraintCategory<'tcx>,
909 ) {
910 if !o.is_static() {
911 return;
912 }
913
914 let tcx = self.infcx.tcx;
915
916 let instance = if let ConstraintCategory::CallArgument(Some(func_ty)) = category {
917 let (fn_did, args) = match func_ty.kind() {
918 ty::FnDef(fn_did, args) => (fn_did, args),
919 _ => return,
920 };
921 debug!(?fn_did, ?args);
922
923 let ty = tcx.type_of(fn_did).instantiate_identity();
925 debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
926 if let ty::Closure(_, _) = ty.kind() {
927 return;
928 }
929
930 if let Ok(Some(instance)) = ty::Instance::try_resolve(
931 tcx,
932 self.infcx.typing_env(self.infcx.param_env),
933 *fn_did,
934 self.infcx.resolve_vars_if_possible(args),
935 ) {
936 instance
937 } else {
938 return;
939 }
940 } else {
941 return;
942 };
943
944 let param = match find_param_with_region(tcx, self.mir_def_id(), f, o) {
945 Some(param) => param,
946 None => return,
947 };
948 debug!(?param);
949
950 let mut visitor = TraitObjectVisitor(FxIndexSet::default());
951 visitor.visit_ty(param.param_ty);
952
953 let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
954 tcx,
955 instance.def_id(),
956 &visitor.0,
957 ) else {
958 return;
959 };
960
961 self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
962 }
963
964 #[allow(rustc::diagnostic_outside_of_impl)]
965 #[instrument(skip(self, err), level = "debug")]
966 fn suggest_constrain_dyn_trait_in_impl(
967 &self,
968 err: &mut Diag<'_>,
969 found_dids: &FxIndexSet<DefId>,
970 ident: Ident,
971 self_ty: &hir::Ty<'_>,
972 ) -> bool {
973 debug!("err: {:#?}", err);
974 let mut suggested = false;
975 for found_did in found_dids {
976 let mut traits = vec![];
977 let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
978 hir_v.visit_ty_unambig(self_ty);
979 debug!("trait spans found: {:?}", traits);
980 for span in &traits {
981 let mut multi_span: MultiSpan = vec![*span].into();
982 multi_span.push_span_label(*span, fluent::borrowck_implicit_static);
983 multi_span.push_span_label(ident.span, fluent::borrowck_implicit_static_introduced);
984 err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
985 err.span_suggestion_verbose(
986 span.shrink_to_hi(),
987 fluent::borrowck_implicit_static_relax,
988 " + '_",
989 Applicability::MaybeIncorrect,
990 );
991 suggested = true;
992 }
993 }
994 suggested
995 }
996
997 fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
998 let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
999 return;
1000 };
1001
1002 let Some((ty_sub, _)) = self
1003 .infcx
1004 .tcx
1005 .is_suitable_region(self.mir_def_id(), sub)
1006 .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
1007 else {
1008 return;
1009 };
1010
1011 let Some((ty_sup, _)) = self
1012 .infcx
1013 .tcx
1014 .is_suitable_region(self.mir_def_id(), sup)
1015 .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1016 else {
1017 return;
1018 };
1019
1020 suggest_adding_lifetime_params(
1021 self.infcx.tcx,
1022 diag,
1023 self.mir_def_id(),
1024 sub,
1025 ty_sup,
1026 ty_sub,
1027 );
1028 }
1029
1030 #[allow(rustc::diagnostic_outside_of_impl)]
1031 fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1035 let tcx = self.infcx.tcx;
1036
1037 let closure_def_id = self.mir_def_id();
1039 let hir::Node::Expr(
1040 closure_expr @ hir::Expr {
1041 kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1042 },
1043 ) = tcx.hir_node_by_def_id(closure_def_id)
1044 else {
1045 return;
1046 };
1047 let ty::Closure(_, args) = *tcx.type_of(closure_def_id).instantiate_identity().kind()
1048 else {
1049 return;
1050 };
1051 let args = args.as_closure();
1052
1053 let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1055 let hir::Node::Expr(
1056 parent_expr @ hir::Expr {
1057 kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1058 },
1059 ) = tcx.hir_node(parent_expr_id)
1060 else {
1061 return;
1062 };
1063 let typeck_results = tcx.typeck(self.mir_def_id());
1064
1065 let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1067 let mut peeled_ty = liberated_sig.output();
1068 let mut count = 0;
1069 while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1070 peeled_ty = ref_ty;
1071 count += 1;
1072 }
1073 if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1074 return;
1075 }
1076
1077 let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1079 tcx,
1080 ty::Binder::dummy(tcx.mk_fn_sig(
1081 liberated_sig.inputs().iter().copied(),
1082 peeled_ty,
1083 liberated_sig.c_variadic,
1084 hir::Safety::Safe,
1085 rustc_abi::ExternAbi::Rust,
1086 )),
1087 );
1088 let closure_ty = Ty::new_closure(
1089 tcx,
1090 closure_def_id.to_def_id(),
1091 ty::ClosureArgs::new(
1092 tcx,
1093 ty::ClosureArgsParts {
1094 parent_args: args.parent_args(),
1095 closure_kind_ty: args.kind_ty(),
1096 tupled_upvars_ty: args.tupled_upvars_ty(),
1097 closure_sig_as_fn_ptr_ty,
1098 },
1099 )
1100 .args,
1101 );
1102
1103 let Some((closure_arg_pos, _)) =
1104 call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1105 else {
1106 return;
1107 };
1108 let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1111 return;
1112 };
1113 let Some(input_arg) = tcx
1114 .fn_sig(method_def_id)
1115 .skip_binder()
1116 .inputs()
1117 .skip_binder()
1118 .get(closure_arg_pos + 1)
1120 else {
1121 return;
1122 };
1123 let ty::Param(closure_param) = input_arg.kind() else { return };
1125
1126 let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1128 let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1129 if let ty::GenericParamDefKind::Lifetime = param.kind {
1130 tcx.lifetimes.re_erased.into()
1131 } else if param.index == 0 && param.name == kw::SelfUpper {
1132 possible_rcvr_ty.into()
1133 } else if param.index == closure_param.index {
1134 closure_ty.into()
1135 } else {
1136 self.infcx.var_for_def(parent_expr.span, param)
1137 }
1138 });
1139
1140 let preds = tcx.predicates_of(method_def_id).instantiate(tcx, args);
1141
1142 let ocx = ObligationCtxt::new(&self.infcx);
1143 ocx.register_obligations(preds.iter().map(|(pred, span)| {
1144 trace!(?pred);
1145 Obligation::misc(tcx, span, self.mir_def_id(), self.infcx.param_env, pred)
1146 }));
1147
1148 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() && count > 0 {
1149 diag.span_suggestion_verbose(
1150 tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1151 fluent::borrowck_dereference_suggestion,
1152 "*".repeat(count),
1153 Applicability::MachineApplicable,
1154 );
1155 }
1156 }
1157
1158 #[allow(rustc::diagnostic_outside_of_impl)]
1159 fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1160 let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1161 let expr = &body.value.peel_blocks();
1162 let mut closure_span = None::<rustc_span::Span>;
1163 match expr.kind {
1164 hir::ExprKind::MethodCall(.., args, _) => {
1165 for arg in args {
1166 if let hir::ExprKind::Closure(hir::Closure {
1167 capture_clause: hir::CaptureBy::Ref,
1168 ..
1169 }) = arg.kind
1170 {
1171 closure_span = Some(arg.span.shrink_to_lo());
1172 break;
1173 }
1174 }
1175 }
1176 hir::ExprKind::Closure(hir::Closure {
1177 capture_clause: hir::CaptureBy::Ref,
1178 kind,
1179 ..
1180 }) => {
1181 if !matches!(
1182 kind,
1183 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1184 hir::CoroutineDesugaring::Async,
1185 _
1186 ),)
1187 ) {
1188 closure_span = Some(expr.span.shrink_to_lo());
1189 }
1190 }
1191 _ => {}
1192 }
1193 if let Some(closure_span) = closure_span {
1194 diag.span_suggestion_verbose(
1195 closure_span,
1196 fluent::borrowck_move_closure_suggestion,
1197 "move ",
1198 Applicability::MaybeIncorrect,
1199 );
1200 }
1201 }
1202}