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::error_reporting::infer::region::unexpected_hidden_region_diagnostic;
27use rustc_trait_selection::infer::InferCtxtExt;
28use rustc_trait_selection::traits::{Obligation, ObligationCtxt};
29use tracing::{debug, instrument, trace};
30
31use super::{OutlivesSuggestionBuilder, RegionName, RegionNameSource};
32use crate::nll::ConstraintDescription;
33use crate::region_infer::values::RegionElement;
34use crate::region_infer::{BlameConstraint, TypeTest};
35use crate::session_diagnostics::{
36 FnMutError, FnMutReturnTypeErr, GenericDoesNotLiveLongEnough, LifetimeOutliveErr,
37 LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote,
38};
39use crate::universal_regions::DefiningTy;
40use crate::{MirBorrowckCtxt, borrowck_errors, fluent_generated as fluent};
41
42impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
43 fn description(&self) -> &'static str {
44 match self {
46 ConstraintCategory::Assignment => "assignment ",
47 ConstraintCategory::Return(_) => "returning this value ",
48 ConstraintCategory::Yield => "yielding this value ",
49 ConstraintCategory::UseAsConst => "using this value as a constant ",
50 ConstraintCategory::UseAsStatic => "using this value as a static ",
51 ConstraintCategory::Cast { is_implicit_coercion: false, .. } => "cast ",
52 ConstraintCategory::Cast { is_implicit_coercion: true, .. } => "coercion ",
53 ConstraintCategory::CallArgument(_) => "argument ",
54 ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => "generic argument ",
55 ConstraintCategory::TypeAnnotation(_) => "type annotation ",
56 ConstraintCategory::SizedBound => "proving this value is `Sized` ",
57 ConstraintCategory::CopyBound => "copying this value ",
58 ConstraintCategory::OpaqueType => "opaque type ",
59 ConstraintCategory::ClosureUpvar(_) => "closure capture ",
60 ConstraintCategory::Usage => "this usage ",
61 ConstraintCategory::Predicate(_)
62 | ConstraintCategory::Boring
63 | ConstraintCategory::BoringNoLocation
64 | ConstraintCategory::Internal
65 | ConstraintCategory::IllegalUniverse => "",
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(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(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(Clone, Debug)]
104pub(crate) enum RegionErrorKind<'tcx> {
105 TypeTestError { type_test: TypeTest<'tcx> },
107
108 UnexpectedHiddenRegion {
110 span: Span,
112 hidden_ty: Ty<'tcx>,
114 key: ty::OpaqueTypeKey<'tcx>,
116 member_region: ty::Region<'tcx>,
118 },
119
120 BoundUniversalRegionError {
122 longer_fr: RegionVid,
124 error_element: RegionElement,
126 placeholder: ty::PlaceholderRegion,
128 },
129
130 RegionError {
132 fr_origin: NllRegionVariableOrigin,
134 longer_fr: RegionVid,
136 shorter_fr: RegionVid,
138 is_reported: bool,
141 },
142}
143
144#[derive(Clone, Debug)]
146pub(crate) struct ErrorConstraintInfo<'tcx> {
147 pub(super) fr: RegionVid,
149 pub(super) outlived_fr: RegionVid,
150
151 pub(super) category: ConstraintCategory<'tcx>,
153 pub(super) span: Span,
154}
155
156impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
157 pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
164 self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
165 }
166
167 pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
170 if self.regioncx.universal_regions().is_universal_region(r) {
171 Some(r)
172 } else {
173 let upper_bound = self.regioncx.approx_universal_upper_bound(r);
176
177 if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
178 self.to_error_region_vid(upper_bound)
179 } else {
180 None
181 }
182 }
183 }
184
185 fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
187 where
188 T: TypeFoldable<TyCtxt<'tcx>>,
189 {
190 fold_regions(tcx, ty, |region, _| match region.kind() {
191 ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
192 _ => region,
193 })
194 }
195
196 fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
198 if let Some(r) = self.to_error_region(fr)
199 && let ty::ReLateParam(late_param) = r.kind()
200 && let ty::LateParamRegionKind::ClosureEnv = late_param.kind
201 && let DefiningTy::Closure(_, args) = self.regioncx.universal_regions().defining_ty
202 {
203 return args.as_closure().kind() == ty::ClosureKind::FnMut;
204 }
205
206 false
207 }
208
209 #[allow(rustc::diagnostic_outside_of_impl)]
213 fn suggest_static_lifetime_for_gat_from_hrtb(
214 &self,
215 diag: &mut Diag<'_>,
216 lower_bound: RegionVid,
217 ) {
218 let tcx = self.infcx.tcx;
219
220 let gat_id_and_generics = self
222 .regioncx
223 .placeholders_contained_in(lower_bound)
224 .map(|placeholder| {
225 if let Some(id) = placeholder.bound.kind.get_id()
226 && let Some(placeholder_id) = id.as_local()
227 && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
228 && let Some(generics_impl) =
229 tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
230 {
231 Some((gat_hir_id, generics_impl))
232 } else {
233 None
234 }
235 })
236 .collect::<Vec<_>>();
237 debug!(?gat_id_and_generics);
238
239 let mut hrtb_bounds = vec![];
243 gat_id_and_generics.iter().flatten().for_each(|&(gat_hir_id, generics)| {
244 for pred in generics.predicates {
245 let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) =
246 pred.kind
247 else {
248 continue;
249 };
250 if bound_generic_params
251 .iter()
252 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
253 .is_some()
254 {
255 for bound in *bounds {
256 hrtb_bounds.push(bound);
257 }
258 } else {
259 for bound in *bounds {
260 if let Trait(trait_bound) = bound {
261 if trait_bound
262 .bound_generic_params
263 .iter()
264 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
265 .is_some()
266 {
267 hrtb_bounds.push(bound);
268 return;
269 }
270 }
271 }
272 }
273 }
274 });
275 debug!(?hrtb_bounds);
276
277 let mut suggestions = vec![];
278 hrtb_bounds.iter().for_each(|bound| {
279 let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }) = bound else {
280 return;
281 };
282 diag.span_note(*trait_span, fluent::borrowck_limitations_implies_static);
283 let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
284 else {
285 return;
286 };
287 let Def(_, trait_res_defid) = trait_ref.path.res else {
288 return;
289 };
290 debug!(?generics_fn);
291 generics_fn.predicates.iter().for_each(|predicate| {
292 let BoundPredicate(WhereBoundPredicate { bounded_ty, bounds, .. }) = predicate.kind
293 else {
294 return;
295 };
296 bounds.iter().for_each(|bd| {
297 if let Trait(PolyTraitRef { trait_ref: tr_ref, .. }) = bd
298 && let Def(_, res_defid) = tr_ref.path.res
299 && res_defid == trait_res_defid && let TyKind::Path(Resolved(_, path)) = bounded_ty.kind
301 && let Def(_, defid) = path.res
302 && generics_fn.params
303 .iter()
304 .rfind(|param| param.def_id.to_def_id() == defid)
305 .is_some()
306 {
307 suggestions.push((predicate.span.shrink_to_hi(), " + 'static".to_string()));
308 }
309 });
310 });
311 });
312 if suggestions.len() > 0 {
313 suggestions.dedup();
314 diag.multipart_suggestion_verbose(
315 fluent::borrowck_restrict_to_static,
316 suggestions,
317 Applicability::MaybeIncorrect,
318 );
319 }
320 }
321
322 pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
324 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
328 let mut last_unexpected_hidden_region: Option<(Span, Ty<'_>, ty::OpaqueTypeKey<'tcx>)> =
329 None;
330
331 for (nll_error, _) in nll_errors.into_iter() {
332 match nll_error {
333 RegionErrorKind::TypeTestError { type_test } => {
334 let lower_bound_region = self.to_error_region(type_test.lower_bound);
337
338 let type_test_span = type_test.span;
339
340 if let Some(lower_bound_region) = lower_bound_region {
341 let generic_ty = self.name_regions(
342 self.infcx.tcx,
343 type_test.generic_kind.to_ty(self.infcx.tcx),
344 );
345 let origin =
346 SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
347 self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
348 self.body.source.def_id().expect_local(),
349 type_test_span,
350 Some(origin),
351 self.name_regions(self.infcx.tcx, type_test.generic_kind),
352 lower_bound_region,
353 ));
354 } else {
355 let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
365 kind: type_test.generic_kind.to_string(),
366 span: type_test_span,
367 });
368
369 self.suggest_static_lifetime_for_gat_from_hrtb(
373 &mut diag,
374 type_test.lower_bound,
375 );
376
377 self.buffer_error(diag);
378 }
379 }
380
381 RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, key, member_region } => {
382 let named_ty =
383 self.regioncx.name_regions_for_member_constraint(self.infcx.tcx, hidden_ty);
384 let named_key =
385 self.regioncx.name_regions_for_member_constraint(self.infcx.tcx, key);
386 let named_region = self
387 .regioncx
388 .name_regions_for_member_constraint(self.infcx.tcx, member_region);
389 let diag = unexpected_hidden_region_diagnostic(
390 self.infcx,
391 self.mir_def_id(),
392 span,
393 named_ty,
394 named_region,
395 named_key,
396 );
397 if last_unexpected_hidden_region != Some((span, named_ty, named_key)) {
398 self.buffer_error(diag);
399 last_unexpected_hidden_region = Some((span, named_ty, named_key));
400 } else {
401 diag.delay_as_bug();
402 }
403 }
404
405 RegionErrorKind::BoundUniversalRegionError {
406 longer_fr,
407 placeholder,
408 error_element,
409 } => {
410 let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
411
412 let (_, cause) = self.regioncx.find_outlives_blame_span(
414 longer_fr,
415 NllRegionVariableOrigin::Placeholder(placeholder),
416 error_vid,
417 );
418
419 let universe = placeholder.universe;
420 let universe_info = self.regioncx.universe_info(universe);
421
422 universe_info.report_erroneous_element(self, placeholder, error_element, cause);
423 }
424
425 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
426 if is_reported {
427 self.report_region_error(
428 longer_fr,
429 fr_origin,
430 shorter_fr,
431 &mut outlives_suggestion,
432 );
433 } else {
434 debug!(
441 "Unreported region error: can't prove that {:?}: {:?}",
442 longer_fr, shorter_fr
443 );
444 }
445 }
446 }
447 }
448
449 outlives_suggestion.add_suggestion(self);
451 }
452
453 #[allow(rustc::diagnostic_outside_of_impl)]
463 #[allow(rustc::untranslatable_diagnostic)]
464 pub(crate) fn report_region_error(
465 &mut self,
466 fr: RegionVid,
467 fr_origin: NllRegionVariableOrigin,
468 outlived_fr: RegionVid,
469 outlives_suggestion: &mut OutlivesSuggestionBuilder,
470 ) {
471 debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
472
473 let (blame_constraint, path) = self.regioncx.best_blame_constraint(fr, fr_origin, |r| {
474 self.regioncx.provides_universal_region(r, fr, outlived_fr)
475 });
476 let BlameConstraint { category, cause, variance_info, .. } = blame_constraint;
477
478 debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
479
480 if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
482 let infer_err = self.infcx.err_ctxt();
483 let nice =
484 NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), cause.span, o, f);
485 if let Some(diag) = nice.try_report_from_nll() {
486 self.buffer_error(diag);
487 return;
488 }
489 }
490
491 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
492 self.regioncx.universal_regions().is_local_free_region(fr),
493 self.regioncx.universal_regions().is_local_free_region(outlived_fr),
494 );
495
496 debug!(
497 "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
498 fr_is_local, outlived_fr_is_local, category
499 );
500
501 let errci = ErrorConstraintInfo { fr, outlived_fr, category, span: cause.span };
502
503 let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
504 (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
505 self.report_fnmut_error(&errci, kind)
506 }
507 (ConstraintCategory::Assignment, true, false)
508 | (ConstraintCategory::CallArgument(_), true, false) => {
509 let mut db = self.report_escaping_data_error(&errci);
510
511 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
512 outlives_suggestion.collect_constraint(fr, outlived_fr);
513
514 db
515 }
516 _ => {
517 let mut db = self.report_general_error(&errci);
518
519 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
520 outlives_suggestion.collect_constraint(fr, outlived_fr);
521
522 db
523 }
524 };
525
526 match variance_info {
527 ty::VarianceDiagInfo::None => {}
528 ty::VarianceDiagInfo::Invariant { ty, param_index } => {
529 let (desc, note) = match ty.kind() {
530 ty::RawPtr(ty, mutbl) => {
531 assert_eq!(*mutbl, hir::Mutability::Mut);
532 (
533 format!("a mutable pointer to `{}`", ty),
534 "mutable pointers are invariant over their type parameter".to_string(),
535 )
536 }
537 ty::Ref(_, inner_ty, mutbl) => {
538 assert_eq!(*mutbl, hir::Mutability::Mut);
539 (
540 format!("a mutable reference to `{inner_ty}`"),
541 "mutable references are invariant over their type parameter"
542 .to_string(),
543 )
544 }
545 ty::Adt(adt, args) => {
546 let generic_arg = args[param_index as usize];
547 let identity_args =
548 GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
549 let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
550 let base_generic_arg = identity_args[param_index as usize];
551 let adt_desc = adt.descr();
552
553 let desc = format!(
554 "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
555 );
556 let note = format!(
557 "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
558 );
559 (desc, note)
560 }
561 ty::FnDef(def_id, _) => {
562 let name = self.infcx.tcx.item_name(*def_id);
563 let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
564 let desc = format!("a function pointer to `{name}`");
565 let note = format!(
566 "the function `{name}` is invariant over the parameter `{}`",
567 identity_args[param_index as usize]
568 );
569 (desc, note)
570 }
571 _ => panic!("Unexpected type {ty:?}"),
572 };
573 diag.note(format!("requirement occurs because of {desc}",));
574 diag.note(note);
575 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
576 }
577 }
578
579 self.add_placeholder_from_predicate_note(&mut diag, &path);
580 self.add_sized_or_copy_bound_info(&mut diag, category, &path);
581
582 self.buffer_error(diag);
583 }
584
585 #[allow(rustc::diagnostic_outside_of_impl)] fn report_fnmut_error(
603 &self,
604 errci: &ErrorConstraintInfo<'tcx>,
605 kind: ReturnConstraint,
606 ) -> Diag<'infcx> {
607 let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
608
609 let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
610 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *output_ty.kind() {
611 output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity()
612 };
613
614 debug!("report_fnmut_error: output_ty={:?}", output_ty);
615
616 let err = FnMutError {
617 span: *span,
618 ty_err: match output_ty.kind() {
619 ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
620 FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
621 }
622 _ if output_ty.contains_closure() => {
623 FnMutReturnTypeErr::ReturnClosure { span: *span }
624 }
625 _ => FnMutReturnTypeErr::ReturnRef { span: *span },
626 },
627 };
628
629 let mut diag = self.dcx().create_err(err);
630
631 if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
632 let def_id = match self.regioncx.universal_regions().defining_ty {
633 DefiningTy::Closure(def_id, _) => def_id,
634 ty => bug!("unexpected DefiningTy {:?}", ty),
635 };
636
637 let captured_place = &self.upvars[upvar_field.index()].place;
638 let defined_hir = match captured_place.base {
639 PlaceBase::Local(hirid) => Some(hirid),
640 PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
641 _ => None,
642 };
643
644 if let Some(def_hir) = defined_hir {
645 let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
646 let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
647 let upvar_span = upvars_map.get(&def_hir).unwrap().span;
648 diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
649 diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
650 }
651 }
652
653 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
654 diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
655 }
656
657 self.suggest_move_on_borrowing_closure(&mut diag);
658
659 diag
660 }
661
662 #[instrument(level = "debug", skip(self))]
675 fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
676 let ErrorConstraintInfo { span, category, .. } = errci;
677
678 let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
679 self.infcx.tcx,
680 self.body,
681 &self.local_names(),
682 &self.upvars,
683 errci.fr,
684 );
685 let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
686 self.infcx.tcx,
687 self.body,
688 &self.local_names(),
689 &self.upvars,
690 errci.outlived_fr,
691 );
692
693 let escapes_from =
694 self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
695
696 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
699 || (*category == ConstraintCategory::Assignment
700 && self.regioncx.universal_regions().defining_ty.is_fn_def())
701 || self.regioncx.universal_regions().defining_ty.is_const()
702 {
703 return self.report_general_error(errci);
704 }
705
706 let mut diag =
707 borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
708
709 if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
710 #[allow(rustc::diagnostic_outside_of_impl)]
712 #[allow(rustc::untranslatable_diagnostic)]
713 diag.span_label(
714 outlived_fr_span,
715 format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
716 );
717 }
718
719 #[allow(rustc::diagnostic_outside_of_impl)]
721 #[allow(rustc::untranslatable_diagnostic)]
722 if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
723 diag.span_label(
724 fr_span,
725 format!(
726 "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
727 ),
728 );
729
730 diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
731 }
732
733 match (self.to_error_region(errci.fr), self.to_error_region(errci.outlived_fr)) {
737 (Some(f), Some(o)) => {
738 self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
739
740 let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
741 fr_region_name.highlight_region_name(&mut diag);
742 let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
743 outlived_fr_region_name.highlight_region_name(&mut diag);
744
745 #[allow(rustc::diagnostic_outside_of_impl)]
747 #[allow(rustc::untranslatable_diagnostic)]
748 diag.span_label(
749 *span,
750 format!(
751 "{}requires that `{}` must outlive `{}`",
752 category.description(),
753 fr_region_name,
754 outlived_fr_region_name,
755 ),
756 );
757 }
758 _ => {}
759 }
760
761 diag
762 }
763
764 #[allow(rustc::diagnostic_outside_of_impl)] fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
781 let ErrorConstraintInfo { fr, outlived_fr, span, category, .. } = errci;
782
783 let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
784
785 let err = LifetimeOutliveErr { span: *span };
786 let mut diag = self.dcx().create_err(err);
787
788 let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
793 name: kw::UnderscoreLifetime,
794 source: RegionNameSource::Static,
795 });
796 fr_name.highlight_region_name(&mut diag);
797 let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
798 outlived_fr_name.highlight_region_name(&mut diag);
799
800 let err_category = if matches!(category, ConstraintCategory::Return(_))
801 && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
802 {
803 LifetimeReturnCategoryErr::WrongReturn {
804 span: *span,
805 mir_def_name,
806 outlived_fr_name,
807 fr_name: &fr_name,
808 }
809 } else {
810 LifetimeReturnCategoryErr::ShortReturn {
811 span: *span,
812 category_desc: category.description(),
813 free_region_name: &fr_name,
814 outlived_fr_name,
815 }
816 };
817
818 diag.subdiagnostic(err_category);
819
820 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
821 self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
822 self.suggest_move_on_borrowing_closure(&mut diag);
823 self.suggest_deref_closure_return(&mut diag);
824
825 diag
826 }
827
828 #[allow(rustc::diagnostic_outside_of_impl)]
838 #[allow(rustc::untranslatable_diagnostic)] fn add_static_impl_trait_suggestion(
840 &self,
841 diag: &mut Diag<'_>,
842 fr: RegionVid,
843 fr_name: RegionName,
845 outlived_fr: RegionVid,
846 ) {
847 if let (Some(f), Some(outlived_f)) =
848 (self.to_error_region(fr), self.to_error_region(outlived_fr))
849 {
850 if outlived_f.kind() != ty::ReStatic {
851 return;
852 }
853 let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
854 let Some(suitable_region) = suitable_region else {
855 return;
856 };
857
858 let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
859
860 let param = if let Some(param) =
861 find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
862 {
863 param
864 } else {
865 return;
866 };
867
868 let lifetime =
869 if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
870
871 let arg = match param.param.pat.simple_ident() {
872 Some(simple_ident) => format!("argument `{simple_ident}`"),
873 None => "the argument".to_string(),
874 };
875 let captures = format!("captures data from {arg}");
876
877 if !fn_returns.is_empty() {
878 nice_region_error::suggest_new_region_bound(
879 self.infcx.tcx,
880 diag,
881 fn_returns,
882 lifetime.to_string(),
883 Some(arg),
884 captures,
885 Some((param.param_ty_span, param.param_ty.to_string())),
886 Some(suitable_region.scope),
887 );
888 return;
889 }
890
891 let Some((alias_tys, alias_span, lt_addition_span)) = self
892 .infcx
893 .tcx
894 .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
895 else {
896 return;
897 };
898
899 let mut spans_suggs: Vec<_> = Vec::new();
901 for alias_ty in alias_tys {
902 if alias_ty.span.desugaring_kind().is_some() {
903 }
905 if let TyKind::TraitObject(_, lt) = alias_ty.kind {
906 if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
907 spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
908 } else {
909 spans_suggs.push((lt.ident.span, "'a".to_string()));
910 }
911 }
912 }
913
914 if let Some(lt_addition_span) = lt_addition_span {
915 spans_suggs.push((lt_addition_span, "'a, ".to_string()));
916 } else {
917 spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
918 }
919
920 diag.multipart_suggestion_verbose(
921 format!(
922 "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
923 ),
924 spans_suggs,
925 Applicability::MaybeIncorrect,
926 );
927 }
928 }
929
930 fn maybe_suggest_constrain_dyn_trait_impl(
931 &self,
932 diag: &mut Diag<'_>,
933 f: Region<'tcx>,
934 o: Region<'tcx>,
935 category: &ConstraintCategory<'tcx>,
936 ) {
937 if !o.is_static() {
938 return;
939 }
940
941 let tcx = self.infcx.tcx;
942
943 let instance = if let ConstraintCategory::CallArgument(Some(func_ty)) = category {
944 let (fn_did, args) = match func_ty.kind() {
945 ty::FnDef(fn_did, args) => (fn_did, args),
946 _ => return,
947 };
948 debug!(?fn_did, ?args);
949
950 let ty = tcx.type_of(fn_did).instantiate_identity();
952 debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
953 if let ty::Closure(_, _) = ty.kind() {
954 return;
955 }
956
957 if let Ok(Some(instance)) = ty::Instance::try_resolve(
958 tcx,
959 self.infcx.typing_env(self.infcx.param_env),
960 *fn_did,
961 self.infcx.resolve_vars_if_possible(args),
962 ) {
963 instance
964 } else {
965 return;
966 }
967 } else {
968 return;
969 };
970
971 let param = match find_param_with_region(tcx, self.mir_def_id(), f, o) {
972 Some(param) => param,
973 None => return,
974 };
975 debug!(?param);
976
977 let mut visitor = TraitObjectVisitor(FxIndexSet::default());
978 visitor.visit_ty(param.param_ty);
979
980 let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
981 tcx,
982 instance.def_id(),
983 &visitor.0,
984 ) else {
985 return;
986 };
987
988 self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
989 }
990
991 #[allow(rustc::diagnostic_outside_of_impl)]
992 #[instrument(skip(self, err), level = "debug")]
993 fn suggest_constrain_dyn_trait_in_impl(
994 &self,
995 err: &mut Diag<'_>,
996 found_dids: &FxIndexSet<DefId>,
997 ident: Ident,
998 self_ty: &hir::Ty<'_>,
999 ) -> bool {
1000 debug!("err: {:#?}", err);
1001 let mut suggested = false;
1002 for found_did in found_dids {
1003 let mut traits = vec![];
1004 let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
1005 hir_v.visit_ty_unambig(self_ty);
1006 debug!("trait spans found: {:?}", traits);
1007 for span in &traits {
1008 let mut multi_span: MultiSpan = vec![*span].into();
1009 multi_span.push_span_label(*span, fluent::borrowck_implicit_static);
1010 multi_span.push_span_label(ident.span, fluent::borrowck_implicit_static_introduced);
1011 err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
1012 err.span_suggestion_verbose(
1013 span.shrink_to_hi(),
1014 fluent::borrowck_implicit_static_relax,
1015 " + '_",
1016 Applicability::MaybeIncorrect,
1017 );
1018 suggested = true;
1019 }
1020 }
1021 suggested
1022 }
1023
1024 fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
1025 let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
1026 return;
1027 };
1028
1029 let Some((ty_sub, _)) = self
1030 .infcx
1031 .tcx
1032 .is_suitable_region(self.mir_def_id(), sub)
1033 .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
1034 else {
1035 return;
1036 };
1037
1038 let Some((ty_sup, _)) = self
1039 .infcx
1040 .tcx
1041 .is_suitable_region(self.mir_def_id(), sup)
1042 .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1043 else {
1044 return;
1045 };
1046
1047 suggest_adding_lifetime_params(
1048 self.infcx.tcx,
1049 diag,
1050 self.mir_def_id(),
1051 sub,
1052 ty_sup,
1053 ty_sub,
1054 );
1055 }
1056
1057 #[allow(rustc::diagnostic_outside_of_impl)]
1058 fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1062 let tcx = self.infcx.tcx;
1063
1064 let closure_def_id = self.mir_def_id();
1066 let hir::Node::Expr(
1067 closure_expr @ hir::Expr {
1068 kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1069 },
1070 ) = tcx.hir_node_by_def_id(closure_def_id)
1071 else {
1072 return;
1073 };
1074 let ty::Closure(_, args) = *tcx.type_of(closure_def_id).instantiate_identity().kind()
1075 else {
1076 return;
1077 };
1078 let args = args.as_closure();
1079
1080 let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1082 let hir::Node::Expr(
1083 parent_expr @ hir::Expr {
1084 kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1085 },
1086 ) = tcx.hir_node(parent_expr_id)
1087 else {
1088 return;
1089 };
1090 let typeck_results = tcx.typeck(self.mir_def_id());
1091
1092 let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1094 let mut peeled_ty = liberated_sig.output();
1095 let mut count = 0;
1096 while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1097 peeled_ty = ref_ty;
1098 count += 1;
1099 }
1100 if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1101 return;
1102 }
1103
1104 let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1106 tcx,
1107 ty::Binder::dummy(tcx.mk_fn_sig(
1108 liberated_sig.inputs().iter().copied(),
1109 peeled_ty,
1110 liberated_sig.c_variadic,
1111 hir::Safety::Safe,
1112 rustc_abi::ExternAbi::Rust,
1113 )),
1114 );
1115 let closure_ty = Ty::new_closure(
1116 tcx,
1117 closure_def_id.to_def_id(),
1118 ty::ClosureArgs::new(
1119 tcx,
1120 ty::ClosureArgsParts {
1121 parent_args: args.parent_args(),
1122 closure_kind_ty: args.kind_ty(),
1123 tupled_upvars_ty: args.tupled_upvars_ty(),
1124 closure_sig_as_fn_ptr_ty,
1125 },
1126 )
1127 .args,
1128 );
1129
1130 let Some((closure_arg_pos, _)) =
1131 call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1132 else {
1133 return;
1134 };
1135 let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1138 return;
1139 };
1140 let Some(input_arg) = tcx
1141 .fn_sig(method_def_id)
1142 .skip_binder()
1143 .inputs()
1144 .skip_binder()
1145 .get(closure_arg_pos + 1)
1147 else {
1148 return;
1149 };
1150 let ty::Param(closure_param) = input_arg.kind() else { return };
1152
1153 let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1155 let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1156 if let ty::GenericParamDefKind::Lifetime = param.kind {
1157 tcx.lifetimes.re_erased.into()
1158 } else if param.index == 0 && param.name == kw::SelfUpper {
1159 possible_rcvr_ty.into()
1160 } else if param.index == closure_param.index {
1161 closure_ty.into()
1162 } else {
1163 self.infcx.var_for_def(parent_expr.span, param)
1164 }
1165 });
1166
1167 let preds = tcx.predicates_of(method_def_id).instantiate(tcx, args);
1168
1169 let ocx = ObligationCtxt::new(&self.infcx);
1170 ocx.register_obligations(preds.iter().map(|(pred, span)| {
1171 trace!(?pred);
1172 Obligation::misc(tcx, span, self.mir_def_id(), self.infcx.param_env, pred)
1173 }));
1174
1175 if ocx.select_all_or_error().is_empty() && count > 0 {
1176 diag.span_suggestion_verbose(
1177 tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1178 fluent::borrowck_dereference_suggestion,
1179 "*".repeat(count),
1180 Applicability::MachineApplicable,
1181 );
1182 }
1183 }
1184
1185 #[allow(rustc::diagnostic_outside_of_impl)]
1186 fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1187 let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1188 let expr = &body.value.peel_blocks();
1189 let mut closure_span = None::<rustc_span::Span>;
1190 match expr.kind {
1191 hir::ExprKind::MethodCall(.., args, _) => {
1192 for arg in args {
1193 if let hir::ExprKind::Closure(hir::Closure {
1194 capture_clause: hir::CaptureBy::Ref,
1195 ..
1196 }) = arg.kind
1197 {
1198 closure_span = Some(arg.span.shrink_to_lo());
1199 break;
1200 }
1201 }
1202 }
1203 hir::ExprKind::Closure(hir::Closure {
1204 capture_clause: hir::CaptureBy::Ref,
1205 kind,
1206 ..
1207 }) => {
1208 if !matches!(
1209 kind,
1210 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1211 hir::CoroutineDesugaring::Async,
1212 _
1213 ),)
1214 ) {
1215 closure_span = Some(expr.span.shrink_to_lo());
1216 }
1217 }
1218 _ => {}
1219 }
1220 if let Some(closure_span) = closure_span {
1221 diag.span_suggestion_verbose(
1222 closure_span,
1223 fluent::borrowck_move_closure_suggestion,
1224 "move ",
1225 Applicability::MaybeIncorrect,
1226 );
1227 }
1228 }
1229}