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