rustc_trait_selection/error_reporting/infer/nice_region_error/
static_impl_trait.rs

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