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