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