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