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