Skip to main content

rustc_hir_analysis/hir_ty_lowering/
dyn_trait.rs

1use rustc_ast::TraitObjectSyntax;
2use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
3use rustc_errors::codes::*;
4use rustc_errors::{
5    Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, StashKey,
6    Suggestions, struct_span_code_err,
7};
8use rustc_hir::def::{DefKind, Res};
9use rustc_hir::def_id::DefId;
10use rustc_hir::{self as hir, HirId, LangItem};
11use rustc_lint_defs::builtin::{BARE_TRAIT_OBJECTS, UNUSED_ASSOCIATED_TYPE_BOUNDS};
12use rustc_middle::ty::elaborate::ClauseWithSupertraitSpan;
13use rustc_middle::ty::{
14    self, BottomUpFolder, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeFoldable,
15    TypeVisitableExt, Upcast,
16};
17use rustc_span::edit_distance::find_best_match_for_name;
18use rustc_span::{ErrorGuaranteed, Span};
19use rustc_trait_selection::error_reporting::traits::report_dyn_incompatibility;
20use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName;
21use rustc_trait_selection::traits;
22use smallvec::{SmallVec, smallvec};
23use tracing::{debug, instrument};
24
25use super::HirTyLowerer;
26use crate::diagnostics::DynTraitAssocItemBindingMentionsSelf;
27use crate::hir_ty_lowering::{
28    GenericArgCountMismatch, ImpliedBoundsContext, OverlappingAsssocItemConstraints,
29    PredicateFilter, RegionInferReason,
30};
31
32impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
33    /// Lower a trait object type from the HIR to our internal notion of a type.
34    x;#[instrument(level = "debug", skip_all, ret)]
35    pub(super) fn lower_trait_object_ty(
36        &self,
37        span: Span,
38        hir_id: hir::HirId,
39        hir_bounds: &[hir::PolyTraitRef<'tcx>],
40        lifetime: &hir::Lifetime,
41        syntax: TraitObjectSyntax,
42    ) -> Ty<'tcx> {
43        let tcx = self.tcx();
44        let dummy_self = tcx.types.trait_object_dummy_self;
45
46        match syntax {
47            TraitObjectSyntax::Dyn => {}
48            TraitObjectSyntax::None => {
49                match self.prohibit_or_lint_bare_trait_object_ty(span, hir_id, hir_bounds) {
50                    // Don't continue with type analysis if the `dyn` keyword is missing.
51                    // It generates confusing errors, especially if the user meant to use
52                    // another keyword like `impl`.
53                    Some(guar) => return Ty::new_error(tcx, guar),
54                    None => {}
55                }
56            }
57        }
58
59        let mut user_written_bounds = Vec::new();
60        let mut potential_assoc_items = Vec::new();
61        for poly_trait_ref in hir_bounds.iter() {
62            // FIXME(mgca): We actually leak `trait_object_dummy_self` if the type of any assoc
63            //              const mentions `Self` (in "Self projections" which we intentionally
64            //              allow). That's because we query feed the instantiated type to `type_of`.
65            //              That's really bad, dummy self should never escape lowering! It leads us
66            //              to accept less code we'd like to support and can lead to ICEs later.
67            let result = self.lower_poly_trait_ref(
68                poly_trait_ref,
69                dummy_self,
70                &mut user_written_bounds,
71                PredicateFilter::SelfOnly,
72                OverlappingAsssocItemConstraints::Forbidden,
73            );
74            if let Err(GenericArgCountMismatch { invalid_args, .. }) = result.correct {
75                potential_assoc_items.extend(invalid_args);
76            }
77        }
78
79        self.add_default_traits(
80            &mut user_written_bounds,
81            dummy_self,
82            &hir_bounds
83                .iter()
84                .map(|&trait_ref| hir::GenericBound::Trait(trait_ref))
85                .collect::<Vec<_>>(),
86            ImpliedBoundsContext::AssociatedTypeOrImplTrait,
87            span,
88        );
89
90        let (mut elaborated_trait_bounds, elaborated_projection_bounds) =
91            traits::expand_trait_aliases(tcx, user_written_bounds.iter().copied());
92
93        // FIXME(sized-hierarchy): https://github.com/rust-lang/rust/pull/142712#issuecomment-3013231794
94        debug!(?user_written_bounds, ?elaborated_trait_bounds);
95        let meta_sized_did = tcx.require_lang_item(LangItem::MetaSized, span);
96        // Don't strip out `MetaSized` when the user wrote it explicitly, only when it was
97        // elaborated
98        if user_written_bounds
99            .iter()
100            .all(|(clause, _)| clause.as_trait_clause().map(|p| p.def_id()) != Some(meta_sized_did))
101        {
102            elaborated_trait_bounds.retain(|(pred, _)| pred.def_id() != meta_sized_did);
103        }
104        debug!(?user_written_bounds, ?elaborated_trait_bounds);
105
106        let (regular_traits, mut auto_traits): (Vec<_>, Vec<_>) = elaborated_trait_bounds
107            .into_iter()
108            .partition(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
109
110        // We don't support empty trait objects.
111        if regular_traits.is_empty() && auto_traits.is_empty() {
112            let guar =
113                self.report_trait_object_with_no_traits(span, user_written_bounds.iter().copied());
114            return Ty::new_error(tcx, guar);
115        }
116        // We don't support >1 principal
117        if regular_traits.len() > 1 {
118            let guar = self.report_trait_object_addition_traits(&regular_traits);
119            return Ty::new_error(tcx, guar);
120        }
121        // Don't create a dyn trait if we have errors in the principal.
122        if let Err(guar) = regular_traits.error_reported() {
123            return Ty::new_error(tcx, guar);
124        }
125
126        // Check that there are no gross dyn-compatibility violations;
127        // most importantly, that the supertraits don't contain `Self`,
128        // to avoid ICEs.
129        for (clause, span) in user_written_bounds {
130            if let Some(trait_pred) = clause.as_trait_clause() {
131                let violations = self.dyn_compatibility_violations(trait_pred.def_id());
132                if !violations.is_empty() {
133                    let reported = report_dyn_incompatibility(
134                        tcx,
135                        span,
136                        Some(hir_id),
137                        trait_pred.def_id(),
138                        &violations,
139                    )
140                    .emit();
141                    return Ty::new_error(tcx, reported);
142                }
143            }
144        }
145
146        // Map the projection bounds onto a key that makes it easy to remove redundant
147        // bounds that are constrained by supertraits of the principal trait.
148        //
149        // Also make sure we detect conflicting bounds from expanding trait aliases.
150        //
151        // FIXME(#150936): Since the elaborated projection bounds also include the user-written ones
152        //                 and we're separately rejecting duplicate+conflicting bindings for trait
153        //                 object types when lowering assoc item bindings, there are basic cases
154        //                 where we're emitting two distinct but very similar diagnostics.
155        let mut projection_bounds = FxIndexMap::default();
156        for (proj, proj_span) in elaborated_projection_bounds {
157            let item_def_id = proj.item_def_id();
158
159            let proj = proj.map_bound(|mut proj| {
160                let references_self = proj.term.walk().any(|arg| arg == dummy_self.into());
161                if references_self {
162                    let guar = self.dcx().emit_err(DynTraitAssocItemBindingMentionsSelf {
163                        span,
164                        kind: tcx.def_descr(item_def_id),
165                        binding: proj_span,
166                    });
167                    proj.term = replace_dummy_self_with_error(tcx, proj.term, guar);
168                }
169                proj
170            });
171
172            let key = (
173                item_def_id,
174                tcx.anonymize_bound_vars(
175                    proj.map_bound(|proj| proj.projection_term.trait_ref(tcx)),
176                ),
177            );
178            if let Some((old_proj, old_proj_span)) =
179                projection_bounds.insert(key, (proj, proj_span))
180                && tcx.anonymize_bound_vars(proj) != tcx.anonymize_bound_vars(old_proj)
181            {
182                let kind = tcx.def_descr(item_def_id);
183                let name = tcx.item_name(item_def_id);
184                self.dcx()
185                    .struct_span_err(span, format!("conflicting {kind} bindings for `{name}`"))
186                    .with_span_label(
187                        old_proj_span,
188                        format!("`{name}` is specified to be `{}` here", old_proj.term()),
189                    )
190                    .with_span_label(
191                        proj_span,
192                        format!("`{name}` is specified to be `{}` here", proj.term()),
193                    )
194                    .emit();
195            }
196        }
197
198        let principal_trait = regular_traits.into_iter().next();
199
200        // A stable ordering of associated types & consts from the principal trait and all its
201        // supertraits. We use this to ensure that different substitutions of a trait don't
202        // result in `dyn Trait` types with different projections lists, which can be unsound:
203        // <https://github.com/rust-lang/rust/pull/136458>.
204        // We achieve a stable ordering by walking over the unsubstituted principal trait ref.
205        let mut ordered_associated_items = vec![];
206
207        if let Some((principal_trait, ref spans)) = principal_trait {
208            let principal_trait = principal_trait.map_bound(|trait_pred| {
209                assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive);
210                trait_pred.trait_ref
211            });
212
213            for ClauseWithSupertraitSpan { clause, supertrait_span } in traits::elaborate(
214                tcx,
215                [ClauseWithSupertraitSpan::new(
216                    ty::TraitRef::identity(tcx, principal_trait.def_id()).upcast(tcx),
217                    *spans.last().unwrap(),
218                )],
219            )
220            .filter_only_self()
221            {
222                let clause = clause.instantiate_supertrait(tcx, principal_trait);
223                debug!("observing object predicate `{clause:?}`");
224
225                let bound_predicate = clause.kind();
226                match bound_predicate.skip_binder() {
227                    ty::ClauseKind::Trait(pred) => {
228                        // FIXME(negative_bounds): Handle this correctly...
229                        let trait_ref =
230                            tcx.anonymize_bound_vars(bound_predicate.rebind(pred.trait_ref));
231                        ordered_associated_items.extend(
232                            tcx.associated_items(pred.trait_ref.def_id)
233                                .in_definition_order()
234                                // Only associated types & type consts can possibly be
235                                // constrained in a trait object type via a binding.
236                                .filter(|item| item.is_type() || item.is_type_const())
237                                // Traits with RPITITs are simply not dyn compatible (for now).
238                                .filter(|item| !item.is_impl_trait_in_trait())
239                                .map(|item| (item.def_id, trait_ref)),
240                        );
241                    }
242                    ty::ClauseKind::Projection(pred) => {
243                        let pred = bound_predicate.rebind(pred);
244                        // A `Self` within the original bound will be instantiated with a
245                        // `trait_object_dummy_self`, so check for that.
246                        let references_self =
247                            pred.skip_binder().term.walk().any(|arg| arg == dummy_self.into());
248
249                        // If the projection output contains `Self`, force the user to
250                        // elaborate it explicitly to avoid a lot of complexity.
251                        //
252                        // The "classically useful" case is the following:
253                        // ```
254                        //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
255                        //         type MyOutput;
256                        //     }
257                        // ```
258                        //
259                        // Here, the user could theoretically write `dyn MyTrait<MyOutput = X>`,
260                        // but actually supporting that would "expand" to an infinitely-long type
261                        // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
262                        //
263                        // Instead, we force the user to write
264                        // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
265                        // the discussion in #56288 for alternatives.
266                        if !references_self {
267                            let key = (
268                                pred.item_def_id(),
269                                tcx.anonymize_bound_vars(
270                                    pred.map_bound(|proj| proj.projection_term.trait_ref(tcx)),
271                                ),
272                            );
273                            if !projection_bounds.contains_key(&key) {
274                                projection_bounds.insert(key, (pred, supertrait_span));
275                            }
276                        }
277
278                        self.check_elaborated_projection_mentions_input_lifetimes(
279                            pred,
280                            *spans.first().unwrap(),
281                            supertrait_span,
282                        );
283                    }
284                    _ => (),
285                }
286            }
287        }
288
289        // Flag assoc item bindings that didn't really need to be specified.
290        for &(projection_bound, span) in projection_bounds.values() {
291            let def_id = projection_bound.item_def_id();
292            if tcx.generics_require_sized_self(def_id) {
293                // FIXME(mgca): Ideally we would generalize the name of this lint to sth. like
294                // `unused_associated_item_bindings` since this can now also trigger on *const*
295                // projections / assoc *const* bindings.
296                tcx.emit_node_span_lint(
297                    UNUSED_ASSOCIATED_TYPE_BOUNDS,
298                    hir_id,
299                    span,
300                    crate::diagnostics::UnusedAssociatedTypeBounds { span },
301                );
302            }
303        }
304
305        // The user has to constrain all associated types & consts via bindings unless the
306        // corresponding associated item has a `where Self: Sized` clause. This can be done
307        // in the `dyn Trait` directly, in the supertrait bounds or behind trait aliases.
308        //
309        // Collect all associated items that weren't specified and compute the list of
310        // projection bounds which we'll later turn into existential ones.
311        //
312        // We intentionally keep around projections whose associated item has a `Self: Sized`
313        // bound in order to be able to wfcheck the RHS, allow the RHS to constrain generic
314        // parameters and to imply bounds.
315        // See also <https://github.com/rust-lang/rust/pull/140684>.
316        let mut missing_assoc_items = FxIndexSet::default();
317        let projection_bounds: Vec<_> = ordered_associated_items
318            .into_iter()
319            .filter_map(|key @ (def_id, _)| {
320                if let Some(&assoc) = projection_bounds.get(&key) {
321                    return Some(assoc);
322                }
323                if !tcx.generics_require_sized_self(def_id) {
324                    missing_assoc_items.insert(key);
325                }
326                None
327            })
328            .collect();
329
330        // If there are any associated items whose value wasn't provided, bail out with an error.
331        if let Err(guar) = self.check_for_required_assoc_items(
332            principal_trait.as_ref().map_or(smallvec![], |(_, spans)| spans.clone()),
333            missing_assoc_items,
334            potential_assoc_items,
335            hir_bounds,
336        ) {
337            return Ty::new_error(tcx, guar);
338        }
339
340        // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
341        // `dyn Trait + Send`.
342        // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
343        // the bounds
344        let mut duplicates = FxHashSet::default();
345        auto_traits.retain(|(trait_pred, _)| duplicates.insert(trait_pred.def_id()));
346
347        debug!(?principal_trait);
348        debug!(?auto_traits);
349
350        // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
351        let principal_trait_ref = principal_trait.map(|(trait_pred, spans)| {
352            trait_pred.map_bound(|trait_pred| {
353                let trait_ref = trait_pred.trait_ref;
354                assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive);
355                assert_eq!(trait_ref.self_ty(), dummy_self);
356
357                let span = *spans.first().unwrap();
358
359                // Verify that `dummy_self` did not leak inside generic parameter defaults. This
360                // could not be done at path creation, since we need to see through trait aliases.
361                let mut missing_generic_params = Vec::new();
362                let generics = tcx.generics_of(trait_ref.def_id);
363                let args: Vec<_> = trait_ref
364                    .args
365                    .iter()
366                    .enumerate()
367                    // Skip `Self`
368                    .skip(1)
369                    .map(|(index, arg)| {
370                        if arg.walk().any(|arg| arg == dummy_self.into()) {
371                            let param = &generics.own_params[index];
372                            missing_generic_params.push((param.name, param.kind.clone()));
373                            param.to_error(tcx)
374                        } else {
375                            arg
376                        }
377                    })
378                    .collect();
379
380                let empty_generic_args = hir_bounds.iter().any(|hir_bound| {
381                    hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
382                        && hir_bound.span.contains(span)
383                });
384                self.report_missing_generic_params(
385                    missing_generic_params,
386                    trait_ref.def_id,
387                    span,
388                    empty_generic_args,
389                );
390
391                ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::new(
392                    tcx,
393                    trait_ref.def_id,
394                    args,
395                ))
396            })
397        });
398
399        let existential_projections = projection_bounds.into_iter().map(|(bound, _)| {
400            bound.map_bound(|mut b| {
401                assert_eq!(b.projection_term.self_ty(), dummy_self);
402
403                // Like for trait refs, verify that `dummy_self` did not leak inside default type
404                // parameters.
405                let references_self = b.projection_term.args.iter().skip(1).any(|arg| {
406                    if arg.walk().any(|arg| arg == dummy_self.into()) {
407                        return true;
408                    }
409                    false
410                });
411                if references_self {
412                    let guar = tcx
413                        .dcx()
414                        .span_delayed_bug(span, "trait object projection bounds reference `Self`");
415                    b.projection_term = replace_dummy_self_with_error(tcx, b.projection_term, guar);
416                }
417
418                ty::ExistentialPredicate::Projection(ty::ExistentialProjection::erase_self_ty(
419                    tcx, b,
420                ))
421            })
422        });
423
424        let mut auto_trait_predicates: Vec<_> = auto_traits
425            .into_iter()
426            .map(|(trait_pred, _)| {
427                assert_eq!(trait_pred.polarity(), ty::PredicatePolarity::Positive);
428                assert_eq!(trait_pred.self_ty().skip_binder(), dummy_self);
429
430                ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_pred.def_id()))
431            })
432            .collect();
433        auto_trait_predicates.dedup();
434
435        // N.b. principal, projections, auto traits
436        // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
437        let mut predicates = principal_trait_ref
438            .into_iter()
439            .chain(existential_projections)
440            .chain(auto_trait_predicates)
441            .collect::<SmallVec<[_; 8]>>();
442        predicates.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
443        let predicates = tcx.mk_poly_existential_predicates(&predicates);
444
445        let region_bound = self.lower_trait_object_lifetime(lifetime, predicates, span);
446
447        Ty::new_dynamic(tcx, predicates, region_bound)
448    }
449
450    fn lower_trait_object_lifetime(
451        &self,
452        lifetime: &hir::Lifetime,
453        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
454        span: Span,
455    ) -> ty::Region<'tcx> {
456        // Curiously, we also use the *object region bound* for `Infer` (`'_`)
457        // while we obviously don't use the *object lifetime default* for it...
458        if let hir::LifetimeKind::ImplicitObjectLifetimeDefault | hir::LifetimeKind::Infer =
459            lifetime.kind
460            && let Some(region) = self.compute_object_lifetime_bound(span, predicates)
461        {
462            return region;
463        }
464
465        let reason = if let hir::LifetimeKind::ImplicitObjectLifetimeDefault = lifetime.kind {
466            RegionInferReason::ObjectLifetimeDefault(span.shrink_to_hi())
467        } else {
468            RegionInferReason::ExplicitObjectLifetime
469        };
470
471        self.lower_lifetime(lifetime, reason)
472    }
473
474    /// Check that elaborating the principal of a trait ref doesn't lead to projections
475    /// that are unconstrained. This can happen because an otherwise unconstrained
476    /// *type variable* can be substituted with a type that has late-bound regions. See
477    /// `elaborated-predicates-unconstrained-late-bound.rs` for a test.
478    fn check_elaborated_projection_mentions_input_lifetimes(
479        &self,
480        pred: ty::PolyProjectionPredicate<'tcx>,
481        span: Span,
482        supertrait_span: Span,
483    ) {
484        let tcx = self.tcx();
485
486        // Find any late-bound regions declared in `ty` that are not
487        // declared in the trait-ref or assoc_item. These are not well-formed.
488        //
489        // Example:
490        //
491        //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
492        //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
493        let late_bound_in_projection_term =
494            tcx.collect_constrained_late_bound_regions(pred.map_bound(|pred| pred.projection_term));
495        let late_bound_in_term =
496            tcx.collect_referenced_late_bound_regions(pred.map_bound(|pred| pred.term));
497        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs:497",
                        "rustc_hir_analysis::hir_ty_lowering::dyn_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(497u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::dyn_trait"),
                        ::tracing_core::field::FieldSet::new(&["late_bound_in_projection_term"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&late_bound_in_projection_term)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?late_bound_in_projection_term);
