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