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