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