498        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs:498",
                        "rustc_hir_analysis::hir_ty_lowering::dyn_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(498u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::dyn_trait"),
                        ::tracing_core::field::FieldSet::new(&["late_bound_in_term"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&late_bound_in_term)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?late_bound_in_term);
499
500        // FIXME: point at the type params that don't have appropriate lifetimes:
501        // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
502        //                         ----  ----     ^^^^^^^
503        // NOTE(mgca): This error should be impossible to trigger with assoc const bindings.
504        self.validate_late_bound_regions(
505            late_bound_in_projection_term,
506            late_bound_in_term,
507            |br_name| {
508                let item_name = tcx.item_name(pred.item_def_id());
509                {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("binding for associated type `{0}` references {1}, which does not appear in the trait input types",
                            item_name, br_name))
                })).with_code(E0582)
}struct_span_code_err!(
510                    self.dcx(),
511                    span,
512                    E0582,
513                    "binding for associated type `{}` references {}, \
514                             which does not appear in the trait input types",
515                    item_name,
516                    br_name
517                )
518                .with_span_label(supertrait_span, "due to this supertrait")
519            },
520        );
521    }
522
523    /// Given the bounds on an object, determines what single region bound (if any) we can
524    /// use to summarize this type.
525    ///
526    /// The basic idea is that we will use the bound the user
527    /// provided, if they provided one, and otherwise search the supertypes of trait bounds
528    /// for region bounds. It may be that we can derive no bound at all, in which case
529    /// we return `None`.
530    x;#[instrument(level = "debug", skip(self, span), ret)]
531    fn compute_object_lifetime_bound(
532        &self,
533        span: Span,
534        existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
535    ) -> Option<ty::Region<'tcx>> // if None, use the default
536    {
537        let tcx = self.tcx();
538
539        // No explicit region bound specified. Therefore, examine trait
540        // bounds and see if we can derive region bounds from those.
541        let derived_region_bounds = traits::wf::object_region_bounds(tcx, existential_predicates);
542
543        // If there are no derived region bounds, then report back that we
544        // can find no region bound. The caller will use the default.
545        if derived_region_bounds.is_empty() {
546            return None;
547        }
548
549        // If any of the derived region bounds are 'static, that is always
550        // the best choice.
551        if derived_region_bounds.iter().any(|r| r.is_static()) {
552            return Some(tcx.lifetimes.re_static);
553        }
554
555        // Determine whether there is exactly one unique region in the set
556        // of derived region bounds. If so, use that. Otherwise, report an
557        // error.
558        let r = derived_region_bounds[0];
559        if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
560            self.dcx().emit_err(crate::diagnostics::AmbiguousLifetimeBound { span });
561        }
562        Some(r)
563    }
564
565    /// Prohibit or lint against *bare* trait object types depending on the edition.
566    ///
567    /// *Bare* trait object types are ones that aren't preceded by the keyword `dyn`.
568    /// In edition 2021 and onward we emit a hard error for them.
569    fn prohibit_or_lint_bare_trait_object_ty(
570        &self,
571        span: Span,
572        hir_id: hir::HirId,
573        hir_bounds: &[hir::PolyTraitRef<'tcx>],
574    ) -> Option<ErrorGuaranteed> {
575        struct TraitObjectWithoutDyn<'a, 'tcx> {
576            span: Span,
577            hir_id: HirId,
578            sugg: Vec<(Span, String)>,
579            this: &'a dyn HirTyLowerer<'tcx>,
580        }
581
582        impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for TraitObjectWithoutDyn<'b, 'tcx> {
583            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
584                let Self { span, hir_id, sugg, this } = self;
585                let mut lint =
586                    Diag::new(dcx, level, "trait objects without an explicit `dyn` are deprecated");
587                if span.can_be_used_for_suggestions() {
588                    lint.multipart_suggestion(
589                        "if this is a dyn-compatible trait, use `dyn`",
590                        sugg,
591                        Applicability::MachineApplicable,
592                    );
593                }
594                this.maybe_suggest_blanket_trait_impl(span, hir_id, &mut lint);
595                lint
596            }
597        }
598
599        let tcx = self.tcx();
600        let [poly_trait_ref, ..] = hir_bounds else { return None };
601
602        let in_path = match tcx.parent_hir_node(hir_id).path() {
603            Some(hir::QPath::TypeRelative(qself, _)) if qself.hir_id == hir_id => true,
604            _ => false,
605        };
606        let needs_bracket = in_path
607            && !tcx
608                .sess
609                .source_map()
610                .span_to_prev_source(span)
611                .ok()
612                .is_some_and(|s| s.trim_end().ends_with('<'));
613
614        let is_global = poly_trait_ref.trait_ref.path.is_global();
615
616        let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}dyn {1}",
                                    if needs_bracket { "<" } else { "" },
                                    if is_global { "(" } else { "" }))
                        }))]))vec![(
617            span.shrink_to_lo(),
618            format!(
619                "{}dyn {}",
620                if needs_bracket { "<" } else { "" },
621                if is_global { "(" } else { "" },
622            ),
623        )];
624
625        if is_global || needs_bracket {
626            sugg.push((
627                span.shrink_to_hi(),
628                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                if is_global { ")" } else { "" },
                if needs_bracket { ">" } else { "" }))
    })format!(
629                    "{}{}",
630                    if is_global { ")" } else { "" },
631                    if needs_bracket { ">" } else { "" },
632                ),
633            ));
634        }
635
636        if span.edition().at_least_rust_2021() {
637            let mut diag = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}",
                            "expected a type, found a trait"))
                })).with_code(E0782)
}rustc_errors::struct_span_code_err!(
638                self.dcx(),
639                span,
640                E0782,
641                "{}",
642                "expected a type, found a trait"
643            );
644            if span.can_be_used_for_suggestions()
645                && poly_trait_ref.trait_ref.trait_def_id().is_some()
646                && !self.maybe_suggest_impl_trait(span, hir_id, hir_bounds, &mut diag)
647                && !self.maybe_suggest_dyn_trait(hir_id, span, sugg, &mut diag)
648            {
649                self.maybe_suggest_add_generic_impl_trait(span, hir_id, &mut diag);
650            }
651            // Check if the impl trait that we are considering is an impl of a local trait.
652            self.maybe_suggest_blanket_trait_impl(span, hir_id, &mut diag);
653            self.maybe_suggest_assoc_ty_bound(hir_id, &mut diag);
654            self.maybe_suggest_typoed_method(
655                hir_id,
656                poly_trait_ref.trait_ref.trait_def_id(),
657                &mut diag,
658            );
659            // In case there is an associated type with the same name
660            // Add the suggestion to this error
661            if let Some(mut sugg) =
662                self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
663                && let Suggestions::Enabled(ref mut s1) = diag.suggestions
664                && let Suggestions::Enabled(ref mut s2) = sugg.suggestions
665            {
666                s1.append(s2);
667                sugg.cancel();
668            }
669            Some(diag.emit())
670        } else {
671            tcx.emit_node_span_lint(
672                BARE_TRAIT_OBJECTS,
673                hir_id,
674                span,
675                TraitObjectWithoutDyn { span, hir_id, sugg, this: self },
676            );
677            None
678        }
679    }
680
681    /// For a struct or enum with an invalid bare trait object field, suggest turning
682    /// it into a generic type bound.
683    fn maybe_suggest_add_generic_impl_trait(
684        &self,
685        span: Span,
686        hir_id: hir::HirId,
687        diag: &mut Diag<'_>,
688    ) -> bool {
689        let tcx = self.tcx();
690
691        let parent_hir_id = tcx.parent_hir_id(hir_id);
692        let parent_item = tcx.hir_get_parent_item(hir_id).def_id;
693
694        let generics = match tcx.hir_node_by_def_id(parent_item) {
695            hir::Node::Item(hir::Item {
696                kind: hir::ItemKind::Struct(_, generics, variant),
697                ..
698            }) => {
699                if !variant.fields().iter().any(|field| field.hir_id == parent_hir_id) {
700                    return false;
701                }
702                generics
703            }
704            hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics, def), .. }) => {
705                if !def
706                    .variants
707                    .iter()
708                    .flat_map(|variant| variant.data.fields().iter())
709                    .any(|field| field.hir_id == parent_hir_id)
710                {
711                    return false;
712                }
713                generics
714            }
715            _ => return false,
716        };
717
718        let Ok(rendered_ty) = tcx.sess.source_map().span_to_snippet(span) else {
719            return false;
720        };
721
722        let param = "TUV"
723            .chars()
724            .map(|c| c.to_string())
725            .chain((0..).map(|i| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("P{0}", i)) })format!("P{i}")))
726            .find(|s| !generics.params.iter().any(|param| param.name.ident().as_str() == s))
727            .expect("we definitely can find at least one param name to generate");
728        let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, param.to_string())]))vec![(span, param.to_string())];
729        if let Some(insertion_span) = generics.span_for_param_suggestion() {
730            sugg.push((insertion_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {1}: {0}", rendered_ty, param))
    })format!(", {param}: {}", rendered_ty)));
