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