]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/astconv/mod.rs
fix most compiler/ doctests
[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     /// ```ignore (illustrative)
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     /// ```ignore (illustrative)
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     /// ```ignore (illustrative)
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                     if pred.is_param_bound(self_ty_def_id) {
928                         search_bounds(pred.bounds);
929                     }
930                 }
931             }
932         }
933
934         let sized_def_id = tcx.lang_items().require(LangItem::Sized);
935         match (&sized_def_id, unbound) {
936             (Ok(sized_def_id), Some(tpb))
937                 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
938             {
939                 // There was in fact a `?Sized` bound, return without doing anything
940                 return;
941             }
942             (_, Some(_)) => {
943                 // There was a `?Trait` bound, but it was not `?Sized`; warn.
944                 tcx.sess.span_warn(
945                     span,
946                     "default bound relaxed for a type parameter, but \
947                         this does nothing because the given bound is not \
948                         a default; only `?Sized` is supported",
949                 );
950                 // Otherwise, add implicitly sized if `Sized` is available.
951             }
952             _ => {
953                 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
954             }
955         }
956         if sized_def_id.is_err() {
957             // No lang item for `Sized`, so we can't add it as a bound.
958             return;
959         }
960         bounds.implicitly_sized = Some(span);
961     }
962
963     /// This helper takes a *converted* parameter type (`param_ty`)
964     /// and an *unconverted* list of bounds:
965     ///
966     /// ```text
967     /// fn foo<T: Debug>
968     ///        ^  ^^^^^ `ast_bounds` parameter, in HIR form
969     ///        |
970     ///        `param_ty`, in ty form
971     /// ```
972     ///
973     /// It adds these `ast_bounds` into the `bounds` structure.
974     ///
975     /// **A note on binders:** there is an implied binder around
976     /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
977     /// for more details.
978     #[tracing::instrument(level = "debug", skip(self, ast_bounds, bounds))]
979     pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
980         &self,
981         param_ty: Ty<'tcx>,
982         ast_bounds: I,
983         bounds: &mut Bounds<'tcx>,
984         bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
985     ) {
986         for ast_bound in ast_bounds {
987             match ast_bound {
988                 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
989                     let constness = match modifier {
990                         hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
991                         hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
992                         hir::TraitBoundModifier::Maybe => continue,
993                     };
994
995                     let _ = self.instantiate_poly_trait_ref(
996                         &poly_trait_ref.trait_ref,
997                         poly_trait_ref.span,
998                         constness,
999                         param_ty,
1000                         bounds,
1001                         false,
1002                     );
1003                 }
1004                 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1005                     self.instantiate_lang_item_trait_ref(
1006                         lang_item, span, hir_id, args, param_ty, bounds,
1007                     );
1008                 }
1009                 hir::GenericBound::Outlives(lifetime) => {
1010                     let region = self.ast_region_to_region(lifetime, None);
1011                     bounds
1012                         .region_bounds
1013                         .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span));
1014                 }
1015             }
1016         }
1017     }
1018
1019     /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1020     /// The self-type for the bounds is given by `param_ty`.
1021     ///
1022     /// Example:
1023     ///
1024     /// ```ignore (illustrative)
1025     /// fn foo<T: Bar + Baz>() { }
1026     /// //     ^  ^^^^^^^^^ ast_bounds
1027     /// //     param_ty
1028     /// ```
1029     ///
1030     /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1031     /// considered `Sized` unless there is an explicit `?Sized` bound.  This would be true in the
1032     /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1033     ///
1034     /// `span` should be the declaration size of the parameter.
1035     pub(crate) fn compute_bounds(
1036         &self,
1037         param_ty: Ty<'tcx>,
1038         ast_bounds: &[hir::GenericBound<'_>],
1039     ) -> Bounds<'tcx> {
1040         self.compute_bounds_inner(param_ty, ast_bounds)
1041     }
1042
1043     /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1044     /// named `assoc_name` into ty::Bounds. Ignore the rest.
1045     pub(crate) fn compute_bounds_that_match_assoc_type(
1046         &self,
1047         param_ty: Ty<'tcx>,
1048         ast_bounds: &[hir::GenericBound<'_>],
1049         assoc_name: Ident,
1050     ) -> Bounds<'tcx> {
1051         let mut result = Vec::new();
1052
1053         for ast_bound in ast_bounds {
1054             if let Some(trait_ref) = ast_bound.trait_ref()
1055                 && let Some(trait_did) = trait_ref.trait_def_id()
1056                 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1057             {
1058                 result.push(ast_bound.clone());
1059             }
1060         }
1061
1062         self.compute_bounds_inner(param_ty, &result)
1063     }
1064
1065     fn compute_bounds_inner(
1066         &self,
1067         param_ty: Ty<'tcx>,
1068         ast_bounds: &[hir::GenericBound<'_>],
1069     ) -> Bounds<'tcx> {
1070         let mut bounds = Bounds::default();
1071
1072         self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1073
1074         bounds
1075     }
1076
1077     /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1078     /// onto `bounds`.
1079     ///
1080     /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1081     /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1082     /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1083     #[tracing::instrument(
1084         level = "debug",
1085         skip(self, bounds, speculative, dup_bindings, path_span)
1086     )]
1087     fn add_predicates_for_ast_type_binding(
1088         &self,
1089         hir_ref_id: hir::HirId,
1090         trait_ref: ty::PolyTraitRef<'tcx>,
1091         binding: &ConvertedBinding<'_, 'tcx>,
1092         bounds: &mut Bounds<'tcx>,
1093         speculative: bool,
1094         dup_bindings: &mut FxHashMap<DefId, Span>,
1095         path_span: Span,
1096     ) -> Result<(), ErrorGuaranteed> {
1097         // Given something like `U: SomeTrait<T = X>`, we want to produce a
1098         // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1099         // subtle in the event that `T` is defined in a supertrait of
1100         // `SomeTrait`, because in that case we need to upcast.
1101         //
1102         // That is, consider this case:
1103         //
1104         // ```
1105         // trait SubTrait: SuperTrait<i32> { }
1106         // trait SuperTrait<A> { type T; }
1107         //
1108         // ... B: SubTrait<T = foo> ...
1109         // ```
1110         //
1111         // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1112
1113         let tcx = self.tcx();
1114
1115         let candidate =
1116             if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1117                 // Simple case: X is defined in the current trait.
1118                 trait_ref
1119             } else {
1120                 // Otherwise, we have to walk through the supertraits to find
1121                 // those that do.
1122                 self.one_bound_for_assoc_type(
1123                     || traits::supertraits(tcx, trait_ref),
1124                     || trait_ref.print_only_trait_path().to_string(),
1125                     binding.item_name,
1126                     path_span,
1127                     || match binding.kind {
1128                         ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1129                         _ => None,
1130                     },
1131                 )?
1132             };
1133
1134         let (assoc_ident, def_scope) =
1135             tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1136
1137         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1138         // of calling `filter_by_name_and_kind`.
1139         let find_item_of_kind = |kind| {
1140             tcx.associated_items(candidate.def_id())
1141                 .filter_by_name_unhygienic(assoc_ident.name)
1142                 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1143         };
1144         let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1145             .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1146             .expect("missing associated type");
1147
1148         if !assoc_item.vis.is_accessible_from(def_scope, tcx) {
1149             let kind = match assoc_item.kind {
1150                 ty::AssocKind::Type => "type",
1151                 ty::AssocKind::Const => "const",
1152                 _ => unreachable!(),
1153             };
1154             tcx.sess
1155                 .struct_span_err(
1156                     binding.span,
1157                     &format!("associated {kind} `{}` is private", binding.item_name),
1158                 )
1159                 .span_label(binding.span, &format!("private associated {kind}"))
1160                 .emit();
1161         }
1162         tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1163
1164         if !speculative {
1165             dup_bindings
1166                 .entry(assoc_item.def_id)
1167                 .and_modify(|prev_span| {
1168                     self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1169                         span: binding.span,
1170                         prev_span: *prev_span,
1171                         item_name: binding.item_name,
1172                         def_path: tcx.def_path_str(assoc_item.container.id()),
1173                     });
1174                 })
1175                 .or_insert(binding.span);
1176         }
1177
1178         // Include substitutions for generic parameters of associated types
1179         let projection_ty = candidate.map_bound(|trait_ref| {
1180             let ident = Ident::new(assoc_item.name, binding.item_name.span);
1181             let item_segment = hir::PathSegment {
1182                 ident,
1183                 hir_id: Some(binding.hir_id),
1184                 res: None,
1185                 args: Some(binding.gen_args),
1186                 infer_args: false,
1187             };
1188
1189             let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1190                 tcx,
1191                 path_span,
1192                 assoc_item.def_id,
1193                 &item_segment,
1194                 trait_ref.substs,
1195             );
1196
1197             debug!(
1198                 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}",
1199                 substs_trait_ref_and_assoc_item
1200             );
1201
1202             ty::ProjectionTy {
1203                 item_def_id: assoc_item.def_id,
1204                 substs: substs_trait_ref_and_assoc_item,
1205             }
1206         });
1207
1208         if !speculative {
1209             // Find any late-bound regions declared in `ty` that are not
1210             // declared in the trait-ref or assoc_item. These are not well-formed.
1211             //
1212             // Example:
1213             //
1214             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1215             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1216             if let ConvertedBindingKind::Equality(ty) = binding.kind {
1217                 let late_bound_in_trait_ref =
1218                     tcx.collect_constrained_late_bound_regions(&projection_ty);
1219                 let late_bound_in_ty =
1220                     tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1221                 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1222                 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1223
1224                 // FIXME: point at the type params that don't have appropriate lifetimes:
1225                 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1226                 //                         ----  ----     ^^^^^^^
1227                 self.validate_late_bound_regions(
1228                     late_bound_in_trait_ref,
1229                     late_bound_in_ty,
1230                     |br_name| {
1231                         struct_span_err!(
1232                             tcx.sess,
1233                             binding.span,
1234                             E0582,
1235                             "binding for associated type `{}` references {}, \
1236                              which does not appear in the trait input types",
1237                             binding.item_name,
1238                             br_name
1239                         )
1240                     },
1241                 );
1242             }
1243         }
1244
1245         match binding.kind {
1246             ConvertedBindingKind::Equality(term) => {
1247                 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1248                 // the "projection predicate" for:
1249                 //
1250                 // `<T as Iterator>::Item = u32`
1251                 let assoc_item_def_id = projection_ty.skip_binder().item_def_id;
1252                 let def_kind = tcx.def_kind(assoc_item_def_id);
1253                 match (def_kind, term) {
1254                     (hir::def::DefKind::AssocTy, ty::Term::Ty(_))
1255                     | (hir::def::DefKind::AssocConst, ty::Term::Const(_)) => (),
1256                     (_, _) => {
1257                         let got = if let ty::Term::Ty(_) = term { "type" } else { "const" };
1258                         let expected = def_kind.descr(assoc_item_def_id);
1259                         tcx.sess
1260                             .struct_span_err(
1261                                 binding.span,
1262                                 &format!("mismatch in bind of {expected}, got {got}"),
1263                             )
1264                             .span_note(
1265                                 tcx.def_span(assoc_item_def_id),
1266                                 &format!("{expected} defined here does not match {got}"),
1267                             )
1268                             .emit();
1269                     }
1270                 }
1271                 bounds.projection_bounds.push((
1272                     projection_ty.map_bound(|projection_ty| ty::ProjectionPredicate {
1273                         projection_ty,
1274                         term: term,
1275                     }),
1276                     binding.span,
1277                 ));
1278             }
1279             ConvertedBindingKind::Constraint(ast_bounds) => {
1280                 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1281                 //
1282                 // `<T as Iterator>::Item: Debug`
1283                 //
1284                 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1285                 // parameter to have a skipped binder.
1286                 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1287                 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1288             }
1289         }
1290         Ok(())
1291     }
1292
1293     fn ast_path_to_ty(
1294         &self,
1295         span: Span,
1296         did: DefId,
1297         item_segment: &hir::PathSegment<'_>,
1298     ) -> Ty<'tcx> {
1299         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1300         self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1301     }
1302
1303     fn conv_object_ty_poly_trait_ref(
1304         &self,
1305         span: Span,
1306         trait_bounds: &[hir::PolyTraitRef<'_>],
1307         lifetime: &hir::Lifetime,
1308         borrowed: bool,
1309     ) -> Ty<'tcx> {
1310         let tcx = self.tcx();
1311
1312         let mut bounds = Bounds::default();
1313         let mut potential_assoc_types = Vec::new();
1314         let dummy_self = self.tcx().types.trait_object_dummy_self;
1315         for trait_bound in trait_bounds.iter().rev() {
1316             if let GenericArgCountResult {
1317                 correct:
1318                     Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1319                 ..
1320             } = self.instantiate_poly_trait_ref(
1321                 &trait_bound.trait_ref,
1322                 trait_bound.span,
1323                 ty::BoundConstness::NotConst,
1324                 dummy_self,
1325                 &mut bounds,
1326                 false,
1327             ) {
1328                 potential_assoc_types.extend(cur_potential_assoc_types);
1329             }
1330         }
1331
1332         // Expand trait aliases recursively and check that only one regular (non-auto) trait
1333         // is used and no 'maybe' bounds are used.
1334         let expanded_traits =
1335             traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1336         let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1337             expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1338         if regular_traits.len() > 1 {
1339             let first_trait = &regular_traits[0];
1340             let additional_trait = &regular_traits[1];
1341             let mut err = struct_span_err!(
1342                 tcx.sess,
1343                 additional_trait.bottom().1,
1344                 E0225,
1345                 "only auto traits can be used as additional traits in a trait object"
1346             );
1347             additional_trait.label_with_exp_info(
1348                 &mut err,
1349                 "additional non-auto trait",
1350                 "additional use",
1351             );
1352             first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1353             err.help(&format!(
1354                 "consider creating a new trait with all of these as supertraits and using that \
1355                  trait here instead: `trait NewTrait: {} {{}}`",
1356                 regular_traits
1357                     .iter()
1358                     .map(|t| t.trait_ref().print_only_trait_path().to_string())
1359                     .collect::<Vec<_>>()
1360                     .join(" + "),
1361             ));
1362             err.note(
1363                 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1364                  for more information on them, visit \
1365                  <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1366             );
1367             err.emit();
1368         }
1369
1370         if regular_traits.is_empty() && auto_traits.is_empty() {
1371             tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span });
1372             return tcx.ty_error();
1373         }
1374
1375         // Check that there are no gross object safety violations;
1376         // most importantly, that the supertraits don't contain `Self`,
1377         // to avoid ICEs.
1378         for item in &regular_traits {
1379             let object_safety_violations =
1380                 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1381             if !object_safety_violations.is_empty() {
1382                 report_object_safety_error(
1383                     tcx,
1384                     span,
1385                     item.trait_ref().def_id(),
1386                     &object_safety_violations,
1387                 )
1388                 .emit();
1389                 return tcx.ty_error();
1390             }
1391         }
1392
1393         // Use a `BTreeSet` to keep output in a more consistent order.
1394         let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1395
1396         let regular_traits_refs_spans = bounds
1397             .trait_bounds
1398             .into_iter()
1399             .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1400
1401         for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1402             assert_eq!(constness, ty::BoundConstness::NotConst);
1403
1404             for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1405                 debug!(
1406                     "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1407                     obligation.predicate
1408                 );
1409
1410                 let bound_predicate = obligation.predicate.kind();
1411                 match bound_predicate.skip_binder() {
1412                     ty::PredicateKind::Trait(pred) => {
1413                         let pred = bound_predicate.rebind(pred);
1414                         associated_types.entry(span).or_default().extend(
1415                             tcx.associated_items(pred.def_id())
1416                                 .in_definition_order()
1417                                 .filter(|item| item.kind == ty::AssocKind::Type)
1418                                 .map(|item| item.def_id),
1419                         );
1420                     }
1421                     ty::PredicateKind::Projection(pred) => {
1422                         let pred = bound_predicate.rebind(pred);
1423                         // A `Self` within the original bound will be substituted with a
1424                         // `trait_object_dummy_self`, so check for that.
1425                         let references_self = match pred.skip_binder().term {
1426                             ty::Term::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1427                             ty::Term::Const(c) => c.ty().walk().any(|arg| arg == dummy_self.into()),
1428                         };
1429
1430                         // If the projection output contains `Self`, force the user to
1431                         // elaborate it explicitly to avoid a lot of complexity.
1432                         //
1433                         // The "classically useful" case is the following:
1434                         // ```
1435                         //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1436                         //         type MyOutput;
1437                         //     }
1438                         // ```
1439                         //
1440                         // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1441                         // but actually supporting that would "expand" to an infinitely-long type
1442                         // `fix $ Ï„ â†’ dyn MyTrait<MyOutput = X, Output = <Ï„ as MyTrait>::MyOutput`.
1443                         //
1444                         // Instead, we force the user to write
1445                         // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1446                         // the discussion in #56288 for alternatives.
1447                         if !references_self {
1448                             // Include projections defined on supertraits.
1449                             bounds.projection_bounds.push((pred, span));
1450                         }
1451                     }
1452                     _ => (),
1453                 }
1454             }
1455         }
1456
1457         for (projection_bound, _) in &bounds.projection_bounds {
1458             for def_ids in associated_types.values_mut() {
1459                 def_ids.remove(&projection_bound.projection_def_id());
1460             }
1461         }
1462
1463         self.complain_about_missing_associated_types(
1464             associated_types,
1465             potential_assoc_types,
1466             trait_bounds,
1467         );
1468
1469         // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1470         // `dyn Trait + Send`.
1471         // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1472         // the bounds
1473         let mut duplicates = FxHashSet::default();
1474         auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1475         debug!("regular_traits: {:?}", regular_traits);
1476         debug!("auto_traits: {:?}", auto_traits);
1477
1478         // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1479         let existential_trait_refs = regular_traits.iter().map(|i| {
1480             i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1481                 if trait_ref.self_ty() != dummy_self {
1482                     // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1483                     // which picks up non-supertraits where clauses - but also, the object safety
1484                     // completely ignores trait aliases, which could be object safety hazards. We
1485                     // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1486                     // disabled. (#66420)
1487                     tcx.sess.delay_span_bug(
1488                         DUMMY_SP,
1489                         &format!(
1490                             "trait_ref_to_existential called on {:?} with non-dummy Self",
1491                             trait_ref,
1492                         ),
1493                     );
1494                 }
1495                 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1496             })
1497         });
1498         let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1499             bound.map_bound(|b| {
1500                 if b.projection_ty.self_ty() != dummy_self {
1501                     tcx.sess.delay_span_bug(
1502                         DUMMY_SP,
1503                         &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b),
1504                     );
1505                 }
1506                 ty::ExistentialProjection::erase_self_ty(tcx, b)
1507             })
1508         });
1509
1510         let regular_trait_predicates = existential_trait_refs
1511             .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1512         let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1513             ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1514         });
1515         // N.b. principal, projections, auto traits
1516         // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1517         let mut v = regular_trait_predicates
1518             .chain(
1519                 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1520             )
1521             .chain(auto_trait_predicates)
1522             .collect::<SmallVec<[_; 8]>>();
1523         v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1524         v.dedup();
1525         let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1526
1527         // Use explicitly-specified region bound.
1528         let region_bound = if !lifetime.is_elided() {
1529             self.ast_region_to_region(lifetime, None)
1530         } else {
1531             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1532                 if tcx.named_region(lifetime.hir_id).is_some() {
1533                     self.ast_region_to_region(lifetime, None)
1534                 } else {
1535                     self.re_infer(None, span).unwrap_or_else(|| {
1536                         let mut err = struct_span_err!(
1537                             tcx.sess,
1538                             span,
1539                             E0228,
1540                             "the lifetime bound for this object type cannot be deduced \
1541                              from context; please supply an explicit bound"
1542                         );
1543                         if borrowed {
1544                             // We will have already emitted an error E0106 complaining about a
1545                             // missing named lifetime in `&dyn Trait`, so we elide this one.
1546                             err.delay_as_bug();
1547                         } else {
1548                             err.emit();
1549                         }
1550                         tcx.lifetimes.re_static
1551                     })
1552                 }
1553             })
1554         };
1555         debug!("region_bound: {:?}", region_bound);
1556
1557         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1558         debug!("trait_object_type: {:?}", ty);
1559         ty
1560     }
1561
1562     fn report_ambiguous_associated_type(
1563         &self,
1564         span: Span,
1565         type_str: &str,
1566         trait_str: &str,
1567         name: Symbol,
1568     ) -> ErrorGuaranteed {
1569         let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1570         if let (true, Ok(snippet)) = (
1571             self.tcx()
1572                 .resolutions(())
1573                 .confused_type_with_std_module
1574                 .keys()
1575                 .any(|full_span| full_span.contains(span)),
1576             self.tcx().sess.source_map().span_to_snippet(span),
1577         ) {
1578             err.span_suggestion(
1579                 span,
1580                 "you are looking for the module in `std`, not the primitive type",
1581                 format!("std::{}", snippet),
1582                 Applicability::MachineApplicable,
1583             );
1584         } else {
1585             err.span_suggestion(
1586                 span,
1587                 "use fully-qualified syntax",
1588                 format!("<{} as {}>::{}", type_str, trait_str, name),
1589                 Applicability::HasPlaceholders,
1590             );
1591         }
1592         err.emit()
1593     }
1594
1595     // Search for a bound on a type parameter which includes the associated item
1596     // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1597     // This function will fail if there are no suitable bounds or there is
1598     // any ambiguity.
1599     fn find_bound_for_assoc_item(
1600         &self,
1601         ty_param_def_id: LocalDefId,
1602         assoc_name: Ident,
1603         span: Span,
1604     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1605         let tcx = self.tcx();
1606
1607         debug!(
1608             "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1609             ty_param_def_id, assoc_name, span,
1610         );
1611
1612         let predicates = &self
1613             .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1614             .predicates;
1615
1616         debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1617
1618         let param_name = tcx.hir().ty_param_name(ty_param_def_id);
1619         self.one_bound_for_assoc_type(
1620             || {
1621                 traits::transitive_bounds_that_define_assoc_type(
1622                     tcx,
1623                     predicates.iter().filter_map(|(p, _)| {
1624                         Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1625                     }),
1626                     assoc_name,
1627                 )
1628             },
1629             || param_name.to_string(),
1630             assoc_name,
1631             span,
1632             || None,
1633         )
1634     }
1635
1636     // Checks that `bounds` contains exactly one element and reports appropriate
1637     // errors otherwise.
1638     fn one_bound_for_assoc_type<I>(
1639         &self,
1640         all_candidates: impl Fn() -> I,
1641         ty_param_name: impl Fn() -> String,
1642         assoc_name: Ident,
1643         span: Span,
1644         is_equality: impl Fn() -> Option<String>,
1645     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1646     where
1647         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1648     {
1649         let mut matching_candidates = all_candidates()
1650             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1651         let mut const_candidates = all_candidates()
1652             .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
1653
1654         let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1655             (Some(bound), _) => (bound, matching_candidates.next()),
1656             (None, Some(bound)) => (bound, const_candidates.next()),
1657             (None, None) => {
1658                 let reported = self.complain_about_assoc_type_not_found(
1659                     all_candidates,
1660                     &ty_param_name(),
1661                     assoc_name,
1662                     span,
1663                 );
1664                 return Err(reported);
1665             }
1666         };
1667         debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1668
1669         if let Some(bound2) = next_cand {
1670             debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1671
1672             let is_equality = is_equality();
1673             let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1674             let mut err = if is_equality.is_some() {
1675                 // More specific Error Index entry.
1676                 struct_span_err!(
1677                     self.tcx().sess,
1678                     span,
1679                     E0222,
1680                     "ambiguous associated type `{}` in bounds of `{}`",
1681                     assoc_name,
1682                     ty_param_name()
1683                 )
1684             } else {
1685                 struct_span_err!(
1686                     self.tcx().sess,
1687                     span,
1688                     E0221,
1689                     "ambiguous associated type `{}` in bounds of `{}`",
1690                     assoc_name,
1691                     ty_param_name()
1692                 )
1693             };
1694             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1695
1696             let mut where_bounds = vec![];
1697             for bound in bounds {
1698                 let bound_id = bound.def_id();
1699                 let bound_span = self
1700                     .tcx()
1701                     .associated_items(bound_id)
1702                     .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1703                     .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1704
1705                 if let Some(bound_span) = bound_span {
1706                     err.span_label(
1707                         bound_span,
1708                         format!(
1709                             "ambiguous `{}` from `{}`",
1710                             assoc_name,
1711                             bound.print_only_trait_path(),
1712                         ),
1713                     );
1714                     if let Some(constraint) = &is_equality {
1715                         where_bounds.push(format!(
1716                             "        T: {trait}::{assoc} = {constraint}",
1717                             trait=bound.print_only_trait_path(),
1718                             assoc=assoc_name,
1719                             constraint=constraint,
1720                         ));
1721                     } else {
1722                         err.span_suggestion_verbose(
1723                             span.with_hi(assoc_name.span.lo()),
1724                             "use fully qualified syntax to disambiguate",
1725                             format!(
1726                                 "<{} as {}>::",
1727                                 ty_param_name(),
1728                                 bound.print_only_trait_path(),
1729                             ),
1730                             Applicability::MaybeIncorrect,
1731                         );
1732                     }
1733                 } else {
1734                     err.note(&format!(
1735                         "associated type `{}` could derive from `{}`",
1736                         ty_param_name(),
1737                         bound.print_only_trait_path(),
1738                     ));
1739                 }
1740             }
1741             if !where_bounds.is_empty() {
1742                 err.help(&format!(
1743                     "consider introducing a new type parameter `T` and adding `where` constraints:\
1744                      \n    where\n        T: {},\n{}",
1745                     ty_param_name(),
1746                     where_bounds.join(",\n"),
1747                 ));
1748             }
1749             let reported = err.emit();
1750             if !where_bounds.is_empty() {
1751                 return Err(reported);
1752             }
1753         }
1754
1755         Ok(bound)
1756     }
1757
1758     // Create a type from a path to an associated type.
1759     // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1760     // and item_segment is the path segment for `D`. We return a type and a def for
1761     // the whole path.
1762     // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1763     // parameter or `Self`.
1764     // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1765     // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1766     pub fn associated_path_to_ty(
1767         &self,
1768         hir_ref_id: hir::HirId,
1769         span: Span,
1770         qself_ty: Ty<'tcx>,
1771         qself_res: Res,
1772         assoc_segment: &hir::PathSegment<'_>,
1773         permit_variants: bool,
1774     ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1775         let tcx = self.tcx();
1776         let assoc_ident = assoc_segment.ident;
1777
1778         debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1779
1780         // Check if we have an enum variant.
1781         let mut variant_resolution = None;
1782         if let ty::Adt(adt_def, _) = qself_ty.kind() {
1783             if adt_def.is_enum() {
1784                 let variant_def = adt_def
1785                     .variants()
1786                     .iter()
1787                     .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
1788                 if let Some(variant_def) = variant_def {
1789                     if permit_variants {
1790                         tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1791                         self.prohibit_generics(slice::from_ref(assoc_segment));
1792                         return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1793                     } else {
1794                         variant_resolution = Some(variant_def.def_id);
1795                     }
1796                 }
1797             }
1798         }
1799
1800         // Find the type of the associated item, and the trait where the associated
1801         // item is declared.
1802         let bound = match (&qself_ty.kind(), qself_res) {
1803             (_, Res::SelfTy { trait_: Some(_), alias_to: Some((impl_def_id, _)) }) => {
1804                 // `Self` in an impl of a trait -- we have a concrete self type and a
1805                 // trait reference.
1806                 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1807                     // A cycle error occurred, most likely.
1808                     let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
1809                     return Err(guar);
1810                 };
1811
1812                 self.one_bound_for_assoc_type(
1813                     || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1814                     || "Self".to_string(),
1815                     assoc_ident,
1816                     span,
1817                     || None,
1818                 )?
1819             }
1820             (
1821                 &ty::Param(_),
1822                 Res::SelfTy { trait_: Some(param_did), alias_to: None }
1823                 | Res::Def(DefKind::TyParam, param_did),
1824             ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1825             _ => {
1826                 let reported = if variant_resolution.is_some() {
1827                     // Variant in type position
1828                     let msg = format!("expected type, found variant `{}`", assoc_ident);
1829                     tcx.sess.span_err(span, &msg)
1830                 } else if qself_ty.is_enum() {
1831                     let mut err = struct_span_err!(
1832                         tcx.sess,
1833                         assoc_ident.span,
1834                         E0599,
1835                         "no variant named `{}` found for enum `{}`",
1836                         assoc_ident,
1837                         qself_ty,
1838                     );
1839
1840                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1841                     if let Some(suggested_name) = find_best_match_for_name(
1842                         &adt_def
1843                             .variants()
1844                             .iter()
1845                             .map(|variant| variant.name)
1846                             .collect::<Vec<Symbol>>(),
1847                         assoc_ident.name,
1848                         None,
1849                     ) {
1850                         err.span_suggestion(
1851                             assoc_ident.span,
1852                             "there is a variant with a similar name",
1853                             suggested_name.to_string(),
1854                             Applicability::MaybeIncorrect,
1855                         );
1856                     } else {
1857                         err.span_label(
1858                             assoc_ident.span,
1859                             format!("variant not found in `{}`", qself_ty),
1860                         );
1861                     }
1862
1863                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
1864                         let sp = tcx.sess.source_map().guess_head_span(sp);
1865                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1866                     }
1867
1868                     err.emit()
1869                 } else if let Some(reported) = qself_ty.error_reported() {
1870                     reported
1871                 } else {
1872                     // Don't print `TyErr` to the user.
1873                     self.report_ambiguous_associated_type(
1874                         span,
1875                         &qself_ty.to_string(),
1876                         "Trait",
1877                         assoc_ident.name,
1878                     )
1879                 };
1880                 return Err(reported);
1881             }
1882         };
1883
1884         let trait_did = bound.def_id();
1885         let (assoc_ident, def_scope) =
1886             tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1887
1888         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1889         // of calling `filter_by_name_and_kind`.
1890         let item = tcx.associated_items(trait_did).in_definition_order().find(|i| {
1891             i.kind.namespace() == Namespace::TypeNS
1892                 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1893         });
1894         // Assume that if it's not matched, there must be a const defined with the same name
1895         // but it was used in a type position.
1896         let Some(item) = item else {
1897             let msg = format!("found associated const `{assoc_ident}` when type was expected");
1898             let guar = tcx.sess.struct_span_err(span, &msg).emit();
1899             return Err(guar);
1900         };
1901
1902         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1903         let ty = self.normalize_ty(span, ty);
1904
1905         let kind = DefKind::AssocTy;
1906         if !item.vis.is_accessible_from(def_scope, tcx) {
1907             let kind = kind.descr(item.def_id);
1908             let msg = format!("{} `{}` is private", kind, assoc_ident);
1909             tcx.sess
1910                 .struct_span_err(span, &msg)
1911                 .span_label(span, &format!("private {}", kind))
1912                 .emit();
1913         }
1914         tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
1915
1916         if let Some(variant_def_id) = variant_resolution {
1917             tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1918                 let mut err = lint.build("ambiguous associated item");
1919                 let mut could_refer_to = |kind: DefKind, def_id, also| {
1920                     let note_msg = format!(
1921                         "`{}` could{} refer to the {} defined here",
1922                         assoc_ident,
1923                         also,
1924                         kind.descr(def_id)
1925                     );
1926                     err.span_note(tcx.def_span(def_id), &note_msg);
1927                 };
1928
1929                 could_refer_to(DefKind::Variant, variant_def_id, "");
1930                 could_refer_to(kind, item.def_id, " also");
1931
1932                 err.span_suggestion(
1933                     span,
1934                     "use fully-qualified syntax",
1935                     format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1936                     Applicability::MachineApplicable,
1937                 );
1938
1939                 err.emit();
1940             });
1941         }
1942         Ok((ty, kind, item.def_id))
1943     }
1944
1945     fn qpath_to_ty(
1946         &self,
1947         span: Span,
1948         opt_self_ty: Option<Ty<'tcx>>,
1949         item_def_id: DefId,
1950         trait_segment: &hir::PathSegment<'_>,
1951         item_segment: &hir::PathSegment<'_>,
1952     ) -> Ty<'tcx> {
1953         let tcx = self.tcx();
1954
1955         let trait_def_id = tcx.parent(item_def_id).unwrap();
1956
1957         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1958
1959         let Some(self_ty) = opt_self_ty else {
1960             let path_str = tcx.def_path_str(trait_def_id);
1961
1962             let def_id = self.item_def_id();
1963
1964             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1965
1966             let parent_def_id = def_id
1967                 .and_then(|def_id| {
1968                     def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1969                 })
1970                 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
1971
1972             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1973
1974             // If the trait in segment is the same as the trait defining the item,
1975             // use the `<Self as ..>` syntax in the error.
1976             let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1977             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1978
1979             let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1980                 "Self"
1981             } else {
1982                 "Type"
1983             };
1984
1985             self.report_ambiguous_associated_type(
1986                 span,
1987                 type_name,
1988                 &path_str,
1989                 item_segment.ident.name,
1990             );
1991             return tcx.ty_error();
1992         };
1993
1994         debug!("qpath_to_ty: self_type={:?}", self_ty);
1995
1996         let trait_ref =
1997             self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false);
1998
1999         let item_substs = self.create_substs_for_associated_item(
2000             tcx,
2001             span,
2002             item_def_id,
2003             item_segment,
2004             trait_ref.substs,
2005         );
2006
2007         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2008
2009         self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2010     }
2011
2012     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2013         &self,
2014         segments: T,
2015     ) -> bool {
2016         let mut has_err = false;
2017         for segment in segments {
2018             let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2019             for arg in segment.args().args {
2020                 let (span, kind) = match arg {
2021                     hir::GenericArg::Lifetime(lt) => {
2022                         if err_for_lt {
2023                             continue;
2024                         }
2025                         err_for_lt = true;
2026                         has_err = true;
2027                         (lt.span, "lifetime")
2028                     }
2029                     hir::GenericArg::Type(ty) => {
2030                         if err_for_ty {
2031                             continue;
2032                         }
2033                         err_for_ty = true;
2034                         has_err = true;
2035                         (ty.span, "type")
2036                     }
2037                     hir::GenericArg::Const(ct) => {
2038                         if err_for_ct {
2039                             continue;
2040                         }
2041                         err_for_ct = true;
2042                         has_err = true;
2043                         (ct.span, "const")
2044                     }
2045                     hir::GenericArg::Infer(inf) => {
2046                         if err_for_ty {
2047                             continue;
2048                         }
2049                         has_err = true;
2050                         err_for_ty = true;
2051                         (inf.span, "generic")
2052                     }
2053                 };
2054                 let mut err = struct_span_err!(
2055                     self.tcx().sess,
2056                     span,
2057                     E0109,
2058                     "{} arguments are not allowed for this type",
2059                     kind,
2060                 );
2061                 err.span_label(span, format!("{} argument not allowed", kind));
2062                 err.emit();
2063                 if err_for_lt && err_for_ty && err_for_ct {
2064                     break;
2065                 }
2066             }
2067
2068             // Only emit the first error to avoid overloading the user with error messages.
2069             if let [binding, ..] = segment.args().bindings {
2070                 has_err = true;
2071                 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2072             }
2073         }
2074         has_err
2075     }
2076
2077     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2078     pub fn def_ids_for_value_path_segments(
2079         &self,
2080         segments: &[hir::PathSegment<'_>],
2081         self_ty: Option<Ty<'tcx>>,
2082         kind: DefKind,
2083         def_id: DefId,
2084     ) -> Vec<PathSeg> {
2085         // We need to extract the type parameters supplied by the user in
2086         // the path `path`. Due to the current setup, this is a bit of a
2087         // tricky-process; the problem is that resolve only tells us the
2088         // end-point of the path resolution, and not the intermediate steps.
2089         // Luckily, we can (at least for now) deduce the intermediate steps
2090         // just from the end-point.
2091         //
2092         // There are basically five cases to consider:
2093         //
2094         // 1. Reference to a constructor of a struct:
2095         //
2096         //        struct Foo<T>(...)
2097         //
2098         //    In this case, the parameters are declared in the type space.
2099         //
2100         // 2. Reference to a constructor of an enum variant:
2101         //
2102         //        enum E<T> { Foo(...) }
2103         //
2104         //    In this case, the parameters are defined in the type space,
2105         //    but may be specified either on the type or the variant.
2106         //
2107         // 3. Reference to a fn item or a free constant:
2108         //
2109         //        fn foo<T>() { }
2110         //
2111         //    In this case, the path will again always have the form
2112         //    `a::b::foo::<T>` where only the final segment should have
2113         //    type parameters. However, in this case, those parameters are
2114         //    declared on a value, and hence are in the `FnSpace`.
2115         //
2116         // 4. Reference to a method or an associated constant:
2117         //
2118         //        impl<A> SomeStruct<A> {
2119         //            fn foo<B>(...)
2120         //        }
2121         //
2122         //    Here we can have a path like
2123         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2124         //    may appear in two places. The penultimate segment,
2125         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2126         //    final segment, `foo::<B>` contains parameters in fn space.
2127         //
2128         // The first step then is to categorize the segments appropriately.
2129
2130         let tcx = self.tcx();
2131
2132         assert!(!segments.is_empty());
2133         let last = segments.len() - 1;
2134
2135         let mut path_segs = vec![];
2136
2137         match kind {
2138             // Case 1. Reference to a struct constructor.
2139             DefKind::Ctor(CtorOf::Struct, ..) => {
2140                 // Everything but the final segment should have no
2141                 // parameters at all.
2142                 let generics = tcx.generics_of(def_id);
2143                 // Variant and struct constructors use the
2144                 // generics of their parent type definition.
2145                 let generics_def_id = generics.parent.unwrap_or(def_id);
2146                 path_segs.push(PathSeg(generics_def_id, last));
2147             }
2148
2149             // Case 2. Reference to a variant constructor.
2150             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2151                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2152                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2153                     debug_assert!(adt_def.is_enum());
2154                     (adt_def.did(), last)
2155                 } else if last >= 1 && segments[last - 1].args.is_some() {
2156                     // Everything but the penultimate segment should have no
2157                     // parameters at all.
2158                     let mut def_id = def_id;
2159
2160                     // `DefKind::Ctor` -> `DefKind::Variant`
2161                     if let DefKind::Ctor(..) = kind {
2162                         def_id = tcx.parent(def_id).unwrap()
2163                     }
2164
2165                     // `DefKind::Variant` -> `DefKind::Enum`
2166                     let enum_def_id = tcx.parent(def_id).unwrap();
2167                     (enum_def_id, last - 1)
2168                 } else {
2169                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2170                     // instead of `Enum::Variant::<...>` form.
2171
2172                     // Everything but the final segment should have no
2173                     // parameters at all.
2174                     let generics = tcx.generics_of(def_id);
2175                     // Variant and struct constructors use the
2176                     // generics of their parent type definition.
2177                     (generics.parent.unwrap_or(def_id), last)
2178                 };
2179                 path_segs.push(PathSeg(generics_def_id, index));
2180             }
2181
2182             // Case 3. Reference to a top-level value.
2183             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2184                 path_segs.push(PathSeg(def_id, last));
2185             }
2186
2187             // Case 4. Reference to a method or associated const.
2188             DefKind::AssocFn | DefKind::AssocConst => {
2189                 if segments.len() >= 2 {
2190                     let generics = tcx.generics_of(def_id);
2191                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2192                 }
2193                 path_segs.push(PathSeg(def_id, last));
2194             }
2195
2196             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2197         }
2198
2199         debug!("path_segs = {:?}", path_segs);
2200
2201         path_segs
2202     }
2203
2204     // Check a type `Path` and convert it to a `Ty`.
2205     pub fn res_to_ty(
2206         &self,
2207         opt_self_ty: Option<Ty<'tcx>>,
2208         path: &hir::Path<'_>,
2209         permit_variants: bool,
2210     ) -> Ty<'tcx> {
2211         let tcx = self.tcx();
2212
2213         debug!(
2214             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2215             path.res, opt_self_ty, path.segments
2216         );
2217
2218         let span = path.span;
2219         match path.res {
2220             Res::Def(DefKind::OpaqueTy, did) => {
2221                 // Check for desugared `impl Trait`.
2222                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2223                 let item_segment = path.segments.split_last().unwrap();
2224                 self.prohibit_generics(item_segment.1);
2225                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2226                 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2227             }
2228             Res::Def(
2229                 DefKind::Enum
2230                 | DefKind::TyAlias
2231                 | DefKind::Struct
2232                 | DefKind::Union
2233                 | DefKind::ForeignTy,
2234                 did,
2235             ) => {
2236                 assert_eq!(opt_self_ty, None);
2237                 self.prohibit_generics(path.segments.split_last().unwrap().1);
2238                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2239             }
2240             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2241                 // Convert "variant type" as if it were a real type.
2242                 // The resulting `Ty` is type of the variant's enum for now.
2243                 assert_eq!(opt_self_ty, None);
2244
2245                 let path_segs =
2246                     self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
2247                 let generic_segs: FxHashSet<_> =
2248                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2249                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2250                     |(index, seg)| {
2251                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2252                     },
2253                 ));
2254
2255                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2256                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2257             }
2258             Res::Def(DefKind::TyParam, def_id) => {
2259                 assert_eq!(opt_self_ty, None);
2260                 self.prohibit_generics(path.segments);
2261
2262                 let def_id = def_id.expect_local();
2263                 let item_def_id = tcx.hir().ty_param_owner(def_id);
2264                 let generics = tcx.generics_of(item_def_id);
2265                 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2266                 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2267             }
2268             Res::SelfTy { trait_: Some(_), alias_to: None } => {
2269                 // `Self` in trait or type alias.
2270                 assert_eq!(opt_self_ty, None);
2271                 self.prohibit_generics(path.segments);
2272                 tcx.types.self_param
2273             }
2274             Res::SelfTy { trait_: _, alias_to: Some((def_id, forbid_generic)) } => {
2275                 // `Self` in impl (we know the concrete type).
2276                 assert_eq!(opt_self_ty, None);
2277                 self.prohibit_generics(path.segments);
2278                 // Try to evaluate any array length constants.
2279                 let ty = tcx.at(span).type_of(def_id);
2280                 // HACK(min_const_generics): Forbid generic `Self` types
2281                 // here as we can't easily do that during nameres.
2282                 //
2283                 // We do this before normalization as we otherwise allow
2284                 // ```rust
2285                 // trait AlwaysApplicable { type Assoc; }
2286                 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2287                 //
2288                 // trait BindsParam<T> {
2289                 //     type ArrayTy;
2290                 // }
2291                 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2292                 //    type ArrayTy = [u8; Self::MAX];
2293                 // }
2294                 // ```
2295                 // Note that the normalization happens in the param env of
2296                 // the anon const, which is empty. This is why the
2297                 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2298                 // this to compile if we were to normalize here.
2299                 if forbid_generic && ty.needs_subst() {
2300                     let mut err = tcx.sess.struct_span_err(
2301                         path.span,
2302                         "generic `Self` types are currently not permitted in anonymous constants",
2303                     );
2304                     if let Some(hir::Node::Item(&hir::Item {
2305                         kind: hir::ItemKind::Impl(ref impl_),
2306                         ..
2307                     })) = tcx.hir().get_if_local(def_id)
2308                     {
2309                         err.span_note(impl_.self_ty.span, "not a concrete type");
2310                     }
2311                     err.emit();
2312                     tcx.ty_error()
2313                 } else {
2314                     self.normalize_ty(span, ty)
2315                 }
2316             }
2317             Res::Def(DefKind::AssocTy, def_id) => {
2318                 debug_assert!(path.segments.len() >= 2);
2319                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2320                 self.qpath_to_ty(
2321                     span,
2322                     opt_self_ty,
2323                     def_id,
2324                     &path.segments[path.segments.len() - 2],
2325                     path.segments.last().unwrap(),
2326                 )
2327             }
2328             Res::PrimTy(prim_ty) => {
2329                 assert_eq!(opt_self_ty, None);
2330                 self.prohibit_generics(path.segments);
2331                 match prim_ty {
2332                     hir::PrimTy::Bool => tcx.types.bool,
2333                     hir::PrimTy::Char => tcx.types.char,
2334                     hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2335                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2336                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2337                     hir::PrimTy::Str => tcx.types.str_,
2338                 }
2339             }
2340             Res::Err => {
2341                 self.set_tainted_by_errors();
2342                 self.tcx().ty_error()
2343             }
2344             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2345         }
2346     }
2347
2348     /// Parses the programmer's textual representation of a type into our
2349     /// internal notion of a type.
2350     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2351         self.ast_ty_to_ty_inner(ast_ty, false, false)
2352     }
2353
2354     /// Parses the programmer's textual representation of a type into our
2355     /// internal notion of a type.  This is meant to be used within a path.
2356     pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2357         self.ast_ty_to_ty_inner(ast_ty, false, true)
2358     }
2359
2360     /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2361     /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2362     #[tracing::instrument(level = "debug", skip(self))]
2363     fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2364         let tcx = self.tcx();
2365
2366         let result_ty = match ast_ty.kind {
2367             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2368             hir::TyKind::Ptr(ref mt) => {
2369                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2370             }
2371             hir::TyKind::Rptr(ref region, ref mt) => {
2372                 let r = self.ast_region_to_region(region, None);
2373                 debug!(?r);
2374                 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2375                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2376             }
2377             hir::TyKind::Never => tcx.types.never,
2378             hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2379             hir::TyKind::BareFn(bf) => {
2380                 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2381
2382                 tcx.mk_fn_ptr(self.ty_of_fn(
2383                     ast_ty.hir_id,
2384                     bf.unsafety,
2385                     bf.abi,
2386                     bf.decl,
2387                     None,
2388                     Some(ast_ty),
2389                 ))
2390             }
2391             hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2392                 self.maybe_lint_bare_trait(ast_ty, in_path);
2393                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2394             }
2395             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2396                 debug!(?maybe_qself, ?path);
2397                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2398                 self.res_to_ty(opt_self_ty, path, false)
2399             }
2400             hir::TyKind::OpaqueDef(item_id, lifetimes) => {
2401                 let opaque_ty = tcx.hir().item(item_id);
2402                 let def_id = item_id.def_id.to_def_id();
2403
2404                 match opaque_ty.kind {
2405                     hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => self
2406                         .impl_trait_ty_to_ty(
2407                             def_id,
2408                             lifetimes,
2409                             matches!(
2410                                 origin,
2411                                 hir::OpaqueTyOrigin::FnReturn(..)
2412                                     | hir::OpaqueTyOrigin::AsyncFn(..)
2413                             ),
2414                         ),
2415                     ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2416                 }
2417             }
2418             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2419                 debug!(?qself, ?segment);
2420                 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2421
2422                 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = qself.kind {
2423                     path.res
2424                 } else {
2425                     Res::Err
2426                 };
2427                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2428                     .map(|(ty, _, _)| ty)
2429                     .unwrap_or_else(|_| tcx.ty_error())
2430             }
2431             hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2432                 let def_id = tcx.require_lang_item(lang_item, Some(span));
2433                 let (substs, _) = self.create_substs_for_ast_path(
2434                     span,
2435                     def_id,
2436                     &[],
2437                     &hir::PathSegment::invalid(),
2438                     &GenericArgs::none(),
2439                     true,
2440                     None,
2441                 );
2442                 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2443             }
2444             hir::TyKind::Array(ref ty, ref length) => {
2445                 let length = match length {
2446                     &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2447                     hir::ArrayLen::Body(constant) => {
2448                         let length_def_id = tcx.hir().local_def_id(constant.hir_id);
2449                         ty::Const::from_anon_const(tcx, length_def_id)
2450                     }
2451                 };
2452
2453                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
2454                 self.normalize_ty(ast_ty.span, array_ty)
2455             }
2456             hir::TyKind::Typeof(ref e) => {
2457                 let ty = tcx.type_of(tcx.hir().local_def_id(e.hir_id));
2458                 let span = ast_ty.span;
2459                 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2460                     span,
2461                     ty,
2462                     opt_sugg: Some((span, Applicability::MachineApplicable))
2463                         .filter(|_| ty.is_suggestable(tcx)),
2464                 });
2465
2466                 ty
2467             }
2468             hir::TyKind::Infer => {
2469                 // Infer also appears as the type of arguments or return
2470                 // values in an ExprKind::Closure, or as
2471                 // the type of local variables. Both of these cases are
2472                 // handled specially and will not descend into this routine.
2473                 self.ty_infer(None, ast_ty.span)
2474             }
2475             hir::TyKind::Err => tcx.ty_error(),
2476         };
2477
2478         debug!(?result_ty);
2479
2480         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2481         result_ty
2482     }
2483
2484     fn impl_trait_ty_to_ty(
2485         &self,
2486         def_id: DefId,
2487         lifetimes: &[hir::GenericArg<'_>],
2488         replace_parent_lifetimes: bool,
2489     ) -> Ty<'tcx> {
2490         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2491         let tcx = self.tcx();
2492
2493         let generics = tcx.generics_of(def_id);
2494
2495         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2496         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2497             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2498                 // Our own parameters are the resolved lifetimes.
2499                 if let GenericParamDefKind::Lifetime = param.kind {
2500                     if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2501                         self.ast_region_to_region(lifetime, None).into()
2502                     } else {
2503                         bug!()
2504                     }
2505                 } else {
2506                     bug!()
2507                 }
2508             } else {
2509                 match param.kind {
2510                     // For RPIT (return position impl trait), only lifetimes
2511                     // mentioned in the impl Trait predicate are captured by
2512                     // the opaque type, so the lifetime parameters from the
2513                     // parent item need to be replaced with `'static`.
2514                     //
2515                     // For `impl Trait` in the types of statics, constants,
2516                     // locals and type aliases. These capture all parent
2517                     // lifetimes, so they can use their identity subst.
2518                     GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2519                         tcx.lifetimes.re_static.into()
2520                     }
2521                     _ => tcx.mk_param_from_def(param),
2522                 }
2523             }
2524         });
2525         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2526
2527         let ty = tcx.mk_opaque(def_id, substs);
2528         debug!("impl_trait_ty_to_ty: {}", ty);
2529         ty
2530     }
2531
2532     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2533         match ty.kind {
2534             hir::TyKind::Infer if expected_ty.is_some() => {
2535                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2536                 expected_ty.unwrap()
2537             }
2538             _ => self.ast_ty_to_ty(ty),
2539         }
2540     }
2541
2542     pub fn ty_of_fn(
2543         &self,
2544         hir_id: hir::HirId,
2545         unsafety: hir::Unsafety,
2546         abi: abi::Abi,
2547         decl: &hir::FnDecl<'_>,
2548         generics: Option<&hir::Generics<'_>>,
2549         hir_ty: Option<&hir::Ty<'_>>,
2550     ) -> ty::PolyFnSig<'tcx> {
2551         debug!("ty_of_fn");
2552
2553         let tcx = self.tcx();
2554         let bound_vars = tcx.late_bound_vars(hir_id);
2555         debug!(?bound_vars);
2556
2557         // We proactively collect all the inferred type params to emit a single error per fn def.
2558         let mut visitor = HirPlaceholderCollector::default();
2559         let mut infer_replacements = vec![];
2560
2561         if let Some(generics) = generics {
2562             walk_generics(&mut visitor, generics);
2563         }
2564
2565         let input_tys: Vec<_> = decl
2566             .inputs
2567             .iter()
2568             .enumerate()
2569             .map(|(i, a)| {
2570                 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
2571                     if let Some(suggested_ty) =
2572                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
2573                     {
2574                         infer_replacements.push((a.span, suggested_ty.to_string()));
2575                         return suggested_ty;
2576                     }
2577                 }
2578
2579                 // Only visit the type looking for `_` if we didn't fix the type above
2580                 visitor.visit_ty(a);
2581                 self.ty_of_arg(a, None)
2582             })
2583             .collect();
2584
2585         let output_ty = match decl.output {
2586             hir::FnRetTy::Return(output) => {
2587                 if let hir::TyKind::Infer = output.kind
2588                     && !self.allow_ty_infer()
2589                     && let Some(suggested_ty) =
2590                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
2591                 {
2592                     infer_replacements.push((output.span, suggested_ty.to_string()));
2593                     suggested_ty
2594                 } else {
2595                     visitor.visit_ty(output);
2596                     self.ast_ty_to_ty(output)
2597                 }
2598             }
2599             hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2600         };
2601
2602         debug!("ty_of_fn: output_ty={:?}", output_ty);
2603
2604         let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
2605         let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2606
2607         if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
2608             // We always collect the spans for placeholder types when evaluating `fn`s, but we
2609             // only want to emit an error complaining about them if infer types (`_`) are not
2610             // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2611             // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2612
2613             let mut diag = crate::collect::placeholder_type_error_diag(
2614                 tcx,
2615                 generics,
2616                 visitor.0,
2617                 infer_replacements.iter().map(|(s, _)| *s).collect(),
2618                 true,
2619                 hir_ty,
2620                 "function",
2621             );
2622
2623             if !infer_replacements.is_empty() {
2624                 diag.multipart_suggestion(&format!(
2625                     "try replacing `_` with the type{} in the corresponding trait method signature",
2626                     rustc_errors::pluralize!(infer_replacements.len()),
2627                 ), infer_replacements, Applicability::MachineApplicable);
2628             }
2629
2630             diag.emit();
2631         }
2632
2633         // Find any late-bound regions declared in return type that do
2634         // not appear in the arguments. These are not well-formed.
2635         //
2636         // Example:
2637         //     for<'a> fn() -> &'a str <-- 'a is bad
2638         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2639         let inputs = bare_fn_ty.inputs();
2640         let late_bound_in_args =
2641             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2642         let output = bare_fn_ty.output();
2643         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2644
2645         self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2646             struct_span_err!(
2647                 tcx.sess,
2648                 decl.output.span(),
2649                 E0581,
2650                 "return type references {}, which is not constrained by the fn input types",
2651                 br_name
2652             )
2653         });
2654
2655         bare_fn_ty
2656     }
2657
2658     /// Given a fn_hir_id for a impl function, suggest the type that is found on the
2659     /// corresponding function in the trait that the impl implements, if it exists.
2660     /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
2661     /// corresponds to the return type.
2662     fn suggest_trait_fn_ty_for_impl_fn_infer(
2663         &self,
2664         fn_hir_id: hir::HirId,
2665         arg_idx: Option<usize>,
2666     ) -> Option<Ty<'tcx>> {
2667         let tcx = self.tcx();
2668         let hir = tcx.hir();
2669
2670         let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
2671             hir.get(fn_hir_id) else { return None };
2672         let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
2673                 hir.get(hir.get_parent_node(fn_hir_id)) else { bug!("ImplItem should have Impl parent") };
2674
2675         let trait_ref =
2676             self.instantiate_mono_trait_ref(i.of_trait.as_ref()?, self.ast_ty_to_ty(i.self_ty));
2677
2678         let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
2679             tcx,
2680             *ident,
2681             ty::AssocKind::Fn,
2682             trait_ref.def_id,
2683         )?;
2684
2685         let fn_sig = tcx.fn_sig(assoc.def_id).subst(
2686             tcx,
2687             trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
2688         );
2689
2690         let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
2691
2692         Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
2693     }
2694
2695     fn validate_late_bound_regions(
2696         &self,
2697         constrained_regions: FxHashSet<ty::BoundRegionKind>,
2698         referenced_regions: FxHashSet<ty::BoundRegionKind>,
2699         generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2700     ) {
2701         for br in referenced_regions.difference(&constrained_regions) {
2702             let br_name = match *br {
2703                 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2704                 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2705             };
2706
2707             let mut err = generate_err(&br_name);
2708
2709             if let ty::BrAnon(_) = *br {
2710                 // The only way for an anonymous lifetime to wind up
2711                 // in the return type but **also** be unconstrained is
2712                 // if it only appears in "associated types" in the
2713                 // input. See #47511 and #62200 for examples. In this case,
2714                 // though we can easily give a hint that ought to be
2715                 // relevant.
2716                 err.note(
2717                     "lifetimes appearing in an associated type are not considered constrained",
2718                 );
2719             }
2720
2721             err.emit();
2722         }
2723     }
2724
2725     /// Given the bounds on an object, determines what single region bound (if any) we can
2726     /// use to summarize this type. The basic idea is that we will use the bound the user
2727     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2728     /// for region bounds. It may be that we can derive no bound at all, in which case
2729     /// we return `None`.
2730     fn compute_object_lifetime_bound(
2731         &self,
2732         span: Span,
2733         existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2734     ) -> Option<ty::Region<'tcx>> // if None, use the default
2735     {
2736         let tcx = self.tcx();
2737
2738         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2739
2740         // No explicit region bound specified. Therefore, examine trait
2741         // bounds and see if we can derive region bounds from those.
2742         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2743
2744         // If there are no derived region bounds, then report back that we
2745         // can find no region bound. The caller will use the default.
2746         if derived_region_bounds.is_empty() {
2747             return None;
2748         }
2749
2750         // If any of the derived region bounds are 'static, that is always
2751         // the best choice.
2752         if derived_region_bounds.iter().any(|r| r.is_static()) {
2753             return Some(tcx.lifetimes.re_static);
2754         }
2755
2756         // Determine whether there is exactly one unique region in the set
2757         // of derived region bounds. If so, use that. Otherwise, report an
2758         // error.
2759         let r = derived_region_bounds[0];
2760         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2761             tcx.sess.emit_err(AmbiguousLifetimeBound { span });
2762         }
2763         Some(r)
2764     }
2765
2766     fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
2767         let tcx = self.tcx();
2768         if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
2769             self_ty.kind
2770         {
2771             let needs_bracket = in_path
2772                 && !tcx
2773                     .sess
2774                     .source_map()
2775                     .span_to_prev_source(self_ty.span)
2776                     .ok()
2777                     .map_or(false, |s| s.trim_end().ends_with('<'));
2778
2779             let is_global = poly_trait_ref.trait_ref.path.is_global();
2780             let sugg = Vec::from_iter([
2781                 (
2782                     self_ty.span.shrink_to_lo(),
2783                     format!(
2784                         "{}dyn {}",
2785                         if needs_bracket { "<" } else { "" },
2786                         if is_global { "(" } else { "" },
2787                     ),
2788                 ),
2789                 (
2790                     self_ty.span.shrink_to_hi(),
2791                     format!(
2792                         "{}{}",
2793                         if is_global { ")" } else { "" },
2794                         if needs_bracket { ">" } else { "" },
2795                     ),
2796                 ),
2797             ]);
2798             if self_ty.span.edition() >= Edition::Edition2021 {
2799                 let msg = "trait objects must include the `dyn` keyword";
2800                 let label = "add `dyn` keyword before this trait";
2801                 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg)
2802                     .multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable)
2803                     .emit();
2804             } else {
2805                 let msg = "trait objects without an explicit `dyn` are deprecated";
2806                 tcx.struct_span_lint_hir(
2807                     BARE_TRAIT_OBJECTS,
2808                     self_ty.hir_id,
2809                     self_ty.span,
2810                     |lint| {
2811                         lint.build(msg)
2812                             .multipart_suggestion_verbose(
2813                                 "use `dyn`",
2814                                 sugg,
2815                                 Applicability::MachineApplicable,
2816                             )
2817                             .emit();
2818                     },
2819                 );
2820             }
2821         }
2822     }
2823 }