731        } else {
732            sugg.push((generics.where_clause_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{1}: {0}>", rendered_ty, param))
    })format!("<{param}: {}>", rendered_ty)));
733        }
734        diag.multipart_suggestion(
735            "you might be missing a type parameter",
736            sugg,
737            Applicability::MachineApplicable,
738        );
739        true
740    }
741
742    /// Make sure that we are in the condition to suggest the blanket implementation.
743    fn maybe_suggest_blanket_trait_impl<G: EmissionGuarantee>(
744        &self,
745        span: Span,
746        hir_id: hir::HirId,
747        diag: &mut Diag<'_, G>,
748    ) {
749        let tcx = self.tcx();
750        let parent_id = tcx.hir_get_parent_item(hir_id).def_id;
751        if let hir::Node::Item(hir::Item {
752            kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, of_trait, generics, .. }),
753            ..
754        }) = tcx.hir_node_by_def_id(parent_id)
755            && hir_id == impl_self_ty.hir_id
756        {
757            let Some(of_trait) = of_trait else {
758                diag.span_suggestion_verbose(
759                    impl_self_ty.span.shrink_to_hi(),
760                    "you might have intended to implement this trait for a given type",
761                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" for /* Type */"))
    })format!(" for /* Type */"),
762                    Applicability::HasPlaceholders,
763                );
764                return;
765            };
766            if !of_trait.trait_ref.trait_def_id().is_some_and(|def_id| def_id.is_local()) {
767                return;
768            }
769            let of_trait_span = of_trait.trait_ref.path.span;
770            // make sure that we are not calling unwrap to abort during the compilation
771            let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else {
772                return;
773            };
774
775            let Ok(impl_trait_name) = self.tcx().sess.source_map().span_to_snippet(span) else {
776                return;
777            };
778            let sugg = self.add_generic_param_suggestion(generics, span, &impl_trait_name);
779            diag.multipart_suggestion(
780                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alternatively use a blanket implementation to implement `{0}` for all types that also implement `{1}`",
                of_trait_name, impl_trait_name))
    })format!(
781                    "alternatively use a blanket implementation to implement `{of_trait_name}` for \
782                     all types that also implement `{impl_trait_name}`"
783                ),
784                sugg,
785                Applicability::MaybeIncorrect,
786            );
787        }
788    }
789
790    /// Try our best to approximate when adding `dyn` would be helpful for a bare
791    /// trait object.
792    ///
793    /// Right now, this is if the type is either directly nested in another ty,
794    /// or if it's in the tail field within a struct. This approximates what the
795    /// user would've gotten on edition 2015, except for the case where we have
796    /// an *obvious* knock-on `Sized` error.
797    fn maybe_suggest_dyn_trait(
798        &self,
799        hir_id: hir::HirId,
800        span: Span,
801        sugg: Vec<(Span, String)>,
802        diag: &mut Diag<'_>,
803    ) -> bool {
804        let tcx = self.tcx();
805        if span.in_derive_expansion() {
806            return false;
807        }
808
809        // Look at the direct HIR parent, since we care about the relationship between
810        // the type and the thing that directly encloses it.
811        match tcx.parent_hir_node(hir_id) {
812            // These are all generally ok. Namely, when a trait object is nested
813            // into another expression or ty, it's either very certain that they
814            // missed the ty (e.g. `&Trait`) or it's not really possible to tell
815            // what their intention is, so let's not give confusing suggestions and
816            // just mention `dyn`. The user can make up their mind what to do here.
817            hir::Node::Ty(_)
818            | hir::Node::Expr(_)
819            | hir::Node::PatExpr(_)
820            | hir::Node::PathSegment(_)
821            | hir::Node::AssocItemConstraint(_)
822            | hir::Node::TraitRef(_)
823            | hir::Node::Item(_)
824            | hir::Node::WherePredicate(_) => {}
825
826            hir::Node::Field(field) => {
827                // Enums can't have unsized fields, fields can only have an unsized tail field.
828                if let hir::Node::Item(hir::Item {
829                    kind: hir::ItemKind::Struct(_, _, variant), ..
830                }) = tcx.parent_hir_node(field.hir_id)
831                    && variant
832                        .fields()
833                        .last()
834                        .is_some_and(|tail_field| tail_field.hir_id == field.hir_id)
835                {
836                    // Ok
837                } else {
838                    return false;
839                }
840            }
841            _ => return false,
842        }
843
844        // FIXME: Only emit this suggestion if the trait is dyn-compatible.
845        diag.multipart_suggestion(
846            "you can add the `dyn` keyword if you want a trait object",
847            sugg,
848            Applicability::MachineApplicable,
849        );
850        true
851    }
852
853    fn add_generic_param_suggestion(
854        &self,
855        generics: &hir::Generics<'_>,
856        self_ty_span: Span,
857        impl_trait_name: &str,
858    ) -> Vec<(Span, String)> {
859        // check if the trait has generics, to make a correct suggestion
860        let param_name = generics.params.next_type_param_name(None);
861
862        let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
863            (span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}: {1}", param_name,
                impl_trait_name))
    })format!(", {param_name}: {impl_trait_name}"))
