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