]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/astconv/mod.rs
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
[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, 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 trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1812                     Some(trait_ref) => trait_ref,
1813                     None => {
1814                         // A cycle error occurred, most likely.
1815                         return Err(ErrorReported);
1816                     }
1817                 };
1818
1819                 self.one_bound_for_assoc_type(
1820                     || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1821                     || "Self".to_string(),
1822                     assoc_ident,
1823                     span,
1824                     || None,
1825                 )?
1826             }
1827             (
1828                 &ty::Param(_),
1829                 Res::SelfTy { trait_: Some(param_did), alias_to: None }
1830                 | Res::Def(DefKind::TyParam, param_did),
1831             ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1832             _ => {
1833                 if variant_resolution.is_some() {
1834                     // Variant in type position
1835                     let msg = format!("expected type, found variant `{}`", assoc_ident);
1836                     tcx.sess.span_err(span, &msg);
1837                 } else if qself_ty.is_enum() {
1838                     let mut err = struct_span_err!(
1839                         tcx.sess,
1840                         assoc_ident.span,
1841                         E0599,
1842                         "no variant named `{}` found for enum `{}`",
1843                         assoc_ident,
1844                         qself_ty,
1845                     );
1846
1847                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1848                     if let Some(suggested_name) = find_best_match_for_name(
1849                         &adt_def
1850                             .variants
1851                             .iter()
1852                             .map(|variant| variant.name)
1853                             .collect::<Vec<Symbol>>(),
1854                         assoc_ident.name,
1855                         None,
1856                     ) {
1857                         err.span_suggestion(
1858                             assoc_ident.span,
1859                             "there is a variant with a similar name",
1860                             suggested_name.to_string(),
1861                             Applicability::MaybeIncorrect,
1862                         );
1863                     } else {
1864                         err.span_label(
1865                             assoc_ident.span,
1866                             format!("variant not found in `{}`", qself_ty),
1867                         );
1868                     }
1869
1870                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1871                         let sp = tcx.sess.source_map().guess_head_span(sp);
1872                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1873                     }
1874
1875                     err.emit();
1876                 } else if !qself_ty.references_error() {
1877                     // Don't print `TyErr` to the user.
1878                     self.report_ambiguous_associated_type(
1879                         span,
1880                         &qself_ty.to_string(),
1881                         "Trait",
1882                         assoc_ident.name,
1883                     );
1884                 }
1885                 return Err(ErrorReported);
1886             }
1887         };
1888
1889         let trait_did = bound.def_id();
1890         let (assoc_ident, def_scope) =
1891             tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1892
1893         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1894         // of calling `filter_by_name_and_kind`.
1895         let item = tcx.associated_items(trait_did).in_definition_order().find(|i| {
1896             i.kind.namespace() == Namespace::TypeNS
1897                 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1898         });
1899         // Assume that if it's not matched, there must be a const defined with the same name
1900         // but it was used in a type position.
1901         let Some(item) = item else {
1902             let msg = format!("found associated const `{assoc_ident}` when type was expected");
1903             tcx.sess.struct_span_err(span, &msg).emit();
1904             return Err(ErrorReported);
1905         };
1906
1907         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1908         let ty = self.normalize_ty(span, ty);
1909
1910         let kind = DefKind::AssocTy;
1911         if !item.vis.is_accessible_from(def_scope, tcx) {
1912             let kind = kind.descr(item.def_id);
1913             let msg = format!("{} `{}` is private", kind, assoc_ident);
1914             tcx.sess
1915                 .struct_span_err(span, &msg)
1916                 .span_label(span, &format!("private {}", kind))
1917                 .emit();
1918         }
1919         tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
1920
1921         if let Some(variant_def_id) = variant_resolution {
1922             tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1923                 let mut err = lint.build("ambiguous associated item");
1924                 let mut could_refer_to = |kind: DefKind, def_id, also| {
1925                     let note_msg = format!(
1926                         "`{}` could{} refer to the {} defined here",
1927                         assoc_ident,
1928                         also,
1929                         kind.descr(def_id)
1930                     );
1931                     err.span_note(tcx.def_span(def_id), &note_msg);
1932                 };
1933
1934                 could_refer_to(DefKind::Variant, variant_def_id, "");
1935                 could_refer_to(kind, item.def_id, " also");
1936
1937                 err.span_suggestion(
1938                     span,
1939                     "use fully-qualified syntax",
1940                     format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1941                     Applicability::MachineApplicable,
1942                 );
1943
1944                 err.emit();
1945             });
1946         }
1947         Ok((ty, kind, item.def_id))
1948     }
1949
1950     fn qpath_to_ty(
1951         &self,
1952         span: Span,
1953         opt_self_ty: Option<Ty<'tcx>>,
1954         item_def_id: DefId,
1955         trait_segment: &hir::PathSegment<'_>,
1956         item_segment: &hir::PathSegment<'_>,
1957     ) -> Ty<'tcx> {
1958         let tcx = self.tcx();
1959
1960         let trait_def_id = tcx.parent(item_def_id).unwrap();
1961
1962         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1963
1964         let Some(self_ty) = opt_self_ty else {
1965             let path_str = tcx.def_path_str(trait_def_id);
1966
1967             let def_id = self.item_def_id();
1968
1969             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1970
1971             let parent_def_id = def_id
1972                 .and_then(|def_id| {
1973                     def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1974                 })
1975                 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
1976
1977             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1978
1979             // If the trait in segment is the same as the trait defining the item,
1980             // use the `<Self as ..>` syntax in the error.
1981             let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1982             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1983
1984             let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1985                 "Self"
1986             } else {
1987                 "Type"
1988             };
1989
1990             self.report_ambiguous_associated_type(
1991                 span,
1992                 type_name,
1993                 &path_str,
1994                 item_segment.ident.name,
1995             );
1996             return tcx.ty_error();
1997         };
1998
1999         debug!("qpath_to_ty: self_type={:?}", self_ty);
2000
2001         let trait_ref =
2002             self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false);
2003
2004         let item_substs = self.create_substs_for_associated_item(
2005             tcx,
2006             span,
2007             item_def_id,
2008             item_segment,
2009             trait_ref.substs,
2010         );
2011
2012         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2013
2014         self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2015     }
2016
2017     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2018         &self,
2019         segments: T,
2020     ) -> bool {
2021         let mut has_err = false;
2022         for segment in segments {
2023             let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2024             for arg in segment.args().args {
2025                 let (span, kind) = match arg {
2026                     hir::GenericArg::Lifetime(lt) => {
2027                         if err_for_lt {
2028                             continue;
2029                         }
2030                         err_for_lt = true;
2031                         has_err = true;
2032                         (lt.span, "lifetime")
2033                     }
2034                     hir::GenericArg::Type(ty) => {
2035                         if err_for_ty {
2036                             continue;
2037                         }
2038                         err_for_ty = true;
2039                         has_err = true;
2040                         (ty.span, "type")
2041                     }
2042                     hir::GenericArg::Const(ct) => {
2043                         if err_for_ct {
2044                             continue;
2045                         }
2046                         err_for_ct = true;
2047                         has_err = true;
2048                         (ct.span, "const")
2049                     }
2050                     hir::GenericArg::Infer(inf) => {
2051                         if err_for_ty {
2052                             continue;
2053                         }
2054                         has_err = true;
2055                         err_for_ty = true;
2056                         (inf.span, "generic")
2057                     }
2058                 };
2059                 let mut err = struct_span_err!(
2060                     self.tcx().sess,
2061                     span,
2062                     E0109,
2063                     "{} arguments are not allowed for this type",
2064                     kind,
2065                 );
2066                 err.span_label(span, format!("{} argument not allowed", kind));
2067                 err.emit();
2068                 if err_for_lt && err_for_ty && err_for_ct {
2069                     break;
2070                 }
2071             }
2072
2073             // Only emit the first error to avoid overloading the user with error messages.
2074             if let [binding, ..] = segment.args().bindings {
2075                 has_err = true;
2076                 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2077             }
2078         }
2079         has_err
2080     }
2081
2082     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2083     pub fn def_ids_for_value_path_segments(
2084         &self,
2085         segments: &[hir::PathSegment<'_>],
2086         self_ty: Option<Ty<'tcx>>,
2087         kind: DefKind,
2088         def_id: DefId,
2089     ) -> Vec<PathSeg> {
2090         // We need to extract the type parameters supplied by the user in
2091         // the path `path`. Due to the current setup, this is a bit of a
2092         // tricky-process; the problem is that resolve only tells us the
2093         // end-point of the path resolution, and not the intermediate steps.
2094         // Luckily, we can (at least for now) deduce the intermediate steps
2095         // just from the end-point.
2096         //
2097         // There are basically five cases to consider:
2098         //
2099         // 1. Reference to a constructor of a struct:
2100         //
2101         //        struct Foo<T>(...)
2102         //
2103         //    In this case, the parameters are declared in the type space.
2104         //
2105         // 2. Reference to a constructor of an enum variant:
2106         //
2107         //        enum E<T> { Foo(...) }
2108         //
2109         //    In this case, the parameters are defined in the type space,
2110         //    but may be specified either on the type or the variant.
2111         //
2112         // 3. Reference to a fn item or a free constant:
2113         //
2114         //        fn foo<T>() { }
2115         //
2116         //    In this case, the path will again always have the form
2117         //    `a::b::foo::<T>` where only the final segment should have
2118         //    type parameters. However, in this case, those parameters are
2119         //    declared on a value, and hence are in the `FnSpace`.
2120         //
2121         // 4. Reference to a method or an associated constant:
2122         //
2123         //        impl<A> SomeStruct<A> {
2124         //            fn foo<B>(...)
2125         //        }
2126         //
2127         //    Here we can have a path like
2128         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2129         //    may appear in two places. The penultimate segment,
2130         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2131         //    final segment, `foo::<B>` contains parameters in fn space.
2132         //
2133         // The first step then is to categorize the segments appropriately.
2134
2135         let tcx = self.tcx();
2136
2137         assert!(!segments.is_empty());
2138         let last = segments.len() - 1;
2139
2140         let mut path_segs = vec![];
2141
2142         match kind {
2143             // Case 1. Reference to a struct constructor.
2144             DefKind::Ctor(CtorOf::Struct, ..) => {
2145                 // Everything but the final segment should have no
2146                 // parameters at all.
2147                 let generics = tcx.generics_of(def_id);
2148                 // Variant and struct constructors use the
2149                 // generics of their parent type definition.
2150                 let generics_def_id = generics.parent.unwrap_or(def_id);
2151                 path_segs.push(PathSeg(generics_def_id, last));
2152             }
2153
2154             // Case 2. Reference to a variant constructor.
2155             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2156                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2157                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2158                     debug_assert!(adt_def.is_enum());
2159                     (adt_def.did, last)
2160                 } else if last >= 1 && segments[last - 1].args.is_some() {
2161                     // Everything but the penultimate segment should have no
2162                     // parameters at all.
2163                     let mut def_id = def_id;
2164
2165                     // `DefKind::Ctor` -> `DefKind::Variant`
2166                     if let DefKind::Ctor(..) = kind {
2167                         def_id = tcx.parent(def_id).unwrap()
2168                     }
2169
2170                     // `DefKind::Variant` -> `DefKind::Enum`
2171                     let enum_def_id = tcx.parent(def_id).unwrap();
2172                     (enum_def_id, last - 1)
2173                 } else {
2174                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2175                     // instead of `Enum::Variant::<...>` form.
2176
2177                     // Everything but the final segment should have no
2178                     // parameters at all.
2179                     let generics = tcx.generics_of(def_id);
2180                     // Variant and struct constructors use the
2181                     // generics of their parent type definition.
2182                     (generics.parent.unwrap_or(def_id), last)
2183                 };
2184                 path_segs.push(PathSeg(generics_def_id, index));
2185             }
2186
2187             // Case 3. Reference to a top-level value.
2188             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2189                 path_segs.push(PathSeg(def_id, last));
2190             }
2191
2192             // Case 4. Reference to a method or associated const.
2193             DefKind::AssocFn | DefKind::AssocConst => {
2194                 if segments.len() >= 2 {
2195                     let generics = tcx.generics_of(def_id);
2196                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2197                 }
2198                 path_segs.push(PathSeg(def_id, last));
2199             }
2200
2201             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2202         }
2203
2204         debug!("path_segs = {:?}", path_segs);
2205
2206         path_segs
2207     }
2208
2209     // Check a type `Path` and convert it to a `Ty`.
2210     pub fn res_to_ty(
2211         &self,
2212         opt_self_ty: Option<Ty<'tcx>>,
2213         path: &hir::Path<'_>,
2214         permit_variants: bool,
2215     ) -> Ty<'tcx> {
2216         let tcx = self.tcx();
2217
2218         debug!(
2219             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2220             path.res, opt_self_ty, path.segments
2221         );
2222
2223         let span = path.span;
2224         match path.res {
2225             Res::Def(DefKind::OpaqueTy, did) => {
2226                 // Check for desugared `impl Trait`.
2227                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2228                 let item_segment = path.segments.split_last().unwrap();
2229                 self.prohibit_generics(item_segment.1);
2230                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2231                 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2232             }
2233             Res::Def(
2234                 DefKind::Enum
2235                 | DefKind::TyAlias
2236                 | DefKind::Struct
2237                 | DefKind::Union
2238                 | DefKind::ForeignTy,
2239                 did,
2240             ) => {
2241                 assert_eq!(opt_self_ty, None);
2242                 self.prohibit_generics(path.segments.split_last().unwrap().1);
2243                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2244             }
2245             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2246                 // Convert "variant type" as if it were a real type.
2247                 // The resulting `Ty` is type of the variant's enum for now.
2248                 assert_eq!(opt_self_ty, None);
2249
2250                 let path_segs =
2251                     self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
2252                 let generic_segs: FxHashSet<_> =
2253                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2254                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2255                     |(index, seg)| {
2256                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2257                     },
2258                 ));
2259
2260                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2261                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2262             }
2263             Res::Def(DefKind::TyParam, def_id) => {
2264                 assert_eq!(opt_self_ty, None);
2265                 self.prohibit_generics(path.segments);
2266
2267                 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2268                 let item_id = tcx.hir().get_parent_node(hir_id);
2269                 let item_def_id = tcx.hir().local_def_id(item_id);
2270                 let generics = tcx.generics_of(item_def_id);
2271                 let index = generics.param_def_id_to_index[&def_id];
2272                 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2273             }
2274             Res::SelfTy { trait_: Some(_), alias_to: None } => {
2275                 // `Self` in trait or type alias.
2276                 assert_eq!(opt_self_ty, None);
2277                 self.prohibit_generics(path.segments);
2278                 tcx.types.self_param
2279             }
2280             Res::SelfTy { trait_: _, alias_to: Some((def_id, forbid_generic)) } => {
2281                 // `Self` in impl (we know the concrete type).
2282                 assert_eq!(opt_self_ty, None);
2283                 self.prohibit_generics(path.segments);
2284                 // Try to evaluate any array length constants.
2285                 let ty = tcx.at(span).type_of(def_id);
2286                 // HACK(min_const_generics): Forbid generic `Self` types
2287                 // here as we can't easily do that during nameres.
2288                 //
2289                 // We do this before normalization as we otherwise allow
2290                 // ```rust
2291                 // trait AlwaysApplicable { type Assoc; }
2292                 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2293                 //
2294                 // trait BindsParam<T> {
2295                 //     type ArrayTy;
2296                 // }
2297                 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2298                 //    type ArrayTy = [u8; Self::MAX];
2299                 // }
2300                 // ```
2301                 // Note that the normalization happens in the param env of
2302                 // the anon const, which is empty. This is why the
2303                 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2304                 // this to compile if we were to normalize here.
2305                 if forbid_generic && ty.needs_subst() {
2306                     let mut err = tcx.sess.struct_span_err(
2307                         path.span,
2308                         "generic `Self` types are currently not permitted in anonymous constants",
2309                     );
2310                     if let Some(hir::Node::Item(&hir::Item {
2311                         kind: hir::ItemKind::Impl(ref impl_),
2312                         ..
2313                     })) = tcx.hir().get_if_local(def_id)
2314                     {
2315                         err.span_note(impl_.self_ty.span, "not a concrete type");
2316                     }
2317                     err.emit();
2318                     tcx.ty_error()
2319                 } else {
2320                     self.normalize_ty(span, ty)
2321                 }
2322             }
2323             Res::Def(DefKind::AssocTy, def_id) => {
2324                 debug_assert!(path.segments.len() >= 2);
2325                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2326                 self.qpath_to_ty(
2327                     span,
2328                     opt_self_ty,
2329                     def_id,
2330                     &path.segments[path.segments.len() - 2],
2331                     path.segments.last().unwrap(),
2332                 )
2333             }
2334             Res::PrimTy(prim_ty) => {
2335                 assert_eq!(opt_self_ty, None);
2336                 self.prohibit_generics(path.segments);
2337                 match prim_ty {
2338                     hir::PrimTy::Bool => tcx.types.bool,
2339                     hir::PrimTy::Char => tcx.types.char,
2340                     hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2341                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2342                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2343                     hir::PrimTy::Str => tcx.types.str_,
2344                 }
2345             }
2346             Res::Err => {
2347                 self.set_tainted_by_errors();
2348                 self.tcx().ty_error()
2349             }
2350             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2351         }
2352     }
2353
2354     /// Parses the programmer's textual representation of a type into our
2355     /// internal notion of a type.
2356     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2357         self.ast_ty_to_ty_inner(ast_ty, false, false)
2358     }
2359
2360     /// Parses the programmer's textual representation of a type into our
2361     /// internal notion of a type.  This is meant to be used within a path.
2362     pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2363         self.ast_ty_to_ty_inner(ast_ty, false, true)
2364     }
2365
2366     /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2367     /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2368     #[tracing::instrument(level = "debug", skip(self))]
2369     fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2370         let tcx = self.tcx();
2371
2372         let result_ty = match ast_ty.kind {
2373             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2374             hir::TyKind::Ptr(ref mt) => {
2375                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2376             }
2377             hir::TyKind::Rptr(ref region, ref mt) => {
2378                 let r = self.ast_region_to_region(region, None);
2379                 debug!(?r);
2380                 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2381                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2382             }
2383             hir::TyKind::Never => tcx.types.never,
2384             hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2385             hir::TyKind::BareFn(bf) => {
2386                 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2387
2388                 tcx.mk_fn_ptr(self.ty_of_fn(
2389                     ast_ty.hir_id,
2390                     bf.unsafety,
2391                     bf.abi,
2392                     bf.decl,
2393                     &hir::Generics::empty(),
2394                     None,
2395                     Some(ast_ty),
2396                 ))
2397             }
2398             hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2399                 self.maybe_lint_bare_trait(ast_ty, in_path);
2400                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2401             }
2402             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2403                 debug!(?maybe_qself, ?path);
2404                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2405                 self.res_to_ty(opt_self_ty, path, false)
2406             }
2407             hir::TyKind::OpaqueDef(item_id, lifetimes) => {
2408                 let opaque_ty = tcx.hir().item(item_id);
2409                 let def_id = item_id.def_id.to_def_id();
2410
2411                 match opaque_ty.kind {
2412                     hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => self
2413                         .impl_trait_ty_to_ty(
2414                             def_id,
2415                             lifetimes,
2416                             matches!(
2417                                 origin,
2418                                 hir::OpaqueTyOrigin::FnReturn(..)
2419                                     | hir::OpaqueTyOrigin::AsyncFn(..)
2420                             ),
2421                         ),
2422                     ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2423                 }
2424             }
2425             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2426                 debug!(?qself, ?segment);
2427                 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2428
2429                 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = qself.kind {
2430                     path.res
2431                 } else {
2432                     Res::Err
2433                 };
2434                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2435                     .map(|(ty, _, _)| ty)
2436                     .unwrap_or_else(|_| tcx.ty_error())
2437             }
2438             hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2439                 let def_id = tcx.require_lang_item(lang_item, Some(span));
2440                 let (substs, _) = self.create_substs_for_ast_path(
2441                     span,
2442                     def_id,
2443                     &[],
2444                     &hir::PathSegment::invalid(),
2445                     &GenericArgs::none(),
2446                     true,
2447                     None,
2448                 );
2449                 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2450             }
2451             hir::TyKind::Array(ref ty, ref length) => {
2452                 let length = match length {
2453                     &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2454                     hir::ArrayLen::Body(constant) => {
2455                         let length_def_id = tcx.hir().local_def_id(constant.hir_id);
2456                         ty::Const::from_anon_const(tcx, length_def_id)
2457                     }
2458                 };
2459
2460                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
2461                 self.normalize_ty(ast_ty.span, array_ty)
2462             }
2463             hir::TyKind::Typeof(ref e) => {
2464                 tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span });
2465                 tcx.type_of(tcx.hir().local_def_id(e.hir_id))
2466             }
2467             hir::TyKind::Infer => {
2468                 // Infer also appears as the type of arguments or return
2469                 // values in an ExprKind::Closure, or as
2470                 // the type of local variables. Both of these cases are
2471                 // handled specially and will not descend into this routine.
2472                 self.ty_infer(None, ast_ty.span)
2473             }
2474             hir::TyKind::Err => tcx.ty_error(),
2475         };
2476
2477         debug!(?result_ty);
2478
2479         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2480         result_ty
2481     }
2482
2483     fn impl_trait_ty_to_ty(
2484         &self,
2485         def_id: DefId,
2486         lifetimes: &[hir::GenericArg<'_>],
2487         replace_parent_lifetimes: bool,
2488     ) -> Ty<'tcx> {
2489         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2490         let tcx = self.tcx();
2491
2492         let generics = tcx.generics_of(def_id);
2493
2494         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2495         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2496             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2497                 // Our own parameters are the resolved lifetimes.
2498                 if let GenericParamDefKind::Lifetime = param.kind {
2499                     if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2500                         self.ast_region_to_region(lifetime, None).into()
2501                     } else {
2502                         bug!()
2503                     }
2504                 } else {
2505                     bug!()
2506                 }
2507             } else {
2508                 match param.kind {
2509                     // For RPIT (return position impl trait), only lifetimes
2510                     // mentioned in the impl Trait predicate are captured by
2511                     // the opaque type, so the lifetime parameters from the
2512                     // parent item need to be replaced with `'static`.
2513                     //
2514                     // For `impl Trait` in the types of statics, constants,
2515                     // locals and type aliases. These capture all parent
2516                     // lifetimes, so they can use their identity subst.
2517                     GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2518                         tcx.lifetimes.re_static.into()
2519                     }
2520                     _ => tcx.mk_param_from_def(param),
2521                 }
2522             }
2523         });
2524         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2525
2526         let ty = tcx.mk_opaque(def_id, substs);
2527         debug!("impl_trait_ty_to_ty: {}", ty);
2528         ty
2529     }
2530
2531     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2532         match ty.kind {
2533             hir::TyKind::Infer if expected_ty.is_some() => {
2534                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2535                 expected_ty.unwrap()
2536             }
2537             _ => self.ast_ty_to_ty(ty),
2538         }
2539     }
2540
2541     pub fn ty_of_fn(
2542         &self,
2543         hir_id: hir::HirId,
2544         unsafety: hir::Unsafety,
2545         abi: abi::Abi,
2546         decl: &hir::FnDecl<'_>,
2547         generics: &hir::Generics<'_>,
2548         ident_span: Option<Span>,
2549         hir_ty: Option<&hir::Ty<'_>>,
2550     ) -> ty::PolyFnSig<'tcx> {
2551         debug!("ty_of_fn");
2552
2553         let tcx = self.tcx();
2554         let bound_vars = tcx.late_bound_vars(hir_id);
2555         debug!(?bound_vars);
2556
2557         // We proactively collect all the inferred type params to emit a single error per fn def.
2558         let mut visitor = HirPlaceholderCollector::default();
2559         for ty in decl.inputs {
2560             visitor.visit_ty(ty);
2561         }
2562         walk_generics(&mut visitor, generics);
2563
2564         let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2565         let output_ty = match decl.output {
2566             hir::FnRetTy::Return(output) => {
2567                 visitor.visit_ty(output);
2568                 self.ast_ty_to_ty(output)
2569             }
2570             hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2571         };
2572
2573         debug!("ty_of_fn: output_ty={:?}", output_ty);
2574
2575         let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi);
2576         let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2577
2578         if !self.allow_ty_infer() {
2579             // We always collect the spans for placeholder types when evaluating `fn`s, but we
2580             // only want to emit an error complaining about them if infer types (`_`) are not
2581             // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2582             // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2583
2584             crate::collect::placeholder_type_error(
2585                 tcx,
2586                 ident_span.map(|sp| sp.shrink_to_hi()),
2587                 generics.params,
2588                 visitor.0,
2589                 true,
2590                 hir_ty,
2591                 "function",
2592             );
2593         }
2594
2595         // Find any late-bound regions declared in return type that do
2596         // not appear in the arguments. These are not well-formed.
2597         //
2598         // Example:
2599         //     for<'a> fn() -> &'a str <-- 'a is bad
2600         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2601         let inputs = bare_fn_ty.inputs();
2602         let late_bound_in_args =
2603             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2604         let output = bare_fn_ty.output();
2605         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2606
2607         self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2608             struct_span_err!(
2609                 tcx.sess,
2610                 decl.output.span(),
2611                 E0581,
2612                 "return type references {}, which is not constrained by the fn input types",
2613                 br_name
2614             )
2615         });
2616
2617         bare_fn_ty
2618     }
2619
2620     fn validate_late_bound_regions(
2621         &self,
2622         constrained_regions: FxHashSet<ty::BoundRegionKind>,
2623         referenced_regions: FxHashSet<ty::BoundRegionKind>,
2624         generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>,
2625     ) {
2626         for br in referenced_regions.difference(&constrained_regions) {
2627             let br_name = match *br {
2628                 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2629                 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2630             };
2631
2632             let mut err = generate_err(&br_name);
2633
2634             if let ty::BrAnon(_) = *br {
2635                 // The only way for an anonymous lifetime to wind up
2636                 // in the return type but **also** be unconstrained is
2637                 // if it only appears in "associated types" in the
2638                 // input. See #47511 and #62200 for examples. In this case,
2639                 // though we can easily give a hint that ought to be
2640                 // relevant.
2641                 err.note(
2642                     "lifetimes appearing in an associated type are not considered constrained",
2643                 );
2644             }
2645
2646             err.emit();
2647         }
2648     }
2649
2650     /// Given the bounds on an object, determines what single region bound (if any) we can
2651     /// use to summarize this type. The basic idea is that we will use the bound the user
2652     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2653     /// for region bounds. It may be that we can derive no bound at all, in which case
2654     /// we return `None`.
2655     fn compute_object_lifetime_bound(
2656         &self,
2657         span: Span,
2658         existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2659     ) -> Option<ty::Region<'tcx>> // if None, use the default
2660     {
2661         let tcx = self.tcx();
2662
2663         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2664
2665         // No explicit region bound specified. Therefore, examine trait
2666         // bounds and see if we can derive region bounds from those.
2667         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2668
2669         // If there are no derived region bounds, then report back that we
2670         // can find no region bound. The caller will use the default.
2671         if derived_region_bounds.is_empty() {
2672             return None;
2673         }
2674
2675         // If any of the derived region bounds are 'static, that is always
2676         // the best choice.
2677         if derived_region_bounds.iter().any(|r| r.is_static()) {
2678             return Some(tcx.lifetimes.re_static);
2679         }
2680
2681         // Determine whether there is exactly one unique region in the set
2682         // of derived region bounds. If so, use that. Otherwise, report an
2683         // error.
2684         let r = derived_region_bounds[0];
2685         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2686             tcx.sess.emit_err(AmbiguousLifetimeBound { span });
2687         }
2688         Some(r)
2689     }
2690
2691     fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
2692         let tcx = self.tcx();
2693         if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
2694             self_ty.kind
2695         {
2696             let needs_bracket = in_path
2697                 && !tcx
2698                     .sess
2699                     .source_map()
2700                     .span_to_prev_source(self_ty.span)
2701                     .ok()
2702                     .map_or(false, |s| s.trim_end().ends_with('<'));
2703
2704             let is_global = poly_trait_ref.trait_ref.path.is_global();
2705             let sugg = Vec::from_iter([
2706                 (
2707                     self_ty.span.shrink_to_lo(),
2708                     format!(
2709                         "{}dyn {}",
2710                         if needs_bracket { "<" } else { "" },
2711                         if is_global { "(" } else { "" },
2712                     ),
2713                 ),
2714                 (
2715                     self_ty.span.shrink_to_hi(),
2716                     format!(
2717                         "{}{}",
2718                         if is_global { ")" } else { "" },
2719                         if needs_bracket { ">" } else { "" },
2720                     ),
2721                 ),
2722             ]);
2723             if self_ty.span.edition() >= Edition::Edition2021 {
2724                 let msg = "trait objects must include the `dyn` keyword";
2725                 let label = "add `dyn` keyword before this trait";
2726                 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg)
2727                     .multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable)
2728                     .emit();
2729             } else {
2730                 let msg = "trait objects without an explicit `dyn` are deprecated";
2731                 tcx.struct_span_lint_hir(
2732                     BARE_TRAIT_OBJECTS,
2733                     self_ty.hir_id,
2734                     self_ty.span,
2735                     |lint| {
2736                         lint.build(msg)
2737                             .multipart_suggestion_verbose(
2738                                 "use `dyn`",
2739                                 sugg,
2740                                 Applicability::MachineApplicable,
2741                             )
2742                             .emit()
2743                     },
2744                 );
2745             }
2746         }
2747     }
2748 }