864        } else {
865            (generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}: {1}>", param_name,
                impl_trait_name))
    })format!("<{param_name}: {impl_trait_name}>"))
866        };
867        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self_ty_span, param_name), add_generic_sugg]))vec![(self_ty_span, param_name), add_generic_sugg]
868    }
869
870    /// Make sure that we are in the condition to suggest `impl Trait`.
871    fn maybe_suggest_impl_trait(
872        &self,
873        span: Span,
874        hir_id: hir::HirId,
875        hir_bounds: &[hir::PolyTraitRef<'tcx>],
876        diag: &mut Diag<'_>,
877    ) -> bool {
878        let tcx = self.tcx();
879        let parent_id = tcx.hir_get_parent_item(hir_id).def_id;
880        // FIXME: If `type_alias_impl_trait` is enabled, also look for `Trait0<Ty = Trait1>`
881        //        and suggest `Trait0<Ty = impl Trait1>`.
882        // Functions are found in three different contexts.
883        // 1. Independent functions
884        // 2. Functions inside trait blocks
885        // 3. Functions inside impl blocks
886        let (sig, generics) = match tcx.hir_node_by_def_id(parent_id) {
887            hir::Node::Item(hir::Item {
888                kind: hir::ItemKind::Fn { sig, generics, .. }, ..
889            }) => (sig, generics),
890            hir::Node::TraitItem(hir::TraitItem {
891                kind: hir::TraitItemKind::Fn(sig, _),
892                generics,
893                ..
894            }) => (sig, generics),
895            hir::Node::ImplItem(hir::ImplItem {
896                kind: hir::ImplItemKind::Fn(sig, _),
897                generics,
898                ..
899            }) => (sig, generics),
900            _ => return false,
901        };
902        let Ok(trait_name) = tcx.sess.source_map().span_to_snippet(span) else {
903            return false;
904        };
905        let impl_sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "impl ".to_string())]))vec![(span.shrink_to_lo(), "impl ".to_string())];
906        // Check if trait object is safe for suggesting dynamic dispatch.
907        let is_dyn_compatible = hir_bounds.iter().all(|bound| match bound.trait_ref.path.res {
908            Res::Def(DefKind::Trait, id) => tcx.is_dyn_compatible(id),
909            _ => false,
910        });
911
912        let borrowed = #[allow(non_exhaustive_omitted_patterns)] match tcx.parent_hir_node(hir_id) {
    hir::Node::Ty(hir::Ty { kind: hir::TyKind::Ref(..), .. }) => true,
    _ => false,
}matches!(
913            tcx.parent_hir_node(hir_id),
914            hir::Node::Ty(hir::Ty { kind: hir::TyKind::Ref(..), .. })
915        );
916
917        // Suggestions for function return type.
918        if let hir::FnRetTy::Return(ty) = sig.decl.output
919            && ty.peel_refs().hir_id == hir_id
920        {
921            let pre = if !is_dyn_compatible {
922                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is dyn-incompatible, ",
                trait_name))
    })format!("`{trait_name}` is dyn-incompatible, ")
