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