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