923            } else {
924                String::new()
925            };
926            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}use `impl {1}` to return an opaque type, as long as you return a single underlying type",
                pre, trait_name))
    })format!(
927                "{pre}use `impl {trait_name}` to return an opaque type, as long as you return a \
928                 single underlying type",
929            );
930
931            diag.multipart_suggestion(msg, impl_sugg, Applicability::MachineApplicable);
932
933            // Suggest `Box<dyn Trait>` for return type
934            if is_dyn_compatible {
935                // If the return type is `&Trait`, we don't want
936                // the ampersand to be displayed in the `Box<dyn Trait>`
937                // suggestion.
938                let suggestion = if borrowed {
939                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ty.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("Box<dyn {0}>",
                                    trait_name))
                        }))]))vec![(ty.span, format!("Box<dyn {trait_name}>"))]
940                } else {
941                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ty.span.shrink_to_lo(), "Box<dyn ".to_string()),
                (ty.span.shrink_to_hi(), ">".to_string())]))vec![
942                        (ty.span.shrink_to_lo(), "Box<dyn ".to_string()),
943                        (ty.span.shrink_to_hi(), ">".to_string()),
944                    ]
945                };
946
947                diag.multipart_suggestion(
948                    "alternatively, you can return an owned trait object",
949                    suggestion,
950                    Applicability::MachineApplicable,
951                );
952            }
953            return true;
954        }
955
956        // Suggestions for function parameters.
957        for ty in sig.decl.inputs {
958            if ty.peel_refs().hir_id != hir_id {
959                continue;
960            }
961            let sugg = self.add_generic_param_suggestion(generics, span, &trait_name);
962            diag.multipart_suggestion(
963                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use a new generic type parameter, constrained by `{0}`",
                trait_name))
    })format!("use a new generic type parameter, constrained by `{trait_name}`"),
