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