]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs
Rollup merge of #100811 - czzrr:master, r=Mark-Simulacrum
[rust.git] / compiler / rustc_infer / src / infer / error_reporting / nice_region_error / static_impl_trait.rs
1 //! Error Reporting for static impl Traits.
2
3 use crate::infer::error_reporting::nice_region_error::NiceRegionError;
4 use crate::infer::lexical_region_resolve::RegionResolutionError;
5 use crate::infer::{SubregionOrigin, TypeTrace};
6 use crate::traits::{ObligationCauseCode, UnifyReceiverContext};
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed, MultiSpan};
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::intravisit::{walk_ty, Visitor};
11 use rustc_hir::{self as hir, GenericBound, Item, ItemKind, Lifetime, LifetimeName, Node, TyKind};
12 use rustc_middle::ty::{
13     self, AssocItemContainer, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor,
14 };
15 use rustc_span::symbol::Ident;
16 use rustc_span::Span;
17
18 use std::ops::ControlFlow;
19
20 impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
21     /// Print the error message for lifetime errors when the return type is a static `impl Trait`,
22     /// `dyn Trait` or if a method call on a trait object introduces a static requirement.
23     pub(super) fn try_report_static_impl_trait(&self) -> Option<ErrorGuaranteed> {
24         debug!("try_report_static_impl_trait(error={:?})", self.error);
25         let tcx = self.tcx();
26         let (var_origin, sub_origin, sub_r, sup_origin, sup_r, spans) = match self.error.as_ref()? {
27             RegionResolutionError::SubSupConflict(
28                 _,
29                 var_origin,
30                 sub_origin,
31                 sub_r,
32                 sup_origin,
33                 sup_r,
34                 spans,
35             ) if sub_r.is_static() => (var_origin, sub_origin, sub_r, sup_origin, sup_r, spans),
36             RegionResolutionError::ConcreteFailure(
37                 SubregionOrigin::Subtype(box TypeTrace { cause, .. }),
38                 sub_r,
39                 sup_r,
40             ) if sub_r.is_static() => {
41                 // This is for an implicit `'static` requirement coming from `impl dyn Trait {}`.
42                 if let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code() {
43                     // This may have a closure and it would cause ICE
44                     // through `find_param_with_region` (#78262).
45                     let anon_reg_sup = tcx.is_suitable_region(*sup_r)?;
46                     let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.def_id);
47                     if fn_returns.is_empty() {
48                         return None;
49                     }
50
51                     let param = self.find_param_with_region(*sup_r, *sub_r)?;
52                     let lifetime = if sup_r.has_name() {
53                         format!("lifetime `{}`", sup_r)
54                     } else {
55                         "an anonymous lifetime `'_`".to_string()
56                     };
57                     let mut err = struct_span_err!(
58                         tcx.sess,
59                         cause.span,
60                         E0772,
61                         "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
62                          requirement",
63                         param
64                             .param
65                             .pat
66                             .simple_ident()
67                             .map(|s| format!("`{}`", s))
68                             .unwrap_or_else(|| "`fn` parameter".to_string()),
69                         lifetime,
70                         ctxt.assoc_item.name,
71                     );
72                     err.span_label(param.param_ty_span, &format!("this data with {}...", lifetime));
73                     err.span_label(
74                         cause.span,
75                         &format!(
76                             "...is used and required to live as long as `'static` here \
77                              because of an implicit lifetime bound on the {}",
78                             match ctxt.assoc_item.container {
79                                 AssocItemContainer::TraitContainer => {
80                                     let id = ctxt.assoc_item.container_id(tcx);
81                                     format!("`impl` of `{}`", tcx.def_path_str(id))
82                                 }
83                                 AssocItemContainer::ImplContainer => "inherent `impl`".to_string(),
84                             },
85                         ),
86                     );
87                     if self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt) {
88                         let reported = err.emit();
89                         return Some(reported);
90                     } else {
91                         err.cancel();
92                     }
93                 }
94                 return None;
95             }
96             _ => return None,
97         };
98         debug!(
99             "try_report_static_impl_trait(var={:?}, sub={:?} {:?} sup={:?} {:?})",
100             var_origin, sub_origin, sub_r, sup_origin, sup_r
101         );
102         let anon_reg_sup = tcx.is_suitable_region(*sup_r)?;
103         debug!("try_report_static_impl_trait: anon_reg_sup={:?}", anon_reg_sup);
104         let sp = var_origin.span();
105         let return_sp = sub_origin.span();
106         let param = self.find_param_with_region(*sup_r, *sub_r)?;
107         let (lifetime_name, lifetime) = if sup_r.has_name() {
108             (sup_r.to_string(), format!("lifetime `{}`", sup_r))
109         } else {
110             ("'_".to_owned(), "an anonymous lifetime `'_`".to_string())
111         };
112         let param_name = param
113             .param
114             .pat
115             .simple_ident()
116             .map(|s| format!("`{}`", s))
117             .unwrap_or_else(|| "`fn` parameter".to_string());
118         let mut err = struct_span_err!(
119             tcx.sess,
120             sp,
121             E0759,
122             "{} has {} but it needs to satisfy a `'static` lifetime requirement",
123             param_name,
124             lifetime,
125         );
126
127         let (mention_influencer, influencer_point) =
128             if sup_origin.span().overlaps(param.param_ty_span) {
129                 // Account for `async fn` like in `async-await/issues/issue-62097.rs`.
130                 // The desugaring of `async `fn`s causes `sup_origin` and `param` to point at the same
131                 // place (but with different `ctxt`, hence `overlaps` instead of `==` above).
132                 //
133                 // This avoids the following:
134                 //
135                 // LL |     pub async fn run_dummy_fn(&self) {
136                 //    |                               ^^^^^
137                 //    |                               |
138                 //    |                               this data with an anonymous lifetime `'_`...
139                 //    |                               ...is captured here...
140                 (false, sup_origin.span())
141             } else {
142                 (!sup_origin.span().overlaps(return_sp), param.param_ty_span)
143             };
144         err.span_label(influencer_point, &format!("this data with {}...", lifetime));
145
146         debug!("try_report_static_impl_trait: param_info={:?}", param);
147
148         let mut spans = spans.clone();
149
150         if mention_influencer {
151             spans.push(sup_origin.span());
152         }
153         // We dedup the spans *ignoring* expansion context.
154         spans.sort();
155         spans.dedup_by_key(|span| (span.lo(), span.hi()));
156
157         // We try to make the output have fewer overlapping spans if possible.
158         let require_msg = if spans.is_empty() {
159             "...is used and required to live as long as `'static` here"
160         } else {
161             "...and is required to live as long as `'static` here"
162         };
163         let require_span =
164             if sup_origin.span().overlaps(return_sp) { sup_origin.span() } else { return_sp };
165
166         for span in &spans {
167             err.span_label(*span, "...is used here...");
168         }
169
170         if spans.iter().any(|sp| sp.overlaps(return_sp) || *sp > return_sp) {
171             // If any of the "captured here" labels appears on the same line or after
172             // `require_span`, we put it on a note to ensure the text flows by appearing
173             // always at the end.
174             err.span_note(require_span, require_msg);
175         } else {
176             // We don't need a note, it's already at the end, it can be shown as a `span_label`.
177             err.span_label(require_span, require_msg);
178         }
179
180         if let SubregionOrigin::RelateParamBound(_, _, Some(bound)) = sub_origin {
181             err.span_note(*bound, "`'static` lifetime requirement introduced by this bound");
182         }
183         if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = sub_origin {
184             if let ObligationCauseCode::ReturnValue(hir_id)
185             | ObligationCauseCode::BlockTailExpression(hir_id) = cause.code()
186             {
187                 let parent_id = tcx.hir().get_parent_item(*hir_id);
188                 let parent_id = tcx.hir().local_def_id_to_hir_id(parent_id);
189                 if let Some(fn_decl) = tcx.hir().fn_decl_by_hir_id(parent_id) {
190                     let mut span: MultiSpan = fn_decl.output.span().into();
191                     let mut add_label = true;
192                     if let hir::FnRetTy::Return(ty) = fn_decl.output {
193                         let mut v = StaticLifetimeVisitor(vec![], tcx.hir());
194                         v.visit_ty(ty);
195                         if !v.0.is_empty() {
196                             span = v.0.clone().into();
197                             for sp in v.0 {
198                                 span.push_span_label(sp, "`'static` requirement introduced here");
199                             }
200                             add_label = false;
201                         }
202                     }
203                     if add_label {
204                         span.push_span_label(
205                             fn_decl.output.span(),
206                             "requirement introduced by this return type",
207                         );
208                     }
209                     span.push_span_label(cause.span, "because of this returned expression");
210                     err.span_note(
211                         span,
212                         "`'static` lifetime requirement introduced by the return type",
213                     );
214                 }
215             }
216         }
217
218         let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.def_id);
219
220         let mut override_error_code = None;
221         if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sup_origin
222             && let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code()
223             // Handle case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a
224             // `'static` lifetime when called as a method on a binding: `bar.qux()`.
225             && self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt)
226         {
227             override_error_code = Some(ctxt.assoc_item.name);
228         }
229
230         if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sub_origin
231             && let code = match cause.code() {
232                 ObligationCauseCode::MatchImpl(parent, ..) => parent.code(),
233                 _ => cause.code(),
234             }
235             && let (&ObligationCauseCode::ItemObligation(item_def_id) | &ObligationCauseCode::ExprItemObligation(item_def_id, ..), None) = (code, override_error_code)
236         {
237             // Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static`
238             // lifetime as above, but called using a fully-qualified path to the method:
239             // `Foo::qux(bar)`.
240             let mut v = TraitObjectVisitor(FxHashSet::default());
241             v.visit_ty(param.param_ty);
242             if let Some((ident, self_ty)) =
243                 self.get_impl_ident_and_self_ty_from_trait(item_def_id, &v.0)
244                 && self.suggest_constrain_dyn_trait_in_impl(&mut err, &v.0, ident, self_ty)
245             {
246                 override_error_code = Some(ident.name);
247             }
248         }
249         if let (Some(ident), true) = (override_error_code, fn_returns.is_empty()) {
250             // Provide a more targeted error code and description.
251             err.code(rustc_errors::error_code!(E0772));
252             err.set_primary_message(&format!(
253                 "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
254                 requirement",
255                 param_name, lifetime, ident,
256             ));
257         }
258
259         let arg = match param.param.pat.simple_ident() {
260             Some(simple_ident) => format!("argument `{}`", simple_ident),
261             None => "the argument".to_string(),
262         };
263         let captures = format!("captures data from {}", arg);
264         suggest_new_region_bound(
265             tcx,
266             &mut err,
267             fn_returns,
268             lifetime_name,
269             Some(arg),
270             captures,
271             Some((param.param_ty_span, param.param_ty.to_string())),
272         );
273
274         let reported = err.emit();
275         Some(reported)
276     }
277 }
278
279 pub fn suggest_new_region_bound(
280     tcx: TyCtxt<'_>,
281     err: &mut Diagnostic,
282     fn_returns: Vec<&rustc_hir::Ty<'_>>,
283     lifetime_name: String,
284     arg: Option<String>,
285     captures: String,
286     param: Option<(Span, String)>,
287 ) {
288     debug!("try_report_static_impl_trait: fn_return={:?}", fn_returns);
289     // FIXME: account for the need of parens in `&(dyn Trait + '_)`
290     let consider = "consider changing the";
291     let declare = "to declare that the";
292     let explicit = format!("you can add an explicit `{}` lifetime bound", lifetime_name);
293     let explicit_static =
294         arg.map(|arg| format!("explicit `'static` bound to the lifetime of {}", arg));
295     let add_static_bound = "alternatively, add an explicit `'static` bound to this reference";
296     let plus_lt = format!(" + {}", lifetime_name);
297     for fn_return in fn_returns {
298         if fn_return.span.desugaring_kind().is_some() {
299             // Skip `async` desugaring `impl Future`.
300             continue;
301         }
302         match fn_return.kind {
303             TyKind::OpaqueDef(item_id, _) => {
304                 let item = tcx.hir().item(item_id);
305                 let ItemKind::OpaqueTy(opaque) = &item.kind else {
306                     return;
307                 };
308
309                 if let Some(span) = opaque
310                     .bounds
311                     .iter()
312                     .filter_map(|arg| match arg {
313                         GenericBound::Outlives(Lifetime {
314                             name: LifetimeName::Static,
315                             span,
316                             ..
317                         }) => Some(*span),
318                         _ => None,
319                     })
320                     .next()
321                 {
322                     if let Some(explicit_static) = &explicit_static {
323                         err.span_suggestion_verbose(
324                             span,
325                             &format!("{} `impl Trait`'s {}", consider, explicit_static),
326                             &lifetime_name,
327                             Applicability::MaybeIncorrect,
328                         );
329                     }
330                     if let Some((param_span, param_ty)) = param.clone() {
331                         err.span_suggestion_verbose(
332                             param_span,
333                             add_static_bound,
334                             param_ty,
335                             Applicability::MaybeIncorrect,
336                         );
337                     }
338                 } else if opaque
339                     .bounds
340                     .iter()
341                     .filter_map(|arg| match arg {
342                         GenericBound::Outlives(Lifetime { name, span, .. })
343                             if name.ident().to_string() == lifetime_name =>
344                         {
345                             Some(*span)
346                         }
347                         _ => None,
348                     })
349                     .next()
350                     .is_some()
351                 {
352                 } else {
353                     err.span_suggestion_verbose(
354                         fn_return.span.shrink_to_hi(),
355                         &format!(
356                             "{declare} `impl Trait` {captures}, {explicit}",
357                             declare = declare,
358                             captures = captures,
359                             explicit = explicit,
360                         ),
361                         &plus_lt,
362                         Applicability::MaybeIncorrect,
363                     );
364                 }
365             }
366             TyKind::TraitObject(_, lt, _) => match lt.name {
367                 LifetimeName::ImplicitObjectLifetimeDefault => {
368                     err.span_suggestion_verbose(
369                         fn_return.span.shrink_to_hi(),
370                         &format!(
371                             "{declare} trait object {captures}, {explicit}",
372                             declare = declare,
373                             captures = captures,
374                             explicit = explicit,
375                         ),
376                         &plus_lt,
377                         Applicability::MaybeIncorrect,
378                     );
379                 }
380                 name if name.ident().to_string() != lifetime_name => {
381                     // With this check we avoid suggesting redundant bounds. This
382                     // would happen if there are nested impl/dyn traits and only
383                     // one of them has the bound we'd suggest already there, like
384                     // in `impl Foo<X = dyn Bar> + '_`.
385                     if let Some(explicit_static) = &explicit_static {
386                         err.span_suggestion_verbose(
387                             lt.span,
388                             &format!("{} trait object's {}", consider, explicit_static),
389                             &lifetime_name,
390                             Applicability::MaybeIncorrect,
391                         );
392                     }
393                     if let Some((param_span, param_ty)) = param.clone() {
394                         err.span_suggestion_verbose(
395                             param_span,
396                             add_static_bound,
397                             param_ty,
398                             Applicability::MaybeIncorrect,
399                         );
400                     }
401                 }
402                 _ => {}
403             },
404             _ => {}
405         }
406     }
407 }
408
409 impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
410     fn get_impl_ident_and_self_ty_from_trait(
411         &self,
412         def_id: DefId,
413         trait_objects: &FxHashSet<DefId>,
414     ) -> Option<(Ident, &'tcx hir::Ty<'tcx>)> {
415         let tcx = self.tcx();
416         match tcx.hir().get_if_local(def_id) {
417             Some(Node::ImplItem(impl_item)) => {
418                 match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id())) {
419                     Some(Node::Item(Item {
420                         kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
421                         ..
422                     })) => Some((impl_item.ident, self_ty)),
423                     _ => None,
424                 }
425             }
426             Some(Node::TraitItem(trait_item)) => {
427                 let trait_did = tcx.hir().get_parent_item(trait_item.hir_id());
428                 match tcx.hir().find_by_def_id(trait_did) {
429                     Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => {
430                         // The method being called is defined in the `trait`, but the `'static`
431                         // obligation comes from the `impl`. Find that `impl` so that we can point
432                         // at it in the suggestion.
433                         let trait_did = trait_did.to_def_id();
434                         match tcx
435                             .hir()
436                             .trait_impls(trait_did)
437                             .iter()
438                             .filter_map(|&impl_did| {
439                                 match tcx.hir().get_if_local(impl_did.to_def_id()) {
440                                     Some(Node::Item(Item {
441                                         kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
442                                         ..
443                                     })) if trait_objects.iter().all(|did| {
444                                         // FIXME: we should check `self_ty` against the receiver
445                                         // type in the `UnifyReceiver` context, but for now, use
446                                         // this imperfect proxy. This will fail if there are
447                                         // multiple `impl`s for the same trait like
448                                         // `impl Foo for Box<dyn Bar>` and `impl Foo for dyn Bar`.
449                                         // In that case, only the first one will get suggestions.
450                                         let mut traits = vec![];
451                                         let mut hir_v = HirTraitObjectVisitor(&mut traits, *did);
452                                         hir_v.visit_ty(self_ty);
453                                         !traits.is_empty()
454                                     }) =>
455                                     {
456                                         Some(self_ty)
457                                     }
458                                     _ => None,
459                                 }
460                             })
461                             .next()
462                         {
463                             Some(self_ty) => Some((trait_item.ident, self_ty)),
464                             _ => None,
465                         }
466                     }
467                     _ => None,
468                 }
469             }
470             _ => None,
471         }
472     }
473
474     /// When we call a method coming from an `impl Foo for dyn Bar`, `dyn Bar` introduces a default
475     /// `'static` obligation. Suggest relaxing that implicit bound.
476     fn find_impl_on_dyn_trait(
477         &self,
478         err: &mut Diagnostic,
479         ty: Ty<'_>,
480         ctxt: &UnifyReceiverContext<'tcx>,
481     ) -> bool {
482         let tcx = self.tcx();
483
484         // Find the method being called.
485         let Ok(Some(instance)) = ty::Instance::resolve(
486             tcx,
487             ctxt.param_env,
488             ctxt.assoc_item.def_id,
489             self.infcx.resolve_vars_if_possible(ctxt.substs),
490         ) else {
491             return false;
492         };
493
494         let mut v = TraitObjectVisitor(FxHashSet::default());
495         v.visit_ty(ty);
496
497         // Get the `Ident` of the method being called and the corresponding `impl` (to point at
498         // `Bar` in `impl Foo for dyn Bar {}` and the definition of the method being called).
499         let Some((ident, self_ty)) = self.get_impl_ident_and_self_ty_from_trait(instance.def_id(), &v.0) else {
500             return false;
501         };
502
503         // Find the trait object types in the argument, so we point at *only* the trait object.
504         self.suggest_constrain_dyn_trait_in_impl(err, &v.0, ident, self_ty)
505     }
506
507     fn suggest_constrain_dyn_trait_in_impl(
508         &self,
509         err: &mut Diagnostic,
510         found_dids: &FxHashSet<DefId>,
511         ident: Ident,
512         self_ty: &hir::Ty<'_>,
513     ) -> bool {
514         let mut suggested = false;
515         for found_did in found_dids {
516             let mut traits = vec![];
517             let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
518             hir_v.visit_ty(&self_ty);
519             for span in &traits {
520                 let mut multi_span: MultiSpan = vec![*span].into();
521                 multi_span
522                     .push_span_label(*span, "this has an implicit `'static` lifetime requirement");
523                 multi_span.push_span_label(
524                     ident.span,
525                     "calling this method introduces the `impl`'s 'static` requirement",
526                 );
527                 err.span_note(multi_span, "the used `impl` has a `'static` requirement");
528                 err.span_suggestion_verbose(
529                     span.shrink_to_hi(),
530                     "consider relaxing the implicit `'static` requirement",
531                     " + '_",
532                     Applicability::MaybeIncorrect,
533                 );
534                 suggested = true;
535             }
536         }
537         suggested
538     }
539 }
540
541 /// Collect all the trait objects in a type that could have received an implicit `'static` lifetime.
542 pub struct TraitObjectVisitor(pub FxHashSet<DefId>);
543
544 impl<'tcx> TypeVisitor<'tcx> for TraitObjectVisitor {
545     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
546         match t.kind() {
547             ty::Dynamic(preds, re) if re.is_static() => {
548                 if let Some(def_id) = preds.principal_def_id() {
549                     self.0.insert(def_id);
550                 }
551                 ControlFlow::CONTINUE
552             }
553             _ => t.super_visit_with(self),
554         }
555     }
556 }
557
558 /// Collect all `hir::Ty<'_>` `Span`s for trait objects with an implicit lifetime.
559 pub struct HirTraitObjectVisitor<'a>(pub &'a mut Vec<Span>, pub DefId);
560
561 impl<'a, 'tcx> Visitor<'tcx> for HirTraitObjectVisitor<'a> {
562     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
563         if let TyKind::TraitObject(
564             poly_trait_refs,
565             Lifetime { name: LifetimeName::ImplicitObjectLifetimeDefault, .. },
566             _,
567         ) = t.kind
568         {
569             for ptr in poly_trait_refs {
570                 if Some(self.1) == ptr.trait_ref.trait_def_id() {
571                     self.0.push(ptr.span);
572                 }
573             }
574         }
575         walk_ty(self, t);
576     }
577 }