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