1 //! Error Reporting for static impl Traits.
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_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorReported};
8 use rustc_hir::def_id::DefId;
9 use rustc_hir::intravisit::{walk_ty, ErasedMap, NestedVisitorMap, Visitor};
11 self as hir, GenericBound, ImplItem, Item, ItemKind, Lifetime, LifetimeName, Node, TraitItem,
14 use rustc_middle::ty::{self, AssocItemContainer, RegionKind, Ty, TypeFoldable, TypeVisitor};
15 use rustc_span::symbol::Ident;
16 use rustc_span::{MultiSpan, Span};
18 impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
19 /// Print the error message for lifetime errors when the return type is a static `impl Trait`,
20 /// `dyn Trait` or if a method call on a trait object introduces a static requirement.
21 pub(super) fn try_report_static_impl_trait(&self) -> Option<ErrorReported> {
22 debug!("try_report_static_impl_trait(error={:?})", self.error);
24 let (var_origin, sub_origin, sub_r, sup_origin, sup_r) = match self.error.as_ref()? {
25 RegionResolutionError::SubSupConflict(
32 ) if **sub_r == RegionKind::ReStatic => {
33 (var_origin, sub_origin, sub_r, sup_origin, sup_r)
35 RegionResolutionError::ConcreteFailure(
36 SubregionOrigin::Subtype(box TypeTrace { cause, .. }),
39 ) if **sub_r == RegionKind::ReStatic => {
40 // This is for an implicit `'static` requirement coming from `impl dyn Trait {}`.
41 if let ObligationCauseCode::UnifyReceiver(ctxt) = &cause.code {
42 let param = self.find_param_with_region(sup_r, sub_r)?;
43 let lifetime = if sup_r.has_name() {
44 format!("lifetime `{}`", sup_r)
46 "an anonymous lifetime `'_`".to_string()
48 let mut err = struct_span_err!(
52 "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
58 .map(|s| format!("`{}`", s))
59 .unwrap_or_else(|| "`fn` parameter".to_string()),
61 ctxt.assoc_item.ident,
63 err.span_label(param.param_ty_span, &format!("this data with {}...", lifetime));
67 "...is captured and required to live as long as `'static` here \
68 because of an implicit lifetime bound on the {}",
69 match ctxt.assoc_item.container {
70 AssocItemContainer::TraitContainer(id) =>
71 format!("`impl` of `{}`", tcx.def_path_str(id)),
72 AssocItemContainer::ImplContainer(_) =>
73 "inherent `impl`".to_string(),
77 if self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt) {
79 return Some(ErrorReported);
89 "try_report_static_impl_trait(var={:?}, sub={:?} {:?} sup={:?} {:?})",
90 var_origin, sub_origin, sub_r, sup_origin, sup_r
92 let anon_reg_sup = tcx.is_suitable_region(sup_r)?;
93 debug!("try_report_static_impl_trait: anon_reg_sup={:?}", anon_reg_sup);
94 let sp = var_origin.span();
95 let return_sp = sub_origin.span();
96 let param = self.find_param_with_region(sup_r, sub_r)?;
97 let (lifetime_name, lifetime) = if sup_r.has_name() {
98 (sup_r.to_string(), format!("lifetime `{}`", sup_r))
100 ("'_".to_owned(), "an anonymous lifetime `'_`".to_string())
102 let param_name = param
106 .map(|s| format!("`{}`", s))
107 .unwrap_or_else(|| "`fn` parameter".to_string());
108 let mut err = struct_span_err!(
112 "{} has {} but it needs to satisfy a `'static` lifetime requirement",
116 err.span_label(param.param_ty_span, &format!("this data with {}...", lifetime));
117 debug!("try_report_static_impl_trait: param_info={:?}", param);
119 // We try to make the output have fewer overlapping spans if possible.
120 if (sp == sup_origin.span() || !return_sp.overlaps(sup_origin.span()))
121 && sup_origin.span() != return_sp
123 // FIXME: account for `async fn` like in `async-await/issues/issue-62097.rs`
125 // Customize the spans and labels depending on their relative order so
126 // that split sentences flow correctly.
127 if sup_origin.span().overlaps(return_sp) && sp == sup_origin.span() {
128 // Avoid the following:
130 // error: cannot infer an appropriate lifetime
131 // --> $DIR/must_outlive_least_region_or_bound.rs:18:50
133 // LL | fn foo(x: &i32) -> Box<dyn Debug> { Box::new(x) }
134 // | ---- ---------^-
138 // error: cannot infer an appropriate lifetime
139 // --> $DIR/must_outlive_least_region_or_bound.rs:18:50
141 // LL | fn foo(x: &i32) -> Box<dyn Debug> { Box::new(x) }
145 "...is captured here, requiring it to live as long as `'static`",
148 err.span_label(sup_origin.span(), "...is captured here...");
149 if return_sp < sup_origin.span() {
152 "...and is required to live as long as `'static` here",
157 "...and is required to live as long as `'static` here",
164 "...is captured and required to live as long as `'static` here",
168 let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.def_id);
170 let mut override_error_code = None;
171 if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sup_origin {
172 if let ObligationCauseCode::UnifyReceiver(ctxt) = &cause.code {
173 // Handle case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a
174 // `'static` lifetime when called as a method on a binding: `bar.qux()`.
175 if self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt) {
176 override_error_code = Some(ctxt.assoc_item.ident);
180 if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sub_origin {
181 if let ObligationCauseCode::ItemObligation(item_def_id) = cause.code {
182 // Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static`
183 // lifetime as above, but called using a fully-qualified path to the method:
185 let mut v = TraitObjectVisitor(vec![]);
186 v.visit_ty(param.param_ty);
187 if let Some((ident, self_ty)) =
188 self.get_impl_ident_and_self_ty_from_trait(item_def_id, &v.0[..])
190 if self.suggest_constrain_dyn_trait_in_impl(&mut err, &v.0[..], ident, self_ty)
192 override_error_code = Some(ident);
197 if let (Some(ident), true) = (override_error_code, fn_returns.is_empty()) {
198 // Provide a more targetted error code and description.
199 err.code(rustc_errors::error_code!(E0767));
200 err.set_primary_message(&format!(
201 "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
203 param_name, lifetime, ident,
207 debug!("try_report_static_impl_trait: fn_return={:?}", fn_returns);
208 // FIXME: account for the need of parens in `&(dyn Trait + '_)`
209 let consider = "consider changing the";
210 let declare = "to declare that the";
211 let arg = match param.param.pat.simple_ident() {
212 Some(simple_ident) => format!("argument `{}`", simple_ident),
213 None => "the argument".to_string(),
215 let explicit = format!("you can add an explicit `{}` lifetime bound", lifetime_name);
216 let explicit_static = format!("explicit `'static` bound to the lifetime of {}", arg);
217 let captures = format!("captures data from {}", arg);
218 let add_static_bound = "alternatively, add an explicit `'static` bound to this reference";
219 let plus_lt = format!(" + {}", lifetime_name);
220 for fn_return in fn_returns {
221 if fn_return.span.desugaring_kind().is_some() {
222 // Skip `async` desugaring `impl Future`.
225 match fn_return.kind {
226 TyKind::OpaqueDef(item_id, _) => {
227 let item = tcx.hir().item(item_id.id);
228 let opaque = if let ItemKind::OpaqueTy(opaque) = &item.kind {
232 return Some(ErrorReported);
235 if let Some(span) = opaque
238 .filter_map(|arg| match arg {
239 GenericBound::Outlives(Lifetime {
240 name: LifetimeName::Static,
248 err.span_suggestion_verbose(
250 &format!("{} `impl Trait`'s {}", consider, explicit_static),
251 lifetime_name.clone(),
252 Applicability::MaybeIncorrect,
254 err.span_suggestion_verbose(
257 param.param_ty.to_string(),
258 Applicability::MaybeIncorrect,
260 } else if let Some(_) = opaque
263 .filter_map(|arg| match arg {
264 GenericBound::Outlives(Lifetime { name, span, .. })
265 if name.ident().to_string() == lifetime_name =>
274 err.span_suggestion_verbose(
275 fn_return.span.shrink_to_hi(),
277 "{declare} `impl Trait` {captures}, {explicit}",
283 Applicability::MaybeIncorrect,
287 TyKind::TraitObject(_, lt) => match lt.name {
288 LifetimeName::ImplicitObjectLifetimeDefault => {
289 err.span_suggestion_verbose(
290 fn_return.span.shrink_to_hi(),
292 "{declare} trait object {captures}, {explicit}",
298 Applicability::MaybeIncorrect,
301 name if name.ident().to_string() != lifetime_name => {
302 // With this check we avoid suggesting redundant bounds. This
303 // would happen if there are nested impl/dyn traits and only
304 // one of them has the bound we'd suggest already there, like
305 // in `impl Foo<X = dyn Bar> + '_`.
306 err.span_suggestion_verbose(
308 &format!("{} trait object's {}", consider, explicit_static),
309 lifetime_name.clone(),
310 Applicability::MaybeIncorrect,
312 err.span_suggestion_verbose(
315 param.param_ty.to_string(),
316 Applicability::MaybeIncorrect,
328 fn get_impl_ident_and_self_ty_from_trait(
331 trait_objects: &[DefId],
332 ) -> Option<(Ident, &'tcx hir::Ty<'tcx>)> {
333 let tcx = self.tcx();
334 match tcx.hir().get_if_local(def_id) {
335 Some(Node::ImplItem(ImplItem { ident, hir_id, .. })) => {
336 match tcx.hir().find(tcx.hir().get_parent_item(*hir_id)) {
337 Some(Node::Item(Item { kind: ItemKind::Impl { self_ty, .. }, .. })) => {
338 Some((*ident, self_ty))
343 Some(Node::TraitItem(TraitItem { ident, hir_id, .. })) => {
344 let parent_id = tcx.hir().get_parent_item(*hir_id);
345 match tcx.hir().find(parent_id) {
346 Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => {
347 // The method being called is defined in the `trait`, but the `'static`
348 // obligation comes from the `impl`. Find that `impl` so that we can point
349 // at it in the suggestion.
350 let trait_did = tcx.hir().local_def_id(parent_id).to_def_id();
353 .trait_impls(trait_did)
355 .filter_map(|impl_node| {
356 let impl_did = tcx.hir().local_def_id(*impl_node);
357 match tcx.hir().get_if_local(impl_did.to_def_id()) {
358 Some(Node::Item(Item {
359 kind: ItemKind::Impl { self_ty, .. },
361 })) if trait_objects.iter().all(|did| {
362 // FIXME: we should check `self_ty` against the receiver
363 // type in the `UnifyReceiver` context, but for now, use
364 // this imperfect proxy. This will fail if there are
365 // multiple `impl`s for the same trait like
366 // `impl Foo for Box<dyn Bar>` and `impl Foo for dyn Bar`.
367 // In that case, only the first one will get suggestions.
368 let mut hir_v = HirTraitObjectVisitor(vec![], *did);
369 hir_v.visit_ty(self_ty);
380 Some(self_ty) => Some((*ident, self_ty)),
391 /// When we call a method coming from an `impl Foo for dyn Bar`, `dyn Bar` introduces a default
392 /// `'static` obligation. Suggest relaxing that implicit bound.
393 fn find_impl_on_dyn_trait(
395 err: &mut DiagnosticBuilder<'_>,
397 ctxt: &UnifyReceiverContext<'tcx>,
399 let tcx = self.tcx();
401 // Find the method being called.
402 let instance = match ty::Instance::resolve(
405 ctxt.assoc_item.def_id,
406 self.infcx.resolve_vars_if_possible(&ctxt.substs),
408 Ok(Some(instance)) => instance,
412 let mut v = TraitObjectVisitor(vec![]);
415 // Get the `Ident` of the method being called and the corresponding `impl` (to point at
416 // `Bar` in `impl Foo for dyn Bar {}` and the definition of the method being called).
417 let (ident, self_ty) =
418 match self.get_impl_ident_and_self_ty_from_trait(instance.def_id(), &v.0[..]) {
419 Some((ident, self_ty)) => (ident, self_ty),
420 None => return false,
423 // Find the trait object types in the argument, so we point at *only* the trait object.
424 self.suggest_constrain_dyn_trait_in_impl(err, &v.0[..], ident, self_ty)
427 fn suggest_constrain_dyn_trait_in_impl(
429 err: &mut DiagnosticBuilder<'_>,
430 found_dids: &[DefId],
432 self_ty: &hir::Ty<'_>,
434 let mut suggested = false;
435 for found_did in found_dids {
436 let mut hir_v = HirTraitObjectVisitor(vec![], *found_did);
437 hir_v.visit_ty(&self_ty);
438 for span in &hir_v.0 {
439 let mut multi_span: MultiSpan = vec![*span].into();
440 multi_span.push_span_label(
442 "this has an implicit `'static` lifetime requirement".to_string(),
444 multi_span.push_span_label(
446 "calling this method introduces the `impl`'s 'static` requirement".to_string(),
448 err.span_note(multi_span, "the used `impl` has a `'static` requirement");
449 err.span_suggestion_verbose(
451 "consider relaxing the implicit `'static` requirement",
453 Applicability::MaybeIncorrect,
462 /// Collect all the trait objects in a type that could have received an implicit `'static` lifetime.
463 struct TraitObjectVisitor(Vec<DefId>);
465 impl TypeVisitor<'_> for TraitObjectVisitor {
466 fn visit_ty(&mut self, t: Ty<'_>) -> bool {
468 ty::Dynamic(preds, RegionKind::ReStatic) => {
469 if let Some(def_id) = preds.principal_def_id() {
474 _ => t.super_visit_with(self),
479 /// Collect all `hir::Ty<'_>` `Span`s for trait objects with an implicit lifetime.
480 struct HirTraitObjectVisitor(Vec<Span>, DefId);
482 impl<'tcx> Visitor<'tcx> for HirTraitObjectVisitor {
483 type Map = ErasedMap<'tcx>;
485 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
486 NestedVisitorMap::None
489 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
493 Lifetime { name: LifetimeName::ImplicitObjectLifetimeDefault, .. },
495 for ptr in poly_trait_refs {
496 if Some(self.1) == ptr.trait_ref.trait_def_id() {
497 self.0.push(ptr.span);