]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/astconv/mod.rs
Simplify astconv item def id handling
[rust.git] / compiler / rustc_hir_analysis / src / astconv / mod.rs
1 //! Conversion from AST representation of types to the `ty.rs` representation.
2 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
3 //! instance of `AstConv`.
4
5 mod errors;
6 mod generics;
7
8 use crate::bounds::Bounds;
9 use crate::collect::HirPlaceholderCollector;
10 use crate::errors::{
11     AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits,
12     TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified,
13 };
14 use crate::middle::resolve_lifetime as rl;
15 use crate::require_c_abi_if_c_variadic;
16 use rustc_ast::TraitObjectSyntax;
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_errors::{
19     struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, FatalError,
20     MultiSpan,
21 };
22 use rustc_hir as hir;
23 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
24 use rustc_hir::def_id::{DefId, LocalDefId};
25 use rustc_hir::intravisit::{walk_generics, Visitor as _};
26 use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin};
27 use rustc_middle::middle::stability::AllowUnstable;
28 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef};
29 use rustc_middle::ty::DynKind;
30 use rustc_middle::ty::GenericParamDefKind;
31 use rustc_middle::ty::{
32     self, Const, DefIdTree, EarlyBinder, IsSuggestable, Ty, TyCtxt, TypeVisitable,
33 };
34 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
35 use rustc_span::edition::Edition;
36 use rustc_span::lev_distance::find_best_match_for_name;
37 use rustc_span::symbol::{kw, Ident, Symbol};
38 use rustc_span::{sym, Span};
39 use rustc_target::spec::abi;
40 use rustc_trait_selection::traits;
41 use rustc_trait_selection::traits::astconv_object_safety_violations;
42 use rustc_trait_selection::traits::error_reporting::{
43     report_object_safety_error, suggestions::NextTypeParamName,
44 };
45 use rustc_trait_selection::traits::wf::object_region_bounds;
46
47 use smallvec::{smallvec, SmallVec};
48 use std::collections::BTreeSet;
49 use std::slice;
50
51 #[derive(Debug)]
52 pub struct PathSeg(pub DefId, pub usize);
53
54 pub trait AstConv<'tcx> {
55     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
56
57     fn item_def_id(&self) -> DefId;
58
59     /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
60     /// is a type parameter `X` with the given id `def_id` and T
61     /// matches `assoc_name`. This is a subset of the full set of
62     /// predicates.
63     ///
64     /// This is used for one specific purpose: resolving "short-hand"
65     /// associated type references like `T::Item`. In principle, we
66     /// would do that by first getting the full set of predicates in
67     /// scope and then filtering down to find those that apply to `T`,
68     /// but this can lead to cycle errors. The problem is that we have
69     /// to do this resolution *in order to create the predicates in
70     /// the first place*. Hence, we have this "special pass".
71     fn get_type_parameter_bounds(
72         &self,
73         span: Span,
74         def_id: DefId,
75         assoc_name: Ident,
76     ) -> ty::GenericPredicates<'tcx>;
77
78     /// Returns the lifetime to use when a lifetime is omitted (and not elided).
79     fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
80     -> Option<ty::Region<'tcx>>;
81
82     /// Returns the type to use when a type is omitted.
83     fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
84
85     /// Returns `true` if `_` is allowed in type signatures in the current context.
86     fn allow_ty_infer(&self) -> bool;
87
88     /// Returns the const to use when a const is omitted.
89     fn ct_infer(
90         &self,
91         ty: Ty<'tcx>,
92         param: Option<&ty::GenericParamDef>,
93         span: Span,
94     ) -> Const<'tcx>;
95
96     /// Projecting an associated type from a (potentially)
97     /// higher-ranked trait reference is more complicated, because of
98     /// the possibility of late-bound regions appearing in the
99     /// associated type binding. This is not legal in function
100     /// signatures for that reason. In a function body, we can always
101     /// handle it because we can use inference variables to remove the
102     /// late-bound regions.
103     fn projected_ty_from_poly_trait_ref(
104         &self,
105         span: Span,
106         item_def_id: DefId,
107         item_segment: &hir::PathSegment<'_>,
108         poly_trait_ref: ty::PolyTraitRef<'tcx>,
109     ) -> Ty<'tcx>;
110
111     /// Normalize an associated type coming from the user.
112     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
113
114     /// Invoked when we encounter an error from some prior pass
115     /// (e.g., resolve) that is translated into a ty-error. This is
116     /// used to help suppress derived errors typeck might otherwise
117     /// report.
118     fn set_tainted_by_errors(&self);
119
120     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
121 }
122
123 #[derive(Debug)]
124 struct ConvertedBinding<'a, 'tcx> {
125     hir_id: hir::HirId,
126     item_name: Ident,
127     kind: ConvertedBindingKind<'a, 'tcx>,
128     gen_args: &'a GenericArgs<'a>,
129     span: Span,
130 }
131
132 #[derive(Debug)]
133 enum ConvertedBindingKind<'a, 'tcx> {
134     Equality(ty::Term<'tcx>),
135     Constraint(&'a [hir::GenericBound<'a>]),
136 }
137
138 /// New-typed boolean indicating whether explicit late-bound lifetimes
139 /// are present in a set of generic arguments.
140 ///
141 /// For example if we have some method `fn f<'a>(&'a self)` implemented
142 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
143 /// is late-bound so should not be provided explicitly. Thus, if `f` is
144 /// instantiated with some generic arguments providing `'a` explicitly,
145 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
146 /// can provide an appropriate diagnostic later.
147 #[derive(Copy, Clone, PartialEq, Debug)]
148 pub enum ExplicitLateBound {
149     Yes,
150     No,
151 }
152
153 #[derive(Copy, Clone, PartialEq)]
154 pub enum IsMethodCall {
155     Yes,
156     No,
157 }
158
159 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
160 /// generic function or generic method call.
161 #[derive(Copy, Clone, PartialEq)]
162 pub(crate) enum GenericArgPosition {
163     Type,
164     Value, // e.g., functions
165     MethodCall,
166 }
167
168 /// A marker denoting that the generic arguments that were
169 /// provided did not match the respective generic parameters.
170 #[derive(Clone, Default, Debug)]
171 pub struct GenericArgCountMismatch {
172     /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
173     pub reported: Option<ErrorGuaranteed>,
174     /// A list of spans of arguments provided that were not valid.
175     pub invalid_args: Vec<Span>,
176 }
177
178 /// Decorates the result of a generic argument count mismatch
179 /// check with whether explicit late bounds were provided.
180 #[derive(Clone, Debug)]
181 pub struct GenericArgCountResult {
182     pub explicit_late_bound: ExplicitLateBound,
183     pub correct: Result<(), GenericArgCountMismatch>,
184 }
185
186 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
187     fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
188
189     fn provided_kind(
190         &mut self,
191         param: &ty::GenericParamDef,
192         arg: &GenericArg<'_>,
193     ) -> subst::GenericArg<'tcx>;
194
195     fn inferred_kind(
196         &mut self,
197         substs: Option<&[subst::GenericArg<'tcx>]>,
198         param: &ty::GenericParamDef,
199         infer_args: bool,
200     ) -> subst::GenericArg<'tcx>;
201 }
202
203 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
204     #[instrument(level = "debug", skip(self), ret)]
205     pub fn ast_region_to_region(
206         &self,
207         lifetime: &hir::Lifetime,
208         def: Option<&ty::GenericParamDef>,
209     ) -> ty::Region<'tcx> {
210         let tcx = self.tcx();
211         let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
212
213         match tcx.named_region(lifetime.hir_id) {
214             Some(rl::Region::Static) => tcx.lifetimes.re_static,
215
216             Some(rl::Region::LateBound(debruijn, index, def_id)) => {
217                 let name = lifetime_name(def_id.expect_local());
218                 let br = ty::BoundRegion {
219                     var: ty::BoundVar::from_u32(index),
220                     kind: ty::BrNamed(def_id, name),
221                 };
222                 tcx.mk_region(ty::ReLateBound(debruijn, br))
223             }
224
225             Some(rl::Region::EarlyBound(def_id)) => {
226                 let name = tcx.hir().ty_param_name(def_id.expect_local());
227                 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
228                 let generics = tcx.generics_of(item_def_id);
229                 let index = generics.param_def_id_to_index[&def_id];
230                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }))
231             }
232
233             Some(rl::Region::Free(scope, id)) => {
234                 let name = lifetime_name(id.expect_local());
235                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
236                     scope,
237                     bound_region: ty::BrNamed(id, name),
238                 }))
239
240                 // (*) -- not late-bound, won't change
241             }
242
243             None => {
244                 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
245                     debug!(?lifetime, "unelided lifetime in signature");
246
247                     // This indicates an illegal lifetime
248                     // elision. `resolve_lifetime` should have
249                     // reported an error in this case -- but if
250                     // not, let's error out.
251                     tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
252
253                     // Supply some dummy value. We don't have an
254                     // `re_error`, annoyingly, so use `'static`.
255                     tcx.lifetimes.re_static
256                 })
257             }
258         }
259     }
260
261     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
262     /// returns an appropriate set of substitutions for this particular reference to `I`.
263     pub fn ast_path_substs_for_ty(
264         &self,
265         span: Span,
266         def_id: DefId,
267         item_segment: &hir::PathSegment<'_>,
268     ) -> SubstsRef<'tcx> {
269         let (substs, _) = self.create_substs_for_ast_path(
270             span,
271             def_id,
272             &[],
273             item_segment,
274             item_segment.args(),
275             item_segment.infer_args,
276             None,
277             None,
278         );
279         if let Some(b) = item_segment.args().bindings.first() {
280             Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
281         }
282
283         substs
284     }
285
286     /// Given the type/lifetime/const arguments provided to some path (along with
287     /// an implicit `Self`, if this is a trait reference), returns the complete
288     /// set of substitutions. This may involve applying defaulted type parameters.
289     /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
290     ///
291     /// Example:
292     ///
293     /// ```ignore (illustrative)
294     ///    T: std::ops::Index<usize, Output = u32>
295     /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
296     /// ```
297     ///
298     /// 1. The `self_ty` here would refer to the type `T`.
299     /// 2. The path in question is the path to the trait `std::ops::Index`,
300     ///    which will have been resolved to a `def_id`
301     /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
302     ///    parameters are returned in the `SubstsRef`, the associated type bindings like
303     ///    `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
304     ///
305     /// Note that the type listing given here is *exactly* what the user provided.
306     ///
307     /// For (generic) associated types
308     ///
309     /// ```ignore (illustrative)
310     /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
311     /// ```
312     ///
313     /// We have the parent substs are the substs for the parent trait:
314     /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
315     /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
316     /// lists: `[Vec<u8>, u8, 'a]`.
317     #[instrument(level = "debug", skip(self, span), ret)]
318     fn create_substs_for_ast_path<'a>(
319         &self,
320         span: Span,
321         def_id: DefId,
322         parent_substs: &[subst::GenericArg<'tcx>],
323         seg: &hir::PathSegment<'_>,
324         generic_args: &'a hir::GenericArgs<'_>,
325         infer_args: bool,
326         self_ty: Option<Ty<'tcx>>,
327         constness: Option<ty::BoundConstness>,
328     ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
329         // If the type is parameterized by this region, then replace this
330         // region with the current anon region binding (in other words,
331         // whatever & would get replaced with).
332
333         let tcx = self.tcx();
334         let generics = tcx.generics_of(def_id);
335         debug!("generics: {:?}", generics);
336
337         if generics.has_self {
338             if generics.parent.is_some() {
339                 // The parent is a trait so it should have at least one subst
340                 // for the `Self` type.
341                 assert!(!parent_substs.is_empty())
342             } else {
343                 // This item (presumably a trait) needs a self-type.
344                 assert!(self_ty.is_some());
345             }
346         } else {
347             assert!(self_ty.is_none() && parent_substs.is_empty());
348         }
349
350         let arg_count = Self::check_generic_arg_count(
351             tcx,
352             span,
353             def_id,
354             seg,
355             generics,
356             generic_args,
357             GenericArgPosition::Type,
358             self_ty.is_some(),
359             infer_args,
360         );
361
362         // Skip processing if type has no generic parameters.
363         // Traits always have `Self` as a generic parameter, which means they will not return early
364         // here and so associated type bindings will be handled regardless of whether there are any
365         // non-`Self` generic parameters.
366         if generics.params.is_empty() {
367             return (tcx.intern_substs(parent_substs), arg_count);
368         }
369
370         struct SubstsForAstPathCtxt<'a, 'tcx> {
371             astconv: &'a (dyn AstConv<'tcx> + 'a),
372             def_id: DefId,
373             generic_args: &'a GenericArgs<'a>,
374             span: Span,
375             inferred_params: Vec<Span>,
376             infer_args: bool,
377         }
378
379         impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
380             fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
381                 if did == self.def_id {
382                     (Some(self.generic_args), self.infer_args)
383                 } else {
384                     // The last component of this tuple is unimportant.
385                     (None, false)
386                 }
387             }
388
389             fn provided_kind(
390                 &mut self,
391                 param: &ty::GenericParamDef,
392                 arg: &GenericArg<'_>,
393             ) -> subst::GenericArg<'tcx> {
394                 let tcx = self.astconv.tcx();
395
396                 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
397                     if has_default {
398                         tcx.check_optional_stability(
399                             param.def_id,
400                             Some(arg.hir_id()),
401                             arg.span(),
402                             None,
403                             AllowUnstable::No,
404                             |_, _| {
405                                 // Default generic parameters may not be marked
406                                 // with stability attributes, i.e. when the
407                                 // default parameter was defined at the same time
408                                 // as the rest of the type. As such, we ignore missing
409                                 // stability attributes.
410                             },
411                         );
412                     }
413                     if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
414                         self.inferred_params.push(ty.span);
415                         tcx.ty_error().into()
416                     } else {
417                         self.astconv.ast_ty_to_ty(ty).into()
418                     }
419                 };
420
421                 match (&param.kind, arg) {
422                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
423                         self.astconv.ast_region_to_region(lt, Some(param)).into()
424                     }
425                     (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
426                         handle_ty_args(has_default, ty)
427                     }
428                     (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
429                         handle_ty_args(has_default, &inf.to_ty())
430                     }
431                     (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
432                         ty::Const::from_opt_const_arg_anon_const(
433                             tcx,
434                             ty::WithOptConstParam {
435                                 did: tcx.hir().local_def_id(ct.value.hir_id),
436                                 const_param_did: Some(param.def_id),
437                             },
438                         )
439                         .into()
440                     }
441                     (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
442                         let ty = tcx.at(self.span).type_of(param.def_id);
443                         if self.astconv.allow_ty_infer() {
444                             self.astconv.ct_infer(ty, Some(param), inf.span).into()
445                         } else {
446                             self.inferred_params.push(inf.span);
447                             tcx.const_error(ty).into()
448                         }
449                     }
450                     _ => unreachable!(),
451                 }
452             }
453
454             fn inferred_kind(
455                 &mut self,
456                 substs: Option<&[subst::GenericArg<'tcx>]>,
457                 param: &ty::GenericParamDef,
458                 infer_args: bool,
459             ) -> subst::GenericArg<'tcx> {
460                 let tcx = self.astconv.tcx();
461                 match param.kind {
462                     GenericParamDefKind::Lifetime => self
463                         .astconv
464                         .re_infer(Some(param), self.span)
465                         .unwrap_or_else(|| {
466                             debug!(?param, "unelided lifetime in signature");
467
468                             // This indicates an illegal lifetime in a non-assoc-trait position
469                             tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
470
471                             // Supply some dummy value. We don't have an
472                             // `re_error`, annoyingly, so use `'static`.
473                             tcx.lifetimes.re_static
474                         })
475                         .into(),
476                     GenericParamDefKind::Type { has_default, .. } => {
477                         if !infer_args && has_default {
478                             // No type parameter provided, but a default exists.
479                             let substs = substs.unwrap();
480                             if substs.iter().any(|arg| match arg.unpack() {
481                                 GenericArgKind::Type(ty) => ty.references_error(),
482                                 _ => false,
483                             }) {
484                                 // Avoid ICE #86756 when type error recovery goes awry.
485                                 return tcx.ty_error().into();
486                             }
487                             self.astconv
488                                 .normalize_ty(
489                                     self.span,
490                                     EarlyBinder(tcx.at(self.span).type_of(param.def_id))
491                                         .subst(tcx, substs),
492                                 )
493                                 .into()
494                         } else if infer_args {
495                             self.astconv.ty_infer(Some(param), self.span).into()
496                         } else {
497                             // We've already errored above about the mismatch.
498                             tcx.ty_error().into()
499                         }
500                     }
501                     GenericParamDefKind::Const { has_default } => {
502                         let ty = tcx.at(self.span).type_of(param.def_id);
503                         if !infer_args && has_default {
504                             tcx.bound_const_param_default(param.def_id)
505                                 .subst(tcx, substs.unwrap())
506                                 .into()
507                         } else {
508                             if infer_args {
509                                 self.astconv.ct_infer(ty, Some(param), self.span).into()
510                             } else {
511                                 // We've already errored above about the mismatch.
512                                 tcx.const_error(ty).into()
513                             }
514                         }
515                     }
516                 }
517             }
518         }
519
520         let mut substs_ctx = SubstsForAstPathCtxt {
521             astconv: self,
522             def_id,
523             span,
524             generic_args,
525             inferred_params: vec![],
526             infer_args,
527         };
528         let substs = Self::create_substs_for_generic_args(
529             tcx,
530             def_id,
531             parent_substs,
532             self_ty.is_some(),
533             self_ty,
534             &arg_count,
535             &mut substs_ctx,
536         );
537
538         if let Some(ty::BoundConstness::ConstIfConst) = constness
539             && generics.has_self && !tcx.has_attr(def_id, sym::const_trait)
540         {
541             tcx.sess.emit_err(crate::errors::ConstBoundForNonConstTrait { span } );
542         }
543
544         (substs, arg_count)
545     }
546
547     fn create_assoc_bindings_for_generic_args<'a>(
548         &self,
549         generic_args: &'a hir::GenericArgs<'_>,
550     ) -> Vec<ConvertedBinding<'a, 'tcx>> {
551         // Convert associated-type bindings or constraints into a separate vector.
552         // Example: Given this:
553         //
554         //     T: Iterator<Item = u32>
555         //
556         // The `T` is passed in as a self-type; the `Item = u32` is
557         // not a "type parameter" of the `Iterator` trait, but rather
558         // a restriction on `<T as Iterator>::Item`, so it is passed
559         // back separately.
560         let assoc_bindings = generic_args
561             .bindings
562             .iter()
563             .map(|binding| {
564                 let kind = match binding.kind {
565                     hir::TypeBindingKind::Equality { ref term } => match term {
566                         hir::Term::Ty(ref ty) => {
567                             ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
568                         }
569                         hir::Term::Const(ref c) => {
570                             let local_did = self.tcx().hir().local_def_id(c.hir_id);
571                             let c = Const::from_anon_const(self.tcx(), local_did);
572                             ConvertedBindingKind::Equality(c.into())
573                         }
574                     },
575                     hir::TypeBindingKind::Constraint { ref bounds } => {
576                         ConvertedBindingKind::Constraint(bounds)
577                     }
578                 };
579                 ConvertedBinding {
580                     hir_id: binding.hir_id,
581                     item_name: binding.ident,
582                     kind,
583                     gen_args: binding.gen_args,
584                     span: binding.span,
585                 }
586             })
587             .collect();
588
589         assoc_bindings
590     }
591
592     pub fn create_substs_for_associated_item(
593         &self,
594         span: Span,
595         item_def_id: DefId,
596         item_segment: &hir::PathSegment<'_>,
597         parent_substs: SubstsRef<'tcx>,
598     ) -> SubstsRef<'tcx> {
599         debug!(
600             "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
601             span, item_def_id, item_segment
602         );
603         let (args, _) = self.create_substs_for_ast_path(
604             span,
605             item_def_id,
606             parent_substs,
607             item_segment,
608             item_segment.args(),
609             item_segment.infer_args,
610             None,
611             None,
612         );
613
614         if let Some(b) = item_segment.args().bindings.first() {
615             Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
616         }
617
618         args
619     }
620
621     /// Instantiates the path for the given trait reference, assuming that it's
622     /// bound to a valid trait type. Returns the `DefId` of the defining trait.
623     /// The type _cannot_ be a type other than a trait type.
624     ///
625     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
626     /// are disallowed. Otherwise, they are pushed onto the vector given.
627     pub fn instantiate_mono_trait_ref(
628         &self,
629         trait_ref: &hir::TraitRef<'_>,
630         self_ty: Ty<'tcx>,
631         constness: ty::BoundConstness,
632     ) -> ty::TraitRef<'tcx> {
633         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
634
635         self.ast_path_to_mono_trait_ref(
636             trait_ref.path.span,
637             trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
638             self_ty,
639             trait_ref.path.segments.last().unwrap(),
640             true,
641             Some(constness),
642         )
643     }
644
645     fn instantiate_poly_trait_ref_inner(
646         &self,
647         hir_id: hir::HirId,
648         span: Span,
649         binding_span: Option<Span>,
650         constness: ty::BoundConstness,
651         bounds: &mut Bounds<'tcx>,
652         speculative: bool,
653         trait_ref_span: Span,
654         trait_def_id: DefId,
655         trait_segment: &hir::PathSegment<'_>,
656         args: &GenericArgs<'_>,
657         infer_args: bool,
658         self_ty: Ty<'tcx>,
659     ) -> GenericArgCountResult {
660         let (substs, arg_count) = self.create_substs_for_ast_path(
661             trait_ref_span,
662             trait_def_id,
663             &[],
664             trait_segment,
665             args,
666             infer_args,
667             Some(self_ty),
668             Some(constness),
669         );
670
671         let tcx = self.tcx();
672         let bound_vars = tcx.late_bound_vars(hir_id);
673         debug!(?bound_vars);
674
675         let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
676
677         let poly_trait_ref =
678             ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
679
680         debug!(?poly_trait_ref, ?assoc_bindings);
681         bounds.trait_bounds.push((poly_trait_ref, span, constness));
682
683         let mut dup_bindings = FxHashMap::default();
684         for binding in &assoc_bindings {
685             // Specify type to assert that error was already reported in `Err` case.
686             let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
687                 hir_id,
688                 poly_trait_ref,
689                 binding,
690                 bounds,
691                 speculative,
692                 &mut dup_bindings,
693                 binding_span.unwrap_or(binding.span),
694                 constness,
695             );
696             // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
697         }
698
699         arg_count
700     }
701
702     /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
703     /// a full trait reference. The resulting trait reference is returned. This may also generate
704     /// auxiliary bounds, which are added to `bounds`.
705     ///
706     /// Example:
707     ///
708     /// ```ignore (illustrative)
709     /// poly_trait_ref = Iterator<Item = u32>
710     /// self_ty = Foo
711     /// ```
712     ///
713     /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
714     ///
715     /// **A note on binders:** against our usual convention, there is an implied bounder around
716     /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
717     /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
718     /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
719     /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
720     /// however.
721     #[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
722     pub(crate) fn instantiate_poly_trait_ref(
723         &self,
724         trait_ref: &hir::TraitRef<'_>,
725         span: Span,
726         constness: ty::BoundConstness,
727         self_ty: Ty<'tcx>,
728         bounds: &mut Bounds<'tcx>,
729         speculative: bool,
730     ) -> GenericArgCountResult {
731         let hir_id = trait_ref.hir_ref_id;
732         let binding_span = None;
733         let trait_ref_span = trait_ref.path.span;
734         let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
735         let trait_segment = trait_ref.path.segments.last().unwrap();
736         let args = trait_segment.args();
737         let infer_args = trait_segment.infer_args;
738
739         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
740         self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
741
742         self.instantiate_poly_trait_ref_inner(
743             hir_id,
744             span,
745             binding_span,
746             constness,
747             bounds,
748             speculative,
749             trait_ref_span,
750             trait_def_id,
751             trait_segment,
752             args,
753             infer_args,
754             self_ty,
755         )
756     }
757
758     pub(crate) fn instantiate_lang_item_trait_ref(
759         &self,
760         lang_item: hir::LangItem,
761         span: Span,
762         hir_id: hir::HirId,
763         args: &GenericArgs<'_>,
764         self_ty: Ty<'tcx>,
765         bounds: &mut Bounds<'tcx>,
766     ) {
767         let binding_span = Some(span);
768         let constness = ty::BoundConstness::NotConst;
769         let speculative = false;
770         let trait_ref_span = span;
771         let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
772         let trait_segment = &hir::PathSegment::invalid();
773         let infer_args = false;
774
775         self.instantiate_poly_trait_ref_inner(
776             hir_id,
777             span,
778             binding_span,
779             constness,
780             bounds,
781             speculative,
782             trait_ref_span,
783             trait_def_id,
784             trait_segment,
785             args,
786             infer_args,
787             self_ty,
788         );
789     }
790
791     fn ast_path_to_mono_trait_ref(
792         &self,
793         span: Span,
794         trait_def_id: DefId,
795         self_ty: Ty<'tcx>,
796         trait_segment: &hir::PathSegment<'_>,
797         is_impl: bool,
798         constness: Option<ty::BoundConstness>,
799     ) -> ty::TraitRef<'tcx> {
800         let (substs, _) = self.create_substs_for_ast_trait_ref(
801             span,
802             trait_def_id,
803             self_ty,
804             trait_segment,
805             is_impl,
806             constness,
807         );
808         if let Some(b) = trait_segment.args().bindings.first() {
809             Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
810         }
811         ty::TraitRef::new(trait_def_id, substs)
812     }
813
814     #[instrument(level = "debug", skip(self, span))]
815     fn create_substs_for_ast_trait_ref<'a>(
816         &self,
817         span: Span,
818         trait_def_id: DefId,
819         self_ty: Ty<'tcx>,
820         trait_segment: &'a hir::PathSegment<'a>,
821         is_impl: bool,
822         constness: Option<ty::BoundConstness>,
823     ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
824         self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
825
826         self.create_substs_for_ast_path(
827             span,
828             trait_def_id,
829             &[],
830             trait_segment,
831             trait_segment.args(),
832             trait_segment.infer_args,
833             Some(self_ty),
834             constness,
835         )
836     }
837
838     fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
839         self.tcx()
840             .associated_items(trait_def_id)
841             .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
842             .is_some()
843     }
844     fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
845         self.tcx()
846             .associated_items(trait_def_id)
847             .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
848             .is_some()
849     }
850
851     // Sets `implicitly_sized` to true on `Bounds` if necessary
852     pub(crate) fn add_implicitly_sized<'hir>(
853         &self,
854         bounds: &mut Bounds<'hir>,
855         ast_bounds: &'hir [hir::GenericBound<'hir>],
856         self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>,
857         span: Span,
858     ) {
859         let tcx = self.tcx();
860
861         // Try to find an unbound in bounds.
862         let mut unbound = None;
863         let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| {
864             for ab in ast_bounds {
865                 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
866                     if unbound.is_none() {
867                         unbound = Some(&ptr.trait_ref);
868                     } else {
869                         tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
870                     }
871                 }
872             }
873         };
874         search_bounds(ast_bounds);
875         if let Some((self_ty, where_clause)) = self_ty_where_predicates {
876             let self_ty_def_id = tcx.hir().local_def_id(self_ty).to_def_id();
877             for clause in where_clause {
878                 if let hir::WherePredicate::BoundPredicate(pred) = clause {
879                     if pred.is_param_bound(self_ty_def_id) {
880                         search_bounds(pred.bounds);
881                     }
882                 }
883             }
884         }
885
886         let sized_def_id = tcx.lang_items().sized_trait();
887         match (&sized_def_id, unbound) {
888             (Some(sized_def_id), Some(tpb))
889                 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
890             {
891                 // There was in fact a `?Sized` bound, return without doing anything
892                 return;
893             }
894             (_, Some(_)) => {
895                 // There was a `?Trait` bound, but it was not `?Sized`; warn.
896                 tcx.sess.span_warn(
897                     span,
898                     "default bound relaxed for a type parameter, but \
899                         this does nothing because the given bound is not \
900                         a default; only `?Sized` is supported",
901                 );
902                 // Otherwise, add implicitly sized if `Sized` is available.
903             }
904             _ => {
905                 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
906             }
907         }
908         if sized_def_id.is_none() {
909             // No lang item for `Sized`, so we can't add it as a bound.
910             return;
911         }
912         bounds.implicitly_sized = Some(span);
913     }
914
915     /// This helper takes a *converted* parameter type (`param_ty`)
916     /// and an *unconverted* list of bounds:
917     ///
918     /// ```text
919     /// fn foo<T: Debug>
920     ///        ^  ^^^^^ `ast_bounds` parameter, in HIR form
921     ///        |
922     ///        `param_ty`, in ty form
923     /// ```
924     ///
925     /// It adds these `ast_bounds` into the `bounds` structure.
926     ///
927     /// **A note on binders:** there is an implied binder around
928     /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
929     /// for more details.
930     #[instrument(level = "debug", skip(self, ast_bounds, bounds))]
931     pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
932         &self,
933         param_ty: Ty<'tcx>,
934         ast_bounds: I,
935         bounds: &mut Bounds<'tcx>,
936         bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
937     ) {
938         for ast_bound in ast_bounds {
939             match ast_bound {
940                 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
941                     let constness = match modifier {
942                         hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
943                         hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
944                         hir::TraitBoundModifier::Maybe => continue,
945                     };
946
947                     let _ = self.instantiate_poly_trait_ref(
948                         &poly_trait_ref.trait_ref,
949                         poly_trait_ref.span,
950                         constness,
951                         param_ty,
952                         bounds,
953                         false,
954                     );
955                 }
956                 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
957                     self.instantiate_lang_item_trait_ref(
958                         lang_item, span, hir_id, args, param_ty, bounds,
959                     );
960                 }
961                 hir::GenericBound::Outlives(lifetime) => {
962                     let region = self.ast_region_to_region(lifetime, None);
963                     bounds
964                         .region_bounds
965                         .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span));
966                 }
967             }
968         }
969     }
970
971     /// Translates a list of bounds from the HIR into the `Bounds` data structure.
972     /// The self-type for the bounds is given by `param_ty`.
973     ///
974     /// Example:
975     ///
976     /// ```ignore (illustrative)
977     /// fn foo<T: Bar + Baz>() { }
978     /// //     ^  ^^^^^^^^^ ast_bounds
979     /// //     param_ty
980     /// ```
981     ///
982     /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
983     /// considered `Sized` unless there is an explicit `?Sized` bound.  This would be true in the
984     /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
985     ///
986     /// `span` should be the declaration size of the parameter.
987     pub(crate) fn compute_bounds(
988         &self,
989         param_ty: Ty<'tcx>,
990         ast_bounds: &[hir::GenericBound<'_>],
991     ) -> Bounds<'tcx> {
992         self.compute_bounds_inner(param_ty, ast_bounds)
993     }
994
995     /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
996     /// named `assoc_name` into ty::Bounds. Ignore the rest.
997     pub(crate) fn compute_bounds_that_match_assoc_type(
998         &self,
999         param_ty: Ty<'tcx>,
1000         ast_bounds: &[hir::GenericBound<'_>],
1001         assoc_name: Ident,
1002     ) -> Bounds<'tcx> {
1003         let mut result = Vec::new();
1004
1005         for ast_bound in ast_bounds {
1006             if let Some(trait_ref) = ast_bound.trait_ref()
1007                 && let Some(trait_did) = trait_ref.trait_def_id()
1008                 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1009             {
1010                 result.push(ast_bound.clone());
1011             }
1012         }
1013
1014         self.compute_bounds_inner(param_ty, &result)
1015     }
1016
1017     fn compute_bounds_inner(
1018         &self,
1019         param_ty: Ty<'tcx>,
1020         ast_bounds: &[hir::GenericBound<'_>],
1021     ) -> Bounds<'tcx> {
1022         let mut bounds = Bounds::default();
1023
1024         self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1025         debug!(?bounds);
1026
1027         bounds
1028     }
1029
1030     /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1031     /// onto `bounds`.
1032     ///
1033     /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1034     /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1035     /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1036     #[instrument(level = "debug", skip(self, bounds, speculative, dup_bindings, path_span))]
1037     fn add_predicates_for_ast_type_binding(
1038         &self,
1039         hir_ref_id: hir::HirId,
1040         trait_ref: ty::PolyTraitRef<'tcx>,
1041         binding: &ConvertedBinding<'_, 'tcx>,
1042         bounds: &mut Bounds<'tcx>,
1043         speculative: bool,
1044         dup_bindings: &mut FxHashMap<DefId, Span>,
1045         path_span: Span,
1046         constness: ty::BoundConstness,
1047     ) -> Result<(), ErrorGuaranteed> {
1048         // Given something like `U: SomeTrait<T = X>`, we want to produce a
1049         // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1050         // subtle in the event that `T` is defined in a supertrait of
1051         // `SomeTrait`, because in that case we need to upcast.
1052         //
1053         // That is, consider this case:
1054         //
1055         // ```
1056         // trait SubTrait: SuperTrait<i32> { }
1057         // trait SuperTrait<A> { type T; }
1058         //
1059         // ... B: SubTrait<T = foo> ...
1060         // ```
1061         //
1062         // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1063
1064         let tcx = self.tcx();
1065
1066         let candidate =
1067             if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1068                 // Simple case: X is defined in the current trait.
1069                 trait_ref
1070             } else {
1071                 // Otherwise, we have to walk through the supertraits to find
1072                 // those that do.
1073                 self.one_bound_for_assoc_type(
1074                     || traits::supertraits(tcx, trait_ref),
1075                     || trait_ref.print_only_trait_path().to_string(),
1076                     binding.item_name,
1077                     path_span,
1078                     || match binding.kind {
1079                         ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1080                         _ => None,
1081                     },
1082                 )?
1083             };
1084
1085         let (assoc_ident, def_scope) =
1086             tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1087
1088         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1089         // of calling `filter_by_name_and_kind`.
1090         let find_item_of_kind = |kind| {
1091             tcx.associated_items(candidate.def_id())
1092                 .filter_by_name_unhygienic(assoc_ident.name)
1093                 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1094         };
1095         let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1096             .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1097             .expect("missing associated type");
1098
1099         if !assoc_item.visibility(tcx).is_accessible_from(def_scope, tcx) {
1100             tcx.sess
1101                 .struct_span_err(
1102                     binding.span,
1103                     &format!("{} `{}` is private", assoc_item.kind, binding.item_name),
1104                 )
1105                 .span_label(binding.span, &format!("private {}", assoc_item.kind))
1106                 .emit();
1107         }
1108         tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1109
1110         if !speculative {
1111             dup_bindings
1112                 .entry(assoc_item.def_id)
1113                 .and_modify(|prev_span| {
1114                     self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1115                         span: binding.span,
1116                         prev_span: *prev_span,
1117                         item_name: binding.item_name,
1118                         def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
1119                     });
1120                 })
1121                 .or_insert(binding.span);
1122         }
1123
1124         // Include substitutions for generic parameters of associated types
1125         let projection_ty = candidate.map_bound(|trait_ref| {
1126             let ident = Ident::new(assoc_item.name, binding.item_name.span);
1127             let item_segment = hir::PathSegment {
1128                 ident,
1129                 hir_id: binding.hir_id,
1130                 res: Res::Err,
1131                 args: Some(binding.gen_args),
1132                 infer_args: false,
1133             };
1134
1135             let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1136                 path_span,
1137                 assoc_item.def_id,
1138                 &item_segment,
1139                 trait_ref.substs,
1140             );
1141
1142             debug!(?substs_trait_ref_and_assoc_item);
1143
1144             ty::ProjectionTy {
1145                 item_def_id: assoc_item.def_id,
1146                 substs: substs_trait_ref_and_assoc_item,
1147             }
1148         });
1149
1150         if !speculative {
1151             // Find any late-bound regions declared in `ty` that are not
1152             // declared in the trait-ref or assoc_item. These are not well-formed.
1153             //
1154             // Example:
1155             //
1156             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1157             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1158             if let ConvertedBindingKind::Equality(ty) = binding.kind {
1159                 let late_bound_in_trait_ref =
1160                     tcx.collect_constrained_late_bound_regions(&projection_ty);
1161                 let late_bound_in_ty =
1162                     tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1163                 debug!(?late_bound_in_trait_ref);
1164                 debug!(?late_bound_in_ty);
1165
1166                 // FIXME: point at the type params that don't have appropriate lifetimes:
1167                 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1168                 //                         ----  ----     ^^^^^^^
1169                 self.validate_late_bound_regions(
1170                     late_bound_in_trait_ref,
1171                     late_bound_in_ty,
1172                     |br_name| {
1173                         struct_span_err!(
1174                             tcx.sess,
1175                             binding.span,
1176                             E0582,
1177                             "binding for associated type `{}` references {}, \
1178                              which does not appear in the trait input types",
1179                             binding.item_name,
1180                             br_name
1181                         )
1182                     },
1183                 );
1184             }
1185         }
1186
1187         match binding.kind {
1188             ConvertedBindingKind::Equality(mut term) => {
1189                 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1190                 // the "projection predicate" for:
1191                 //
1192                 // `<T as Iterator>::Item = u32`
1193                 let assoc_item_def_id = projection_ty.skip_binder().item_def_id;
1194                 let def_kind = tcx.def_kind(assoc_item_def_id);
1195                 match (def_kind, term.unpack()) {
1196                     (hir::def::DefKind::AssocTy, ty::TermKind::Ty(_))
1197                     | (hir::def::DefKind::AssocConst, ty::TermKind::Const(_)) => (),
1198                     (_, _) => {
1199                         let got = if let Some(_) = term.ty() { "type" } else { "constant" };
1200                         let expected = def_kind.descr(assoc_item_def_id);
1201                         tcx.sess
1202                             .struct_span_err(
1203                                 binding.span,
1204                                 &format!("expected {expected} bound, found {got}"),
1205                             )
1206                             .span_note(
1207                                 tcx.def_span(assoc_item_def_id),
1208                                 &format!("{expected} defined here"),
1209                             )
1210                             .emit();
1211                         term = match def_kind {
1212                             hir::def::DefKind::AssocTy => tcx.ty_error().into(),
1213                             hir::def::DefKind::AssocConst => tcx
1214                                 .const_error(
1215                                     tcx.bound_type_of(assoc_item_def_id)
1216                                         .subst(tcx, projection_ty.skip_binder().substs),
1217                                 )
1218                                 .into(),
1219                             _ => unreachable!(),
1220                         };
1221                     }
1222                 }
1223                 bounds.projection_bounds.push((
1224                     projection_ty.map_bound(|projection_ty| ty::ProjectionPredicate {
1225                         projection_ty,
1226                         term: term,
1227                     }),
1228                     binding.span,
1229                 ));
1230             }
1231             ConvertedBindingKind::Constraint(ast_bounds) => {
1232                 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1233                 //
1234                 // `<T as Iterator>::Item: Debug`
1235                 //
1236                 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1237                 // parameter to have a skipped binder.
1238                 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1239                 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1240             }
1241         }
1242         Ok(())
1243     }
1244
1245     fn ast_path_to_ty(
1246         &self,
1247         span: Span,
1248         did: DefId,
1249         item_segment: &hir::PathSegment<'_>,
1250     ) -> Ty<'tcx> {
1251         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1252         self.normalize_ty(
1253             span,
1254             EarlyBinder(self.tcx().at(span).type_of(did)).subst(self.tcx(), substs),
1255         )
1256     }
1257
1258     fn conv_object_ty_poly_trait_ref(
1259         &self,
1260         span: Span,
1261         trait_bounds: &[hir::PolyTraitRef<'_>],
1262         lifetime: &hir::Lifetime,
1263         borrowed: bool,
1264         representation: DynKind,
1265     ) -> Ty<'tcx> {
1266         let tcx = self.tcx();
1267
1268         let mut bounds = Bounds::default();
1269         let mut potential_assoc_types = Vec::new();
1270         let dummy_self = self.tcx().types.trait_object_dummy_self;
1271         for trait_bound in trait_bounds.iter().rev() {
1272             if let GenericArgCountResult {
1273                 correct:
1274                     Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1275                 ..
1276             } = self.instantiate_poly_trait_ref(
1277                 &trait_bound.trait_ref,
1278                 trait_bound.span,
1279                 ty::BoundConstness::NotConst,
1280                 dummy_self,
1281                 &mut bounds,
1282                 false,
1283             ) {
1284                 potential_assoc_types.extend(cur_potential_assoc_types);
1285             }
1286         }
1287
1288         // Expand trait aliases recursively and check that only one regular (non-auto) trait
1289         // is used and no 'maybe' bounds are used.
1290         let expanded_traits =
1291             traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1292         let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits
1293             .filter(|i| i.trait_ref().self_ty().skip_binder() == dummy_self)
1294             .partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1295         if regular_traits.len() > 1 {
1296             let first_trait = &regular_traits[0];
1297             let additional_trait = &regular_traits[1];
1298             let mut err = struct_span_err!(
1299                 tcx.sess,
1300                 additional_trait.bottom().1,
1301                 E0225,
1302                 "only auto traits can be used as additional traits in a trait object"
1303             );
1304             additional_trait.label_with_exp_info(
1305                 &mut err,
1306                 "additional non-auto trait",
1307                 "additional use",
1308             );
1309             first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1310             err.help(&format!(
1311                 "consider creating a new trait with all of these as supertraits and using that \
1312                  trait here instead: `trait NewTrait: {} {{}}`",
1313                 regular_traits
1314                     .iter()
1315                     .map(|t| t.trait_ref().print_only_trait_path().to_string())
1316                     .collect::<Vec<_>>()
1317                     .join(" + "),
1318             ));
1319             err.note(
1320                 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1321                  for more information on them, visit \
1322                  <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1323             );
1324             err.emit();
1325         }
1326
1327         if regular_traits.is_empty() && auto_traits.is_empty() {
1328             let trait_alias_span = bounds
1329                 .trait_bounds
1330                 .iter()
1331                 .map(|&(trait_ref, _, _)| trait_ref.def_id())
1332                 .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
1333                 .map(|trait_ref| tcx.def_span(trait_ref));
1334             tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
1335             return tcx.ty_error();
1336         }
1337
1338         // Check that there are no gross object safety violations;
1339         // most importantly, that the supertraits don't contain `Self`,
1340         // to avoid ICEs.
1341         for item in &regular_traits {
1342             let object_safety_violations =
1343                 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1344             if !object_safety_violations.is_empty() {
1345                 report_object_safety_error(
1346                     tcx,
1347                     span,
1348                     item.trait_ref().def_id(),
1349                     &object_safety_violations,
1350                 )
1351                 .emit();
1352                 return tcx.ty_error();
1353             }
1354         }
1355
1356         // Use a `BTreeSet` to keep output in a more consistent order.
1357         let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1358
1359         let regular_traits_refs_spans = bounds
1360             .trait_bounds
1361             .into_iter()
1362             .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1363
1364         for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1365             assert_eq!(constness, ty::BoundConstness::NotConst);
1366
1367             for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1368                 debug!(
1369                     "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1370                     obligation.predicate
1371                 );
1372
1373                 let bound_predicate = obligation.predicate.kind();
1374                 match bound_predicate.skip_binder() {
1375                     ty::PredicateKind::Trait(pred) => {
1376                         let pred = bound_predicate.rebind(pred);
1377                         associated_types.entry(span).or_default().extend(
1378                             tcx.associated_items(pred.def_id())
1379                                 .in_definition_order()
1380                                 .filter(|item| item.kind == ty::AssocKind::Type)
1381                                 .map(|item| item.def_id),
1382                         );
1383                     }
1384                     ty::PredicateKind::Projection(pred) => {
1385                         let pred = bound_predicate.rebind(pred);
1386                         // A `Self` within the original bound will be substituted with a
1387                         // `trait_object_dummy_self`, so check for that.
1388                         let references_self = match pred.skip_binder().term.unpack() {
1389                             ty::TermKind::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1390                             ty::TermKind::Const(c) => {
1391                                 c.ty().walk().any(|arg| arg == dummy_self.into())
1392                             }
1393                         };
1394
1395                         // If the projection output contains `Self`, force the user to
1396                         // elaborate it explicitly to avoid a lot of complexity.
1397                         //
1398                         // The "classically useful" case is the following:
1399                         // ```
1400                         //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1401                         //         type MyOutput;
1402                         //     }
1403                         // ```
1404                         //
1405                         // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1406                         // but actually supporting that would "expand" to an infinitely-long type
1407                         // `fix $ Ï„ â†’ dyn MyTrait<MyOutput = X, Output = <Ï„ as MyTrait>::MyOutput`.
1408                         //
1409                         // Instead, we force the user to write
1410                         // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1411                         // the discussion in #56288 for alternatives.
1412                         if !references_self {
1413                             // Include projections defined on supertraits.
1414                             bounds.projection_bounds.push((pred, span));
1415                         }
1416                     }
1417                     _ => (),
1418                 }
1419             }
1420         }
1421
1422         for (projection_bound, _) in &bounds.projection_bounds {
1423             for def_ids in associated_types.values_mut() {
1424                 def_ids.remove(&projection_bound.projection_def_id());
1425             }
1426         }
1427
1428         self.complain_about_missing_associated_types(
1429             associated_types,
1430             potential_assoc_types,
1431             trait_bounds,
1432         );
1433
1434         // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1435         // `dyn Trait + Send`.
1436         // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1437         // the bounds
1438         let mut duplicates = FxHashSet::default();
1439         auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1440         debug!("regular_traits: {:?}", regular_traits);
1441         debug!("auto_traits: {:?}", auto_traits);
1442
1443         // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1444         let existential_trait_refs = regular_traits.iter().map(|i| {
1445             i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1446                 assert_eq!(trait_ref.self_ty(), dummy_self);
1447
1448                 // Verify that `dummy_self` did not leak inside default type parameters.  This
1449                 // could not be done at path creation, since we need to see through trait aliases.
1450                 let mut missing_type_params = vec![];
1451                 let mut references_self = false;
1452                 let generics = tcx.generics_of(trait_ref.def_id);
1453                 let substs: Vec<_> = trait_ref
1454                     .substs
1455                     .iter()
1456                     .enumerate()
1457                     .skip(1) // Remove `Self` for `ExistentialPredicate`.
1458                     .map(|(index, arg)| {
1459                         if arg == dummy_self.into() {
1460                             let param = &generics.params[index];
1461                             missing_type_params.push(param.name);
1462                             return tcx.ty_error().into();
1463                         } else if arg.walk().any(|arg| arg == dummy_self.into()) {
1464                             references_self = true;
1465                             return tcx.ty_error().into();
1466                         }
1467                         arg
1468                     })
1469                     .collect();
1470                 let substs = tcx.intern_substs(&substs[..]);
1471
1472                 let span = i.bottom().1;
1473                 let empty_generic_args = trait_bounds.iter().any(|hir_bound| {
1474                     hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
1475                         && hir_bound.span.contains(span)
1476                 });
1477                 self.complain_about_missing_type_params(
1478                     missing_type_params,
1479                     trait_ref.def_id,
1480                     span,
1481                     empty_generic_args,
1482                 );
1483
1484                 if references_self {
1485                     let def_id = i.bottom().0.def_id();
1486                     let mut err = struct_span_err!(
1487                         tcx.sess,
1488                         i.bottom().1,
1489                         E0038,
1490                         "the {} `{}` cannot be made into an object",
1491                         tcx.def_kind(def_id).descr(def_id),
1492                         tcx.item_name(def_id),
1493                     );
1494                     err.note(
1495                         rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
1496                             .error_msg(),
1497                     );
1498                     err.emit();
1499                 }
1500
1501                 ty::ExistentialTraitRef { def_id: trait_ref.def_id, substs }
1502             })
1503         });
1504
1505         let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1506             bound.map_bound(|mut b| {
1507                 assert_eq!(b.projection_ty.self_ty(), dummy_self);
1508
1509                 // Like for trait refs, verify that `dummy_self` did not leak inside default type
1510                 // parameters.
1511                 let references_self = b.projection_ty.substs.iter().skip(1).any(|arg| {
1512                     if arg.walk().any(|arg| arg == dummy_self.into()) {
1513                         return true;
1514                     }
1515                     false
1516                 });
1517                 if references_self {
1518                     tcx.sess
1519                         .delay_span_bug(span, "trait object projection bounds reference `Self`");
1520                     let substs: Vec<_> = b
1521                         .projection_ty
1522                         .substs
1523                         .iter()
1524                         .map(|arg| {
1525                             if arg.walk().any(|arg| arg == dummy_self.into()) {
1526                                 return tcx.ty_error().into();
1527                             }
1528                             arg
1529                         })
1530                         .collect();
1531                     b.projection_ty.substs = tcx.intern_substs(&substs[..]);
1532                 }
1533
1534                 ty::ExistentialProjection::erase_self_ty(tcx, b)
1535             })
1536         });
1537
1538         let regular_trait_predicates = existential_trait_refs
1539             .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1540         let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1541             ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1542         });
1543         // N.b. principal, projections, auto traits
1544         // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1545         let mut v = regular_trait_predicates
1546             .chain(
1547                 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1548             )
1549             .chain(auto_trait_predicates)
1550             .collect::<SmallVec<[_; 8]>>();
1551         v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1552         v.dedup();
1553         let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1554
1555         // Use explicitly-specified region bound.
1556         let region_bound = if !lifetime.is_elided() {
1557             self.ast_region_to_region(lifetime, None)
1558         } else {
1559             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1560                 if tcx.named_region(lifetime.hir_id).is_some() {
1561                     self.ast_region_to_region(lifetime, None)
1562                 } else {
1563                     self.re_infer(None, span).unwrap_or_else(|| {
1564                         let mut err = struct_span_err!(
1565                             tcx.sess,
1566                             span,
1567                             E0228,
1568                             "the lifetime bound for this object type cannot be deduced \
1569                              from context; please supply an explicit bound"
1570                         );
1571                         if borrowed {
1572                             // We will have already emitted an error E0106 complaining about a
1573                             // missing named lifetime in `&dyn Trait`, so we elide this one.
1574                             err.delay_as_bug();
1575                         } else {
1576                             err.emit();
1577                         }
1578                         tcx.lifetimes.re_static
1579                     })
1580                 }
1581             })
1582         };
1583         debug!("region_bound: {:?}", region_bound);
1584
1585         let ty = tcx.mk_dynamic(existential_predicates, region_bound, representation);
1586         debug!("trait_object_type: {:?}", ty);
1587         ty
1588     }
1589
1590     fn report_ambiguous_associated_type(
1591         &self,
1592         span: Span,
1593         type_str: &str,
1594         trait_str: &str,
1595         name: Symbol,
1596     ) -> ErrorGuaranteed {
1597         let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1598         if self
1599             .tcx()
1600             .resolutions(())
1601             .confused_type_with_std_module
1602             .keys()
1603             .any(|full_span| full_span.contains(span))
1604         {
1605             err.span_suggestion(
1606                 span.shrink_to_lo(),
1607                 "you are looking for the module in `std`, not the primitive type",
1608                 "std::",
1609                 Applicability::MachineApplicable,
1610             );
1611         } else {
1612             err.span_suggestion(
1613                 span,
1614                 "use fully-qualified syntax",
1615                 format!("<{} as {}>::{}", type_str, trait_str, name),
1616                 Applicability::HasPlaceholders,
1617             );
1618         }
1619         err.emit()
1620     }
1621
1622     // Search for a bound on a type parameter which includes the associated item
1623     // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1624     // This function will fail if there are no suitable bounds or there is
1625     // any ambiguity.
1626     fn find_bound_for_assoc_item(
1627         &self,
1628         ty_param_def_id: LocalDefId,
1629         assoc_name: Ident,
1630         span: Span,
1631     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1632         let tcx = self.tcx();
1633
1634         debug!(
1635             "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1636             ty_param_def_id, assoc_name, span,
1637         );
1638
1639         let predicates = &self
1640             .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1641             .predicates;
1642
1643         debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1644
1645         let param_name = tcx.hir().ty_param_name(ty_param_def_id);
1646         self.one_bound_for_assoc_type(
1647             || {
1648                 traits::transitive_bounds_that_define_assoc_type(
1649                     tcx,
1650                     predicates.iter().filter_map(|(p, _)| {
1651                         Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1652                     }),
1653                     assoc_name,
1654                 )
1655             },
1656             || param_name.to_string(),
1657             assoc_name,
1658             span,
1659             || None,
1660         )
1661     }
1662
1663     // Checks that `bounds` contains exactly one element and reports appropriate
1664     // errors otherwise.
1665     #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, is_equality), ret)]
1666     fn one_bound_for_assoc_type<I>(
1667         &self,
1668         all_candidates: impl Fn() -> I,
1669         ty_param_name: impl Fn() -> String,
1670         assoc_name: Ident,
1671         span: Span,
1672         is_equality: impl Fn() -> Option<String>,
1673     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1674     where
1675         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1676     {
1677         let mut matching_candidates = all_candidates()
1678             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1679         let mut const_candidates = all_candidates()
1680             .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
1681
1682         let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1683             (Some(bound), _) => (bound, matching_candidates.next()),
1684             (None, Some(bound)) => (bound, const_candidates.next()),
1685             (None, None) => {
1686                 let reported = self.complain_about_assoc_type_not_found(
1687                     all_candidates,
1688                     &ty_param_name(),
1689                     assoc_name,
1690                     span,
1691                 );
1692                 return Err(reported);
1693             }
1694         };
1695         debug!(?bound);
1696
1697         if let Some(bound2) = next_cand {
1698             debug!(?bound2);
1699
1700             let is_equality = is_equality();
1701             let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1702             let mut err = if is_equality.is_some() {
1703                 // More specific Error Index entry.
1704                 struct_span_err!(
1705                     self.tcx().sess,
1706                     span,
1707                     E0222,
1708                     "ambiguous associated type `{}` in bounds of `{}`",
1709                     assoc_name,
1710                     ty_param_name()
1711                 )
1712             } else {
1713                 struct_span_err!(
1714                     self.tcx().sess,
1715                     span,
1716                     E0221,
1717                     "ambiguous associated type `{}` in bounds of `{}`",
1718                     assoc_name,
1719                     ty_param_name()
1720                 )
1721             };
1722             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1723
1724             let mut where_bounds = vec![];
1725             for bound in bounds {
1726                 let bound_id = bound.def_id();
1727                 let bound_span = self
1728                     .tcx()
1729                     .associated_items(bound_id)
1730                     .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1731                     .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1732
1733                 if let Some(bound_span) = bound_span {
1734                     err.span_label(
1735                         bound_span,
1736                         format!(
1737                             "ambiguous `{}` from `{}`",
1738                             assoc_name,
1739                             bound.print_only_trait_path(),
1740                         ),
1741                     );
1742                     if let Some(constraint) = &is_equality {
1743                         where_bounds.push(format!(
1744                             "        T: {trait}::{assoc} = {constraint}",
1745                             trait=bound.print_only_trait_path(),
1746                             assoc=assoc_name,
1747                             constraint=constraint,
1748                         ));
1749                     } else {
1750                         err.span_suggestion_verbose(
1751                             span.with_hi(assoc_name.span.lo()),
1752                             "use fully qualified syntax to disambiguate",
1753                             format!(
1754                                 "<{} as {}>::",
1755                                 ty_param_name(),
1756                                 bound.print_only_trait_path(),
1757                             ),
1758                             Applicability::MaybeIncorrect,
1759                         );
1760                     }
1761                 } else {
1762                     err.note(&format!(
1763                         "associated type `{}` could derive from `{}`",
1764                         ty_param_name(),
1765                         bound.print_only_trait_path(),
1766                     ));
1767                 }
1768             }
1769             if !where_bounds.is_empty() {
1770                 err.help(&format!(
1771                     "consider introducing a new type parameter `T` and adding `where` constraints:\
1772                      \n    where\n        T: {},\n{}",
1773                     ty_param_name(),
1774                     where_bounds.join(",\n"),
1775                 ));
1776             }
1777             let reported = err.emit();
1778             if !where_bounds.is_empty() {
1779                 return Err(reported);
1780             }
1781         }
1782
1783         Ok(bound)
1784     }
1785
1786     // Create a type from a path to an associated type.
1787     // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1788     // and item_segment is the path segment for `D`. We return a type and a def for
1789     // the whole path.
1790     // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1791     // parameter or `Self`.
1792     // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1793     // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1794     #[instrument(level = "debug", skip(self, hir_ref_id, span, qself, assoc_segment), fields(assoc_ident=?assoc_segment.ident), ret)]
1795     pub fn associated_path_to_ty(
1796         &self,
1797         hir_ref_id: hir::HirId,
1798         span: Span,
1799         qself_ty: Ty<'tcx>,
1800         qself: &hir::Ty<'_>,
1801         assoc_segment: &hir::PathSegment<'_>,
1802         permit_variants: bool,
1803     ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1804         let tcx = self.tcx();
1805         let assoc_ident = assoc_segment.ident;
1806         let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
1807             path.res
1808         } else {
1809             Res::Err
1810         };
1811
1812         // Check if we have an enum variant.
1813         let mut variant_resolution = None;
1814         if let ty::Adt(adt_def, _) = qself_ty.kind() {
1815             if adt_def.is_enum() {
1816                 let variant_def = adt_def
1817                     .variants()
1818                     .iter()
1819                     .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
1820                 if let Some(variant_def) = variant_def {
1821                     if permit_variants {
1822                         tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1823                         self.prohibit_generics(slice::from_ref(assoc_segment).iter(), |err| {
1824                             err.note("enum variants can't have type parameters");
1825                             let type_name = tcx.item_name(adt_def.did());
1826                             let msg = format!(
1827                                 "you might have meant to specity type parameters on enum \
1828                                  `{type_name}`"
1829                             );
1830                             let Some(args) = assoc_segment.args else { return; };
1831                             // Get the span of the generics args *including* the leading `::`.
1832                             let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext);
1833                             if tcx.generics_of(adt_def.did()).count() == 0 {
1834                                 // FIXME(estebank): we could also verify that the arguments being
1835                                 // work for the `enum`, instead of just looking if it takes *any*.
1836                                 err.span_suggestion_verbose(
1837                                     args_span,
1838                                     &format!("{type_name} doesn't have generic parameters"),
1839                                     "",
1840                                     Applicability::MachineApplicable,
1841                                 );
1842                                 return;
1843                             }
1844                             let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1845                                 err.note(&msg);
1846                                 return;
1847                             };
1848                             let (qself_sugg_span, is_self) = if let hir::TyKind::Path(
1849                                 hir::QPath::Resolved(_, ref path)
1850                             ) = qself.kind {
1851                                 // If the path segment already has type params, we want to overwrite
1852                                 // them.
1853                                 match &path.segments[..] {
1854                                     // `segment` is the previous to last element on the path,
1855                                     // which would normally be the `enum` itself, while the last
1856                                     // `_` `PathSegment` corresponds to the variant.
1857                                     [.., hir::PathSegment {
1858                                         ident,
1859                                         args,
1860                                         res: Res::Def(DefKind::Enum, _),
1861                                         ..
1862                                     }, _] => (
1863                                         // We need to include the `::` in `Type::Variant::<Args>`
1864                                         // to point the span to `::<Args>`, not just `<Args>`.
1865                                         ident.span.shrink_to_hi().to(args.map_or(
1866                                             ident.span.shrink_to_hi(),
1867                                             |a| a.span_ext)),
1868                                         false,
1869                                     ),
1870                                     [segment] => (
1871                                         // We need to include the `::` in `Type::Variant::<Args>`
1872                                         // to point the span to `::<Args>`, not just `<Args>`.
1873                                         segment.ident.span.shrink_to_hi().to(segment.args.map_or(
1874                                             segment.ident.span.shrink_to_hi(),
1875                                             |a| a.span_ext)),
1876                                         kw::SelfUpper == segment.ident.name,
1877                                     ),
1878                                     _ => {
1879                                         err.note(&msg);
1880                                         return;
1881                                     }
1882                                 }
1883                             } else {
1884                                 err.note(&msg);
1885                                 return;
1886                             };
1887                             let suggestion = vec![
1888                                 if is_self {
1889                                     // Account for people writing `Self::Variant::<Args>`, where
1890                                     // `Self` is the enum, and suggest replacing `Self` with the
1891                                     // appropriate type: `Type::<Args>::Variant`.
1892                                     (qself.span, format!("{type_name}{snippet}"))
1893                                 } else {
1894                                     (qself_sugg_span, snippet)
1895                                 },
1896                                 (args_span, String::new()),
1897                             ];
1898                             err.multipart_suggestion_verbose(
1899                                 &msg,
1900                                 suggestion,
1901                                 Applicability::MaybeIncorrect,
1902                             );
1903                         });
1904                         return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1905                     } else {
1906                         variant_resolution = Some(variant_def.def_id);
1907                     }
1908                 }
1909             }
1910         }
1911
1912         // Find the type of the associated item, and the trait where the associated
1913         // item is declared.
1914         let bound = match (&qself_ty.kind(), qself_res) {
1915             (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1916                 // `Self` in an impl of a trait -- we have a concrete self type and a
1917                 // trait reference.
1918                 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1919                     // A cycle error occurred, most likely.
1920                     let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
1921                     return Err(guar);
1922                 };
1923
1924                 self.one_bound_for_assoc_type(
1925                     || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1926                     || "Self".to_string(),
1927                     assoc_ident,
1928                     span,
1929                     || None,
1930                 )?
1931             }
1932             (
1933                 &ty::Param(_),
1934                 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1935             ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1936             _ => {
1937                 let reported = if variant_resolution.is_some() {
1938                     // Variant in type position
1939                     let msg = format!("expected type, found variant `{}`", assoc_ident);
1940                     tcx.sess.span_err(span, &msg)
1941                 } else if qself_ty.is_enum() {
1942                     let mut err = struct_span_err!(
1943                         tcx.sess,
1944                         assoc_ident.span,
1945                         E0599,
1946                         "no variant named `{}` found for enum `{}`",
1947                         assoc_ident,
1948                         qself_ty,
1949                     );
1950
1951                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1952                     if let Some(suggested_name) = find_best_match_for_name(
1953                         &adt_def
1954                             .variants()
1955                             .iter()
1956                             .map(|variant| variant.name)
1957                             .collect::<Vec<Symbol>>(),
1958                         assoc_ident.name,
1959                         None,
1960                     ) {
1961                         err.span_suggestion(
1962                             assoc_ident.span,
1963                             "there is a variant with a similar name",
1964                             suggested_name,
1965                             Applicability::MaybeIncorrect,
1966                         );
1967                     } else {
1968                         err.span_label(
1969                             assoc_ident.span,
1970                             format!("variant not found in `{}`", qself_ty),
1971                         );
1972                     }
1973
1974                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
1975                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1976                     }
1977
1978                     err.emit()
1979                 } else if let Some(reported) = qself_ty.error_reported() {
1980                     reported
1981                 } else {
1982                     // Don't print `TyErr` to the user.
1983                     self.report_ambiguous_associated_type(
1984                         span,
1985                         &qself_ty.to_string(),
1986                         "Trait",
1987                         assoc_ident.name,
1988                     )
1989                 };
1990                 return Err(reported);
1991             }
1992         };
1993
1994         let trait_did = bound.def_id();
1995         let (assoc_ident, def_scope) =
1996             tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1997
1998         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1999         // of calling `filter_by_name_and_kind`.
2000         let item = tcx.associated_items(trait_did).in_definition_order().find(|i| {
2001             i.kind.namespace() == Namespace::TypeNS
2002                 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
2003         });
2004         // Assume that if it's not matched, there must be a const defined with the same name
2005         // but it was used in a type position.
2006         let Some(item) = item else {
2007             let msg = format!("found associated const `{assoc_ident}` when type was expected");
2008             let guar = tcx.sess.struct_span_err(span, &msg).emit();
2009             return Err(guar);
2010         };
2011
2012         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2013         let ty = self.normalize_ty(span, ty);
2014
2015         let kind = DefKind::AssocTy;
2016         if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2017             let kind = kind.descr(item.def_id);
2018             let msg = format!("{} `{}` is private", kind, assoc_ident);
2019             tcx.sess
2020                 .struct_span_err(span, &msg)
2021                 .span_label(span, &format!("private {}", kind))
2022                 .emit();
2023         }
2024         tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
2025
2026         if let Some(variant_def_id) = variant_resolution {
2027             tcx.struct_span_lint_hir(
2028                 AMBIGUOUS_ASSOCIATED_ITEMS,
2029                 hir_ref_id,
2030                 span,
2031                 "ambiguous associated item",
2032                 |lint| {
2033                     let mut could_refer_to = |kind: DefKind, def_id, also| {
2034                         let note_msg = format!(
2035                             "`{}` could{} refer to the {} defined here",
2036                             assoc_ident,
2037                             also,
2038                             kind.descr(def_id)
2039                         );
2040                         lint.span_note(tcx.def_span(def_id), &note_msg);
2041                     };
2042
2043                     could_refer_to(DefKind::Variant, variant_def_id, "");
2044                     could_refer_to(kind, item.def_id, " also");
2045
2046                     lint.span_suggestion(
2047                         span,
2048                         "use fully-qualified syntax",
2049                         format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2050                         Applicability::MachineApplicable,
2051                     );
2052
2053                     lint
2054                 },
2055             );
2056         }
2057         Ok((ty, kind, item.def_id))
2058     }
2059
2060     fn qpath_to_ty(
2061         &self,
2062         span: Span,
2063         opt_self_ty: Option<Ty<'tcx>>,
2064         item_def_id: DefId,
2065         trait_segment: &hir::PathSegment<'_>,
2066         item_segment: &hir::PathSegment<'_>,
2067         constness: ty::BoundConstness,
2068     ) -> Ty<'tcx> {
2069         let tcx = self.tcx();
2070
2071         let trait_def_id = tcx.parent(item_def_id);
2072
2073         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2074
2075         let Some(self_ty) = opt_self_ty else {
2076             let path_str = tcx.def_path_str(trait_def_id);
2077
2078             let def_id = self.item_def_id();
2079
2080             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2081
2082             let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
2083                 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
2084
2085             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2086
2087             // If the trait in segment is the same as the trait defining the item,
2088             // use the `<Self as ..>` syntax in the error.
2089             let is_part_of_self_trait_constraints = def_id == trait_def_id;
2090             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2091
2092             let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2093                 "Self"
2094             } else {
2095                 "Type"
2096             };
2097
2098             self.report_ambiguous_associated_type(
2099                 span,
2100                 type_name,
2101                 &path_str,
2102                 item_segment.ident.name,
2103             );
2104             return tcx.ty_error();
2105         };
2106
2107         debug!("qpath_to_ty: self_type={:?}", self_ty);
2108
2109         let trait_ref = self.ast_path_to_mono_trait_ref(
2110             span,
2111             trait_def_id,
2112             self_ty,
2113             trait_segment,
2114             false,
2115             Some(constness),
2116         );
2117
2118         let item_substs = self.create_substs_for_associated_item(
2119             span,
2120             item_def_id,
2121             item_segment,
2122             trait_ref.substs,
2123         );
2124
2125         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2126
2127         self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2128     }
2129
2130     pub fn prohibit_generics<'a>(
2131         &self,
2132         segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2133         extend: impl Fn(&mut Diagnostic),
2134     ) -> bool {
2135         let args = segments.clone().flat_map(|segment| segment.args().args);
2136
2137         let (lt, ty, ct, inf) =
2138             args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2139                 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2140                 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2141                 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2142                 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2143             });
2144         let mut emitted = false;
2145         if lt || ty || ct || inf {
2146             let types_and_spans: Vec<_> = segments
2147                 .clone()
2148                 .flat_map(|segment| {
2149                     if segment.args().args.is_empty() {
2150                         None
2151                     } else {
2152                         Some((
2153                             match segment.res {
2154                                 Res::PrimTy(ty) => format!("{} `{}`", segment.res.descr(), ty.name()),
2155                                 Res::Def(_, def_id)
2156                                 if let Some(name) = self.tcx().opt_item_name(def_id) => {
2157                                     format!("{} `{name}`", segment.res.descr())
2158                                 }
2159                                 Res::Err => "this type".to_string(),
2160                                 _ => segment.res.descr().to_string(),
2161                             },
2162                             segment.ident.span,
2163                         ))
2164                     }
2165                 })
2166                 .collect();
2167             let this_type = match &types_and_spans[..] {
2168                 [.., _, (last, _)] => format!(
2169                     "{} and {last}",
2170                     types_and_spans[..types_and_spans.len() - 1]
2171                         .iter()
2172                         .map(|(x, _)| x.as_str())
2173                         .intersperse(&", ")
2174                         .collect::<String>()
2175                 ),
2176                 [(only, _)] => only.to_string(),
2177                 [] => "this type".to_string(),
2178             };
2179
2180             let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2181
2182             let mut kinds = Vec::with_capacity(4);
2183             if lt {
2184                 kinds.push("lifetime");
2185             }
2186             if ty {
2187                 kinds.push("type");
2188             }
2189             if ct {
2190                 kinds.push("const");
2191             }
2192             if inf {
2193                 kinds.push("generic");
2194             }
2195             let (kind, s) = match kinds[..] {
2196                 [.., _, last] => (
2197                     format!(
2198                         "{} and {last}",
2199                         kinds[..kinds.len() - 1]
2200                             .iter()
2201                             .map(|&x| x)
2202                             .intersperse(", ")
2203                             .collect::<String>()
2204                     ),
2205                     "s",
2206                 ),
2207                 [only] => (format!("{only}"), ""),
2208                 [] => unreachable!(),
2209             };
2210             let last_span = *arg_spans.last().unwrap();
2211             let span: MultiSpan = arg_spans.into();
2212             let mut err = struct_span_err!(
2213                 self.tcx().sess,
2214                 span,
2215                 E0109,
2216                 "{kind} arguments are not allowed on {this_type}",
2217             );
2218             err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2219             for (what, span) in types_and_spans {
2220                 err.span_label(span, format!("not allowed on {what}"));
2221             }
2222             extend(&mut err);
2223             err.emit();
2224             emitted = true;
2225         }
2226
2227         for segment in segments {
2228             // Only emit the first error to avoid overloading the user with error messages.
2229             if let Some(b) = segment.args().bindings.first() {
2230                 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
2231                 return true;
2232             }
2233         }
2234         emitted
2235     }
2236
2237     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2238     pub fn def_ids_for_value_path_segments(
2239         &self,
2240         segments: &[hir::PathSegment<'_>],
2241         self_ty: Option<Ty<'tcx>>,
2242         kind: DefKind,
2243         def_id: DefId,
2244     ) -> Vec<PathSeg> {
2245         // We need to extract the type parameters supplied by the user in
2246         // the path `path`. Due to the current setup, this is a bit of a
2247         // tricky-process; the problem is that resolve only tells us the
2248         // end-point of the path resolution, and not the intermediate steps.
2249         // Luckily, we can (at least for now) deduce the intermediate steps
2250         // just from the end-point.
2251         //
2252         // There are basically five cases to consider:
2253         //
2254         // 1. Reference to a constructor of a struct:
2255         //
2256         //        struct Foo<T>(...)
2257         //
2258         //    In this case, the parameters are declared in the type space.
2259         //
2260         // 2. Reference to a constructor of an enum variant:
2261         //
2262         //        enum E<T> { Foo(...) }
2263         //
2264         //    In this case, the parameters are defined in the type space,
2265         //    but may be specified either on the type or the variant.
2266         //
2267         // 3. Reference to a fn item or a free constant:
2268         //
2269         //        fn foo<T>() { }
2270         //
2271         //    In this case, the path will again always have the form
2272         //    `a::b::foo::<T>` where only the final segment should have
2273         //    type parameters. However, in this case, those parameters are
2274         //    declared on a value, and hence are in the `FnSpace`.
2275         //
2276         // 4. Reference to a method or an associated constant:
2277         //
2278         //        impl<A> SomeStruct<A> {
2279         //            fn foo<B>(...)
2280         //        }
2281         //
2282         //    Here we can have a path like
2283         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2284         //    may appear in two places. The penultimate segment,
2285         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2286         //    final segment, `foo::<B>` contains parameters in fn space.
2287         //
2288         // The first step then is to categorize the segments appropriately.
2289
2290         let tcx = self.tcx();
2291
2292         assert!(!segments.is_empty());
2293         let last = segments.len() - 1;
2294
2295         let mut path_segs = vec![];
2296
2297         match kind {
2298             // Case 1. Reference to a struct constructor.
2299             DefKind::Ctor(CtorOf::Struct, ..) => {
2300                 // Everything but the final segment should have no
2301                 // parameters at all.
2302                 let generics = tcx.generics_of(def_id);
2303                 // Variant and struct constructors use the
2304                 // generics of their parent type definition.
2305                 let generics_def_id = generics.parent.unwrap_or(def_id);
2306                 path_segs.push(PathSeg(generics_def_id, last));
2307             }
2308
2309             // Case 2. Reference to a variant constructor.
2310             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2311                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2312                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2313                     debug_assert!(adt_def.is_enum());
2314                     (adt_def.did(), last)
2315                 } else if last >= 1 && segments[last - 1].args.is_some() {
2316                     // Everything but the penultimate segment should have no
2317                     // parameters at all.
2318                     let mut def_id = def_id;
2319
2320                     // `DefKind::Ctor` -> `DefKind::Variant`
2321                     if let DefKind::Ctor(..) = kind {
2322                         def_id = tcx.parent(def_id);
2323                     }
2324
2325                     // `DefKind::Variant` -> `DefKind::Enum`
2326                     let enum_def_id = tcx.parent(def_id);
2327                     (enum_def_id, last - 1)
2328                 } else {
2329                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2330                     // instead of `Enum::Variant::<...>` form.
2331
2332                     // Everything but the final segment should have no
2333                     // parameters at all.
2334                     let generics = tcx.generics_of(def_id);
2335                     // Variant and struct constructors use the
2336                     // generics of their parent type definition.
2337                     (generics.parent.unwrap_or(def_id), last)
2338                 };
2339                 path_segs.push(PathSeg(generics_def_id, index));
2340             }
2341
2342             // Case 3. Reference to a top-level value.
2343             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2344                 path_segs.push(PathSeg(def_id, last));
2345             }
2346
2347             // Case 4. Reference to a method or associated const.
2348             DefKind::AssocFn | DefKind::AssocConst => {
2349                 if segments.len() >= 2 {
2350                     let generics = tcx.generics_of(def_id);
2351                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2352                 }
2353                 path_segs.push(PathSeg(def_id, last));
2354             }
2355
2356             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2357         }
2358
2359         debug!("path_segs = {:?}", path_segs);
2360
2361         path_segs
2362     }
2363
2364     // Check a type `Path` and convert it to a `Ty`.
2365     pub fn res_to_ty(
2366         &self,
2367         opt_self_ty: Option<Ty<'tcx>>,
2368         path: &hir::Path<'_>,
2369         permit_variants: bool,
2370     ) -> Ty<'tcx> {
2371         let tcx = self.tcx();
2372
2373         debug!(
2374             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2375             path.res, opt_self_ty, path.segments
2376         );
2377
2378         let span = path.span;
2379         match path.res {
2380             Res::Def(DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder, did) => {
2381                 // Check for desugared `impl Trait`.
2382                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2383                 let item_segment = path.segments.split_last().unwrap();
2384                 self.prohibit_generics(item_segment.1.iter(), |err| {
2385                     err.note("`impl Trait` types can't have type parameters");
2386                 });
2387                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2388                 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2389             }
2390             Res::Def(
2391                 DefKind::Enum
2392                 | DefKind::TyAlias
2393                 | DefKind::Struct
2394                 | DefKind::Union
2395                 | DefKind::ForeignTy,
2396                 did,
2397             ) => {
2398                 assert_eq!(opt_self_ty, None);
2399                 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
2400                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2401             }
2402             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2403                 // Convert "variant type" as if it were a real type.
2404                 // The resulting `Ty` is type of the variant's enum for now.
2405                 assert_eq!(opt_self_ty, None);
2406
2407                 let path_segs =
2408                     self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
2409                 let generic_segs: FxHashSet<_> =
2410                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2411                 self.prohibit_generics(
2412                     path.segments.iter().enumerate().filter_map(|(index, seg)| {
2413                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2414                     }),
2415                     |err| {
2416                         err.note("enum variants can't have type parameters");
2417                     },
2418                 );
2419
2420                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2421                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2422             }
2423             Res::Def(DefKind::TyParam, def_id) => {
2424                 assert_eq!(opt_self_ty, None);
2425                 self.prohibit_generics(path.segments.iter(), |err| {
2426                     if let Some(span) = tcx.def_ident_span(def_id) {
2427                         let name = tcx.item_name(def_id);
2428                         err.span_note(span, &format!("type parameter `{name}` defined here"));
2429                     }
2430                 });
2431
2432                 let def_id = def_id.expect_local();
2433                 let item_def_id = tcx.hir().ty_param_owner(def_id);
2434                 let generics = tcx.generics_of(item_def_id);
2435                 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2436                 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2437             }
2438             Res::SelfTyParam { .. } => {
2439                 // `Self` in trait or type alias.
2440                 assert_eq!(opt_self_ty, None);
2441                 self.prohibit_generics(path.segments.iter(), |err| {
2442                     if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2443                         err.span_suggestion_verbose(
2444                             ident.span.shrink_to_hi().to(args.span_ext),
2445                             "the `Self` type doesn't accept type parameters",
2446                             "",
2447                             Applicability::MaybeIncorrect,
2448                         );
2449                     }
2450                 });
2451                 tcx.types.self_param
2452             }
2453             Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
2454                 // `Self` in impl (we know the concrete type).
2455                 assert_eq!(opt_self_ty, None);
2456                 // Try to evaluate any array length constants.
2457                 let ty = tcx.at(span).type_of(def_id);
2458                 let span_of_impl = tcx.span_of_impl(def_id);
2459                 self.prohibit_generics(path.segments.iter(), |err| {
2460                     let def_id = match *ty.kind() {
2461                         ty::Adt(self_def, _) => self_def.did(),
2462                         _ => return,
2463                     };
2464
2465                     let type_name = tcx.item_name(def_id);
2466                     let span_of_ty = tcx.def_ident_span(def_id);
2467                     let generics = tcx.generics_of(def_id).count();
2468
2469                     let msg = format!("`Self` is of type `{ty}`");
2470                     if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
2471                         let mut span: MultiSpan = vec![t_sp].into();
2472                         span.push_span_label(
2473                             i_sp,
2474                             &format!("`Self` is on type `{type_name}` in this `impl`"),
2475                         );
2476                         let mut postfix = "";
2477                         if generics == 0 {
2478                             postfix = ", which doesn't have generic parameters";
2479                         }
2480                         span.push_span_label(
2481                             t_sp,
2482                             &format!("`Self` corresponds to this type{postfix}"),
2483                         );
2484                         err.span_note(span, &msg);
2485                     } else {
2486                         err.note(&msg);
2487                     }
2488                     for segment in path.segments {
2489                         if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2490                             if generics == 0 {
2491                                 // FIXME(estebank): we could also verify that the arguments being
2492                                 // work for the `enum`, instead of just looking if it takes *any*.
2493                                 err.span_suggestion_verbose(
2494                                     segment.ident.span.shrink_to_hi().to(args.span_ext),
2495                                     "the `Self` type doesn't accept type parameters",
2496                                     "",
2497                                     Applicability::MachineApplicable,
2498                                 );
2499                                 return;
2500                             } else {
2501                                 err.span_suggestion_verbose(
2502                                     segment.ident.span,
2503                                     format!(
2504                                         "the `Self` type doesn't accept type parameters, use the \
2505                                         concrete type's name `{type_name}` instead if you want to \
2506                                         specify its type parameters"
2507                                     ),
2508                                     type_name,
2509                                     Applicability::MaybeIncorrect,
2510                                 );
2511                             }
2512                         }
2513                     }
2514                 });
2515                 // HACK(min_const_generics): Forbid generic `Self` types
2516                 // here as we can't easily do that during nameres.
2517                 //
2518                 // We do this before normalization as we otherwise allow
2519                 // ```rust
2520                 // trait AlwaysApplicable { type Assoc; }
2521                 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2522                 //
2523                 // trait BindsParam<T> {
2524                 //     type ArrayTy;
2525                 // }
2526                 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2527                 //    type ArrayTy = [u8; Self::MAX];
2528                 // }
2529                 // ```
2530                 // Note that the normalization happens in the param env of
2531                 // the anon const, which is empty. This is why the
2532                 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2533                 // this to compile if we were to normalize here.
2534                 if forbid_generic && ty.needs_subst() {
2535                     let mut err = tcx.sess.struct_span_err(
2536                         path.span,
2537                         "generic `Self` types are currently not permitted in anonymous constants",
2538                     );
2539                     if let Some(hir::Node::Item(&hir::Item {
2540                         kind: hir::ItemKind::Impl(ref impl_),
2541                         ..
2542                     })) = tcx.hir().get_if_local(def_id)
2543                     {
2544                         err.span_note(impl_.self_ty.span, "not a concrete type");
2545                     }
2546                     err.emit();
2547                     tcx.ty_error()
2548                 } else {
2549                     self.normalize_ty(span, ty)
2550                 }
2551             }
2552             Res::Def(DefKind::AssocTy, def_id) => {
2553                 debug_assert!(path.segments.len() >= 2);
2554                 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2555                 // HACK: until we support `<Type as ~const Trait>`, assume all of them are.
2556                 let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) {
2557                     ty::BoundConstness::ConstIfConst
2558                 } else {
2559                     ty::BoundConstness::NotConst
2560                 };
2561                 self.qpath_to_ty(
2562                     span,
2563                     opt_self_ty,
2564                     def_id,
2565                     &path.segments[path.segments.len() - 2],
2566                     path.segments.last().unwrap(),
2567                     constness,
2568                 )
2569             }
2570             Res::PrimTy(prim_ty) => {
2571                 assert_eq!(opt_self_ty, None);
2572                 self.prohibit_generics(path.segments.iter(), |err| {
2573                     let name = prim_ty.name_str();
2574                     for segment in path.segments {
2575                         if let Some(args) = segment.args {
2576                             err.span_suggestion_verbose(
2577                                 segment.ident.span.shrink_to_hi().to(args.span_ext),
2578                                 &format!("primitive type `{name}` doesn't have generic parameters"),
2579                                 "",
2580                                 Applicability::MaybeIncorrect,
2581                             );
2582                         }
2583                     }
2584                 });
2585                 match prim_ty {
2586                     hir::PrimTy::Bool => tcx.types.bool,
2587                     hir::PrimTy::Char => tcx.types.char,
2588                     hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2589                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2590                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2591                     hir::PrimTy::Str => tcx.types.str_,
2592                 }
2593             }
2594             Res::Err => {
2595                 self.set_tainted_by_errors();
2596                 self.tcx().ty_error()
2597             }
2598             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2599         }
2600     }
2601
2602     /// Parses the programmer's textual representation of a type into our
2603     /// internal notion of a type.
2604     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2605         self.ast_ty_to_ty_inner(ast_ty, false, false)
2606     }
2607
2608     /// Parses the programmer's textual representation of a type into our
2609     /// internal notion of a type.  This is meant to be used within a path.
2610     pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2611         self.ast_ty_to_ty_inner(ast_ty, false, true)
2612     }
2613
2614     /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2615     /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2616     #[instrument(level = "debug", skip(self), ret)]
2617     fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2618         let tcx = self.tcx();
2619
2620         let result_ty = match ast_ty.kind {
2621             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2622             hir::TyKind::Ptr(ref mt) => {
2623                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2624             }
2625             hir::TyKind::Rptr(ref region, ref mt) => {
2626                 let r = self.ast_region_to_region(region, None);
2627                 debug!(?r);
2628                 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2629                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2630             }
2631             hir::TyKind::Never => tcx.types.never,
2632             hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2633             hir::TyKind::BareFn(bf) => {
2634                 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2635
2636                 tcx.mk_fn_ptr(self.ty_of_fn(
2637                     ast_ty.hir_id,
2638                     bf.unsafety,
2639                     bf.abi,
2640                     bf.decl,
2641                     None,
2642                     Some(ast_ty),
2643                 ))
2644             }
2645             hir::TyKind::TraitObject(bounds, ref lifetime, repr) => {
2646                 self.maybe_lint_bare_trait(ast_ty, in_path);
2647                 let repr = match repr {
2648                     TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2649                     TraitObjectSyntax::DynStar => ty::DynStar,
2650                 };
2651                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr)
2652             }
2653             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2654                 debug!(?maybe_qself, ?path);
2655                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2656                 self.res_to_ty(opt_self_ty, path, false)
2657             }
2658             hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
2659                 let opaque_ty = tcx.hir().item(item_id);
2660                 let def_id = item_id.owner_id.to_def_id();
2661
2662                 match opaque_ty.kind {
2663                     hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2664                         self.impl_trait_ty_to_ty(def_id, lifetimes, origin, in_trait)
2665                     }
2666                     ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2667                 }
2668             }
2669             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2670                 debug!(?qself, ?segment);
2671                 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2672                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
2673                     .map(|(ty, _, _)| ty)
2674                     .unwrap_or_else(|_| tcx.ty_error())
2675             }
2676             hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2677                 let def_id = tcx.require_lang_item(lang_item, Some(span));
2678                 let (substs, _) = self.create_substs_for_ast_path(
2679                     span,
2680                     def_id,
2681                     &[],
2682                     &hir::PathSegment::invalid(),
2683                     &GenericArgs::none(),
2684                     true,
2685                     None,
2686                     None,
2687                 );
2688                 EarlyBinder(self.normalize_ty(span, tcx.at(span).type_of(def_id)))
2689                     .subst(tcx, substs)
2690             }
2691             hir::TyKind::Array(ref ty, ref length) => {
2692                 let length = match length {
2693                     &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2694                     hir::ArrayLen::Body(constant) => {
2695                         let length_def_id = tcx.hir().local_def_id(constant.hir_id);
2696                         ty::Const::from_anon_const(tcx, length_def_id)
2697                     }
2698                 };
2699
2700                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
2701                 self.normalize_ty(ast_ty.span, array_ty)
2702             }
2703             hir::TyKind::Typeof(ref e) => {
2704                 let ty_erased = tcx.type_of(tcx.hir().local_def_id(e.hir_id));
2705                 let ty = tcx.fold_regions(ty_erased, |r, _| {
2706                     if r.is_erased() { tcx.lifetimes.re_static } else { r }
2707                 });
2708                 let span = ast_ty.span;
2709                 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2710                     span,
2711                     ty,
2712                     opt_sugg: Some((span, Applicability::MachineApplicable))
2713                         .filter(|_| ty.is_suggestable(tcx, false)),
2714                 });
2715
2716                 ty
2717             }
2718             hir::TyKind::Infer => {
2719                 // Infer also appears as the type of arguments or return
2720                 // values in an ExprKind::Closure, or as
2721                 // the type of local variables. Both of these cases are
2722                 // handled specially and will not descend into this routine.
2723                 self.ty_infer(None, ast_ty.span)
2724             }
2725             hir::TyKind::Err => tcx.ty_error(),
2726         };
2727
2728         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2729         result_ty
2730     }
2731
2732     #[instrument(level = "debug", skip(self), ret)]
2733     fn impl_trait_ty_to_ty(
2734         &self,
2735         def_id: DefId,
2736         lifetimes: &[hir::GenericArg<'_>],
2737         origin: OpaqueTyOrigin,
2738         in_trait: bool,
2739     ) -> Ty<'tcx> {
2740         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2741         let tcx = self.tcx();
2742
2743         let generics = tcx.generics_of(def_id);
2744
2745         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2746         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2747             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2748                 // Our own parameters are the resolved lifetimes.
2749                 if let GenericParamDefKind::Lifetime = param.kind {
2750                     if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2751                         self.ast_region_to_region(lifetime, None).into()
2752                     } else {
2753                         bug!()
2754                     }
2755                 } else {
2756                     bug!()
2757                 }
2758             } else {
2759                 match param.kind {
2760                     // For RPIT (return position impl trait), only lifetimes
2761                     // mentioned in the impl Trait predicate are captured by
2762                     // the opaque type, so the lifetime parameters from the
2763                     // parent item need to be replaced with `'static`.
2764                     //
2765                     // For `impl Trait` in the types of statics, constants,
2766                     // locals and type aliases. These capture all parent
2767                     // lifetimes, so they can use their identity subst.
2768                     GenericParamDefKind::Lifetime
2769                         if matches!(
2770                             origin,
2771                             hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..)
2772                         ) =>
2773                     {
2774                         tcx.lifetimes.re_static.into()
2775                     }
2776                     _ => tcx.mk_param_from_def(param),
2777                 }
2778             }
2779         });
2780         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2781
2782         if in_trait { tcx.mk_projection(def_id, substs) } else { tcx.mk_opaque(def_id, substs) }
2783     }
2784
2785     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2786         match ty.kind {
2787             hir::TyKind::Infer if expected_ty.is_some() => {
2788                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2789                 expected_ty.unwrap()
2790             }
2791             _ => self.ast_ty_to_ty(ty),
2792         }
2793     }
2794
2795     #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)]
2796     pub fn ty_of_fn(
2797         &self,
2798         hir_id: hir::HirId,
2799         unsafety: hir::Unsafety,
2800         abi: abi::Abi,
2801         decl: &hir::FnDecl<'_>,
2802         generics: Option<&hir::Generics<'_>>,
2803         hir_ty: Option<&hir::Ty<'_>>,
2804     ) -> ty::PolyFnSig<'tcx> {
2805         let tcx = self.tcx();
2806         let bound_vars = tcx.late_bound_vars(hir_id);
2807         debug!(?bound_vars);
2808
2809         // We proactively collect all the inferred type params to emit a single error per fn def.
2810         let mut visitor = HirPlaceholderCollector::default();
2811         let mut infer_replacements = vec![];
2812
2813         if let Some(generics) = generics {
2814             walk_generics(&mut visitor, generics);
2815         }
2816
2817         let input_tys: Vec<_> = decl
2818             .inputs
2819             .iter()
2820             .enumerate()
2821             .map(|(i, a)| {
2822                 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
2823                     if let Some(suggested_ty) =
2824                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
2825                     {
2826                         infer_replacements.push((a.span, suggested_ty.to_string()));
2827                         return suggested_ty;
2828                     }
2829                 }
2830
2831                 // Only visit the type looking for `_` if we didn't fix the type above
2832                 visitor.visit_ty(a);
2833                 self.ty_of_arg(a, None)
2834             })
2835             .collect();
2836
2837         let output_ty = match decl.output {
2838             hir::FnRetTy::Return(output) => {
2839                 if let hir::TyKind::Infer = output.kind
2840                     && !self.allow_ty_infer()
2841                     && let Some(suggested_ty) =
2842                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
2843                 {
2844                     infer_replacements.push((output.span, suggested_ty.to_string()));
2845                     suggested_ty
2846                 } else {
2847                     visitor.visit_ty(output);
2848                     self.ast_ty_to_ty(output)
2849                 }
2850             }
2851             hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2852         };
2853
2854         debug!(?output_ty);
2855
2856         let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
2857         let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2858
2859         if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
2860             // We always collect the spans for placeholder types when evaluating `fn`s, but we
2861             // only want to emit an error complaining about them if infer types (`_`) are not
2862             // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2863             // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2864
2865             let mut diag = crate::collect::placeholder_type_error_diag(
2866                 tcx,
2867                 generics,
2868                 visitor.0,
2869                 infer_replacements.iter().map(|(s, _)| *s).collect(),
2870                 true,
2871                 hir_ty,
2872                 "function",
2873             );
2874
2875             if !infer_replacements.is_empty() {
2876                 diag.multipart_suggestion(
2877                     &format!(
2878                     "try replacing `_` with the type{} in the corresponding trait method signature",
2879                     rustc_errors::pluralize!(infer_replacements.len()),
2880                 ),
2881                     infer_replacements,
2882                     Applicability::MachineApplicable,
2883                 );
2884             }
2885
2886             diag.emit();
2887         }
2888
2889         // Find any late-bound regions declared in return type that do
2890         // not appear in the arguments. These are not well-formed.
2891         //
2892         // Example:
2893         //     for<'a> fn() -> &'a str <-- 'a is bad
2894         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2895         let inputs = bare_fn_ty.inputs();
2896         let late_bound_in_args =
2897             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2898         let output = bare_fn_ty.output();
2899         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2900
2901         self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2902             struct_span_err!(
2903                 tcx.sess,
2904                 decl.output.span(),
2905                 E0581,
2906                 "return type references {}, which is not constrained by the fn input types",
2907                 br_name
2908             )
2909         });
2910
2911         bare_fn_ty
2912     }
2913
2914     /// Given a fn_hir_id for a impl function, suggest the type that is found on the
2915     /// corresponding function in the trait that the impl implements, if it exists.
2916     /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
2917     /// corresponds to the return type.
2918     fn suggest_trait_fn_ty_for_impl_fn_infer(
2919         &self,
2920         fn_hir_id: hir::HirId,
2921         arg_idx: Option<usize>,
2922     ) -> Option<Ty<'tcx>> {
2923         let tcx = self.tcx();
2924         let hir = tcx.hir();
2925
2926         let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
2927             hir.get(fn_hir_id) else { return None };
2928         let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
2929                 hir.get(hir.get_parent_node(fn_hir_id)) else { bug!("ImplItem should have Impl parent") };
2930
2931         let trait_ref = self.instantiate_mono_trait_ref(
2932             i.of_trait.as_ref()?,
2933             self.ast_ty_to_ty(i.self_ty),
2934             ty::BoundConstness::NotConst,
2935         );
2936
2937         let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
2938             tcx,
2939             *ident,
2940             ty::AssocKind::Fn,
2941             trait_ref.def_id,
2942         )?;
2943
2944         let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst(
2945             tcx,
2946             trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
2947         );
2948
2949         let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
2950
2951         Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
2952     }
2953
2954     fn validate_late_bound_regions(
2955         &self,
2956         constrained_regions: FxHashSet<ty::BoundRegionKind>,
2957         referenced_regions: FxHashSet<ty::BoundRegionKind>,
2958         generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2959     ) {
2960         for br in referenced_regions.difference(&constrained_regions) {
2961             let br_name = match *br {
2962                 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) | ty::BrEnv => {
2963                     "an anonymous lifetime".to_string()
2964                 }
2965                 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2966             };
2967
2968             let mut err = generate_err(&br_name);
2969
2970             if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) = *br {
2971                 // The only way for an anonymous lifetime to wind up
2972                 // in the return type but **also** be unconstrained is
2973                 // if it only appears in "associated types" in the
2974                 // input. See #47511 and #62200 for examples. In this case,
2975                 // though we can easily give a hint that ought to be
2976                 // relevant.
2977                 err.note(
2978                     "lifetimes appearing in an associated or opaque type are not considered constrained",
2979                 );
2980                 err.note("consider introducing a named lifetime parameter");
2981             }
2982
2983             err.emit();
2984         }
2985     }
2986
2987     /// Given the bounds on an object, determines what single region bound (if any) we can
2988     /// use to summarize this type. The basic idea is that we will use the bound the user
2989     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2990     /// for region bounds. It may be that we can derive no bound at all, in which case
2991     /// we return `None`.
2992     fn compute_object_lifetime_bound(
2993         &self,
2994         span: Span,
2995         existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2996     ) -> Option<ty::Region<'tcx>> // if None, use the default
2997     {
2998         let tcx = self.tcx();
2999
3000         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3001
3002         // No explicit region bound specified. Therefore, examine trait
3003         // bounds and see if we can derive region bounds from those.
3004         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3005
3006         // If there are no derived region bounds, then report back that we
3007         // can find no region bound. The caller will use the default.
3008         if derived_region_bounds.is_empty() {
3009             return None;
3010         }
3011
3012         // If any of the derived region bounds are 'static, that is always
3013         // the best choice.
3014         if derived_region_bounds.iter().any(|r| r.is_static()) {
3015             return Some(tcx.lifetimes.re_static);
3016         }
3017
3018         // Determine whether there is exactly one unique region in the set
3019         // of derived region bounds. If so, use that. Otherwise, report an
3020         // error.
3021         let r = derived_region_bounds[0];
3022         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3023             tcx.sess.emit_err(AmbiguousLifetimeBound { span });
3024         }
3025         Some(r)
3026     }
3027
3028     /// Make sure that we are in the condition to suggest the blanket implementation.
3029     fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
3030         let tcx = self.tcx();
3031         let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
3032         if let hir::Node::Item(hir::Item {
3033             kind:
3034                 hir::ItemKind::Impl(hir::Impl {
3035                     self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
3036                 }),
3037             ..
3038         }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
3039         {
3040             if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3041                 return;
3042             }
3043             let of_trait_span = of_trait_ref.path.span;
3044             // make sure that we are not calling unwrap to abort during the compilation
3045             let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3046             let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3047             // check if the trait has generics, to make a correct suggestion
3048             let param_name = generics.params.next_type_param_name(None);
3049
3050             let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3051                 (span, format!(", {}: {}", param_name, impl_trait_name))
3052             } else {
3053                 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3054             };
3055             diag.multipart_suggestion(
3056             format!("alternatively use a blanket \
3057                      implementation to implement `{of_trait_name}` for \
3058                      all types that also implement `{impl_trait_name}`"),
3059                 vec![
3060                     (self_ty.span, param_name),
3061                     add_generic_sugg,
3062                 ],
3063                 Applicability::MaybeIncorrect,
3064             );
3065         }
3066     }
3067
3068     fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3069         let tcx = self.tcx();
3070         if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3071             self_ty.kind
3072         {
3073             let needs_bracket = in_path
3074                 && !tcx
3075                     .sess
3076                     .source_map()
3077                     .span_to_prev_source(self_ty.span)
3078                     .ok()
3079                     .map_or(false, |s| s.trim_end().ends_with('<'));
3080
3081             let is_global = poly_trait_ref.trait_ref.path.is_global();
3082
3083             let mut sugg = Vec::from_iter([(
3084                 self_ty.span.shrink_to_lo(),
3085                 format!(
3086                     "{}dyn {}",
3087                     if needs_bracket { "<" } else { "" },
3088                     if is_global { "(" } else { "" },
3089                 ),
3090             )]);
3091
3092             if is_global || needs_bracket {
3093                 sugg.push((
3094                     self_ty.span.shrink_to_hi(),
3095                     format!(
3096                         "{}{}",
3097                         if is_global { ")" } else { "" },
3098                         if needs_bracket { ">" } else { "" },
3099                     ),
3100                 ));
3101             }
3102
3103             if self_ty.span.edition() >= Edition::Edition2021 {
3104                 let msg = "trait objects must include the `dyn` keyword";
3105                 let label = "add `dyn` keyword before this trait";
3106                 let mut diag =
3107                     rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3108                 diag.multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable);
3109                 // check if the impl trait that we are considering is a impl of a local trait
3110                 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3111                 diag.emit();
3112             } else {
3113                 let msg = "trait objects without an explicit `dyn` are deprecated";
3114                 tcx.struct_span_lint_hir(
3115                     BARE_TRAIT_OBJECTS,
3116                     self_ty.hir_id,
3117                     self_ty.span,
3118                     msg,
3119                     |lint| {
3120                         lint.multipart_suggestion_verbose(
3121                             "use `dyn`",
3122                             sugg,
3123                             Applicability::MachineApplicable,
3124                         );
3125                         self.maybe_lint_blanket_trait_impl(&self_ty, lint);
3126                         lint
3127                     },
3128                 );
3129             }
3130         }
3131     }
3132 }