964                sugg,
965                Applicability::MachineApplicable,
966            );
967            diag.multipart_suggestion(
968                "you can also use an opaque type, but users won't be able to specify the type \
969                 parameter when calling the `fn`, having to rely exclusively on type inference",
970                impl_sugg,
971                Applicability::MachineApplicable,
972            );
973            if !is_dyn_compatible {
974                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is dyn-incompatible, otherwise a trait object could be used",
                trait_name))
    })format!(
975                    "`{trait_name}` is dyn-incompatible, otherwise a trait object could be used"
976                ));
977            } else {
978                // No ampersand in suggestion if it's borrowed already
979                let (dyn_str, paren_dyn_str) =
980                    if borrowed { ("dyn ", "(dyn ") } else { ("&dyn ", "&(dyn ") };
981
982                let sugg = if let [_, _, ..] = hir_bounds {
983                    // There is more than one trait bound, we need surrounding parentheses.
984                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), paren_dyn_str.to_string()),
                (span.shrink_to_hi(), ")".to_string())]))vec![
985                        (span.shrink_to_lo(), paren_dyn_str.to_string()),
986                        (span.shrink_to_hi(), ")".to_string()),
987                    ]
988                } else {
989                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), dyn_str.to_string())]))vec![(span.shrink_to_lo(), dyn_str.to_string())]
990                };
991                diag.multipart_suggestion(
992                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alternatively, use a trait object to accept any type that implements `{0}`, accessing its methods at runtime using dynamic dispatch",
                trait_name))
    })format!(
993                        "alternatively, use a trait object to accept any type that implements \
994                         `{trait_name}`, accessing its methods at runtime using dynamic dispatch",
995                    ),
996                    sugg,
997                    Applicability::MachineApplicable,
998                );
999            }
1000            return true;
1001        }
1002        false
1003    }
1004
1005    fn maybe_suggest_assoc_ty_bound(&self, hir_id: hir::HirId, diag: &mut Diag<'_>) {
1006        let mut parents = self.tcx().hir_parent_iter(hir_id);
1007
1008        if let Some((c_hir_id, hir::Node::AssocItemConstraint(constraint))) = parents.next()
1009            && let Some(obj_ty) = constraint.ty()
1010            && let Some((_, hir::Node::TraitRef(trait_ref))) = parents.next()
1011        {
1012            if let Some((_, hir::Node::Ty(ty))) = parents.next()
1013                && let hir::TyKind::TraitObject(..) = ty.kind
1014            {
1015                // Assoc ty bounds aren't permitted inside trait object types.
1016                return;
1017            }
1018
1019            if trait_ref
1020                .path
1021                .segments
1022                .iter()
1023                .find_map(|seg| {
1024                    seg.args.filter(|args| args.constraints.iter().any(|c| c.hir_id == c_hir_id))
1025                })
1026                .is_none_or(|args| args.parenthesized != hir::GenericArgsParentheses::No)
1027            {
1028                // Only consider angle-bracketed args (where we have a `=` to replace with `:`).
1029                return;
1030            }
1031
1032            let lo = if constraint.gen_args.span_ext.is_dummy() {
1033                constraint.ident.span
1034            } else {
1035                constraint.gen_args.span_ext
1036            };
1037            let hi = obj_ty.span;
1038
1039            if !lo.eq_ctxt(hi) {
1040                return;
1041            }
1042
1043            diag.span_suggestion_verbose(
1044                lo.between(hi),
1045                "you might have meant to write a bound here",
1046                ": ",
1047                Applicability::MaybeIncorrect,
1048            );
1049        }
1050    }
1051
1052    fn maybe_suggest_typoed_method(
1053        &self,
1054        hir_id: hir::HirId,
1055        trait_def_id: Option<DefId>,
1056        diag: &mut Diag<'_>,
1057    ) {
1058        let tcx = self.tcx();
1059        let Some(trait_def_id) = trait_def_id else {
1060            return;
1061        };
1062        let hir::Node::Expr(hir::Expr {
1063            kind: hir::ExprKind::Path(hir::QPath::TypeRelative(path_ty, segment)),
1064            ..
1065        }) = tcx.parent_hir_node(hir_id)
1066        else {
1067            return;
1068        };
1069        if path_ty.hir_id != hir_id {
1070            return;
1071        }
1072        let names: Vec<_> = tcx
1073            .associated_items(trait_def_id)
1074            .in_definition_order()
1075            .filter(|assoc| assoc.namespace() == hir::def::Namespace::ValueNS)
1076            .map(|cand| cand.name())
1077            .collect();
1078        if let Some(typo) = find_best_match_for_name(&names, segment.ident.name, None) {
1079            diag.span_suggestion_verbose(
1080                segment.ident.span,
1081                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you may have misspelled this associated item, causing `{0}` to be interpreted as a type rather than a trait",
                tcx.item_name(trait_def_id)))
    })format!(
1082                    "you may have misspelled this associated item, causing `{}` \
1083                    to be interpreted as a type rather than a trait",
1084                    tcx.item_name(trait_def_id),
1085                ),
1086                typo,
1087                Applicability::MaybeIncorrect,
1088            );
1089        }
1090    }
1091}
1092
1093fn replace_dummy_self_with_error<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
1094    tcx: TyCtxt<'tcx>,
1095    t: T,
1096    guar: ErrorGuaranteed,
1097) -> T {
1098    t.fold_with(&mut BottomUpFolder {
1099        tcx,
1100        ty_op: |ty| {
1101            if ty == tcx.types.trait_object_dummy_self { Ty::new_error(tcx, guar) } else { ty }
1102        },
1103        lt_op: |lt| lt,
1104        ct_op: |ct| ct,
1105    })
1106}