]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Rollup merge of #56210 - RalfJung:c_str, r=oli-obk
[rust.git] / src / librustc_typeck / astconv.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Conversion from AST representation of types to the `ty.rs`
12 //! representation.  The main routine here is `ast_ty_to_ty()`: each use
13 //! is parameterized by an instance of `AstConv`.
14
15 use smallvec::SmallVec;
16 use hir::{self, GenericArg, GenericArgs};
17 use hir::def::Def;
18 use hir::def_id::DefId;
19 use hir::HirVec;
20 use middle::resolve_lifetime as rl;
21 use namespace::Namespace;
22 use rustc::ty::subst::{Kind, Subst, Substs};
23 use rustc::traits;
24 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
25 use rustc::ty::{GenericParamDef, GenericParamDefKind};
26 use rustc::ty::wf::object_region_bounds;
27 use rustc_data_structures::sync::Lrc;
28 use rustc_target::spec::abi;
29 use std::collections::BTreeSet;
30 use std::slice;
31 use require_c_abi_if_variadic;
32 use util::common::ErrorReported;
33 use util::nodemap::FxHashMap;
34 use errors::{Applicability, FatalError, DiagnosticId};
35 use lint;
36
37 use std::iter;
38 use syntax::ast;
39 use syntax::feature_gate::{GateIssue, emit_feature_err};
40 use syntax::ptr::P;
41 use syntax::util::lev_distance::find_best_match_for_name;
42 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
43
44 pub trait AstConv<'gcx, 'tcx> {
45     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
46
47     /// Returns the set of bounds in scope for the type parameter with
48     /// the given id.
49     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
50                                  -> Lrc<ty::GenericPredicates<'tcx>>;
51
52     /// What lifetime should we use when a lifetime is omitted (and not elided)?
53     fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
54                 -> Option<ty::Region<'tcx>>;
55
56     /// What type should we use when a type is omitted?
57     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
58
59     /// Same as ty_infer, but with a known type parameter definition.
60     fn ty_infer_for_def(&self,
61                         _def: &ty::GenericParamDef,
62                         span: Span) -> Ty<'tcx> {
63         self.ty_infer(span)
64     }
65
66     /// Projecting an associated type from a (potentially)
67     /// higher-ranked trait reference is more complicated, because of
68     /// the possibility of late-bound regions appearing in the
69     /// associated type binding. This is not legal in function
70     /// signatures for that reason. In a function body, we can always
71     /// handle it because we can use inference variables to remove the
72     /// late-bound regions.
73     fn projected_ty_from_poly_trait_ref(&self,
74                                         span: Span,
75                                         item_def_id: DefId,
76                                         poly_trait_ref: ty::PolyTraitRef<'tcx>)
77                                         -> Ty<'tcx>;
78
79     /// Normalize an associated type coming from the user.
80     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
81
82     /// Invoked when we encounter an error from some prior pass
83     /// (e.g. resolve) that is translated into a ty-error. This is
84     /// used to help suppress derived errors typeck might otherwise
85     /// report.
86     fn set_tainted_by_errors(&self);
87
88     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
89 }
90
91 struct ConvertedBinding<'tcx> {
92     item_name: ast::Ident,
93     ty: Ty<'tcx>,
94     span: Span,
95 }
96
97 #[derive(PartialEq)]
98 enum GenericArgPosition {
99     Type,
100     Value, // e.g. functions
101     MethodCall,
102 }
103
104 /// Dummy type used for the `Self` of a `TraitRef` created for converting
105 /// a trait object, and which gets removed in `ExistentialTraitRef`.
106 /// This type must not appear anywhere in other converted types.
107 const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
108
109 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o {
110     pub fn ast_region_to_region(&self,
111         lifetime: &hir::Lifetime,
112         def: Option<&ty::GenericParamDef>)
113         -> ty::Region<'tcx>
114     {
115         let tcx = self.tcx();
116         let lifetime_name = |def_id| {
117             tcx.hir.name(tcx.hir.as_local_node_id(def_id).unwrap()).as_interned_str()
118         };
119
120         let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
121         let r = match tcx.named_region(hir_id) {
122             Some(rl::Region::Static) => {
123                 tcx.types.re_static
124             }
125
126             Some(rl::Region::LateBound(debruijn, id, _)) => {
127                 let name = lifetime_name(id);
128                 tcx.mk_region(ty::ReLateBound(debruijn,
129                     ty::BrNamed(id, name)))
130             }
131
132             Some(rl::Region::LateBoundAnon(debruijn, index)) => {
133                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
134             }
135
136             Some(rl::Region::EarlyBound(index, id, _)) => {
137                 let name = lifetime_name(id);
138                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
139                     def_id: id,
140                     index,
141                     name,
142                 }))
143             }
144
145             Some(rl::Region::Free(scope, id)) => {
146                 let name = lifetime_name(id);
147                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
148                     scope,
149                     bound_region: ty::BrNamed(id, name)
150                 }))
151
152                 // (*) -- not late-bound, won't change
153             }
154
155             None => {
156                 self.re_infer(lifetime.span, def)
157                     .unwrap_or_else(|| {
158                         // This indicates an illegal lifetime
159                         // elision. `resolve_lifetime` should have
160                         // reported an error in this case -- but if
161                         // not, let's error out.
162                         tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
163
164                         // Supply some dummy value. We don't have an
165                         // `re_error`, annoyingly, so use `'static`.
166                         tcx.types.re_static
167                     })
168             }
169         };
170
171         debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
172                lifetime,
173                r);
174
175         r
176     }
177
178     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
179     /// returns an appropriate set of substitutions for this particular reference to `I`.
180     pub fn ast_path_substs_for_ty(&self,
181         span: Span,
182         def_id: DefId,
183         item_segment: &hir::PathSegment)
184         -> &'tcx Substs<'tcx>
185     {
186         let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| {
187             self.create_substs_for_ast_path(
188                 span,
189                 def_id,
190                 generic_args,
191                 item_segment.infer_types,
192                 None,
193             )
194         });
195
196         assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
197
198         substs
199     }
200
201     /// Report error if there is an explicit type parameter when using `impl Trait`.
202     fn check_impl_trait(
203         tcx: TyCtxt,
204         span: Span,
205         seg: &hir::PathSegment,
206         generics: &ty::Generics,
207     ) -> bool {
208         let explicit = !seg.infer_types;
209         let impl_trait = generics.params.iter().any(|param| match param.kind {
210             ty::GenericParamDefKind::Type {
211                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
212             } => true,
213             _ => false,
214         });
215
216         if explicit && impl_trait {
217             let mut err = struct_span_err! {
218                 tcx.sess,
219                 span,
220                 E0632,
221                 "cannot provide explicit type parameters when `impl Trait` is \
222                  used in argument position."
223             };
224
225             err.emit();
226         }
227
228         impl_trait
229     }
230
231     /// Check that the correct number of generic arguments have been provided.
232     /// Used specifically for function calls.
233     pub fn check_generic_arg_count_for_call(
234         tcx: TyCtxt,
235         span: Span,
236         def: &ty::Generics,
237         seg: &hir::PathSegment,
238         is_method_call: bool,
239     ) -> bool {
240         let empty_args = P(hir::GenericArgs {
241             args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
242         });
243         let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
244         Self::check_generic_arg_count(
245             tcx,
246             span,
247             def,
248             if let Some(ref args) = seg.args {
249                 args
250             } else {
251                 &empty_args
252             },
253             if is_method_call {
254                 GenericArgPosition::MethodCall
255             } else {
256                 GenericArgPosition::Value
257             },
258             def.parent.is_none() && def.has_self, // `has_self`
259             seg.infer_types || suppress_mismatch, // `infer_types`
260         ).0
261     }
262
263     /// Check that the correct number of generic arguments have been provided.
264     /// This is used both for datatypes and function calls.
265     fn check_generic_arg_count(
266         tcx: TyCtxt,
267         span: Span,
268         def: &ty::Generics,
269         args: &hir::GenericArgs,
270         position: GenericArgPosition,
271         has_self: bool,
272         infer_types: bool,
273     ) -> (bool, Option<Vec<Span>>) {
274         // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
275         // that lifetimes will proceed types. So it suffices to check the number of each generic
276         // arguments in order to validate them with respect to the generic parameters.
277         let param_counts = def.own_counts();
278         let arg_counts = args.own_counts();
279         let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
280
281         let mut defaults: ty::GenericParamCount = Default::default();
282         for param in &def.params {
283             match param.kind {
284                 GenericParamDefKind::Lifetime => {}
285                 GenericParamDefKind::Type { has_default, .. } => {
286                     defaults.types += has_default as usize
287                 }
288             };
289         }
290
291         if position != GenericArgPosition::Type && !args.bindings.is_empty() {
292             AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
293         }
294
295         // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
296         if !infer_lifetimes {
297             if let Some(span_late) = def.has_late_bound_regions {
298                 let msg = "cannot specify lifetime arguments explicitly \
299                            if late bound lifetime parameters are present";
300                 let note = "the late bound lifetime parameter is introduced here";
301                 let span = args.args[0].span();
302                 if position == GenericArgPosition::Value
303                     && arg_counts.lifetimes != param_counts.lifetimes {
304                     let mut err = tcx.sess.struct_span_err(span, msg);
305                     err.span_note(span_late, note);
306                     err.emit();
307                     return (true, None);
308                 } else {
309                     let mut multispan = MultiSpan::from_span(span);
310                     multispan.push_span_label(span_late, note.to_string());
311                     tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
312                                   args.args[0].id(), multispan, msg);
313                     return (false, None);
314                 }
315             }
316         }
317
318         let check_kind_count = |kind,
319                                 required,
320                                 permitted,
321                                 provided,
322                                 offset| {
323             // We enforce the following: `required` <= `provided` <= `permitted`.
324             // For kinds without defaults (i.e. lifetimes), `required == permitted`.
325             // For other kinds (i.e. types), `permitted` may be greater than `required`.
326             if required <= provided && provided <= permitted {
327                 return (false, None);
328             }
329
330             // Unfortunately lifetime and type parameter mismatches are typically styled
331             // differently in diagnostics, which means we have a few cases to consider here.
332             let (bound, quantifier) = if required != permitted {
333                 if provided < required {
334                     (required, "at least ")
335                 } else { // provided > permitted
336                     (permitted, "at most ")
337                 }
338             } else {
339                 (required, "")
340             };
341
342             let mut potential_assoc_types: Option<Vec<Span>> = None;
343             let (spans, label) = if required == permitted && provided > permitted {
344                 // In the case when the user has provided too many arguments,
345                 // we want to point to the unexpected arguments.
346                 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
347                         .iter()
348                         .map(|arg| arg.span())
349                         .collect();
350                 potential_assoc_types = Some(spans.clone());
351                 (spans, format!( "unexpected {} argument", kind))
352             } else {
353                 (vec![span], format!(
354                     "expected {}{} {} argument{}",
355                     quantifier,
356                     bound,
357                     kind,
358                     if bound != 1 { "s" } else { "" },
359                 ))
360             };
361
362             let mut err = tcx.sess.struct_span_err_with_code(
363                 spans.clone(),
364                 &format!(
365                     "wrong number of {} arguments: expected {}{}, found {}",
366                     kind,
367                     quantifier,
368                     bound,
369                     provided,
370                 ),
371                 DiagnosticId::Error("E0107".into())
372             );
373             for span in spans {
374                 err.span_label(span, label.as_str());
375             }
376             err.emit();
377
378             (provided > required, // `suppress_error`
379              potential_assoc_types)
380         };
381
382         if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
383             check_kind_count(
384                 "lifetime",
385                 param_counts.lifetimes,
386                 param_counts.lifetimes,
387                 arg_counts.lifetimes,
388                 0,
389             );
390         }
391         if !infer_types
392             || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
393             check_kind_count(
394                 "type",
395                 param_counts.types - defaults.types - has_self as usize,
396                 param_counts.types - has_self as usize,
397                 arg_counts.types,
398                 arg_counts.lifetimes,
399             )
400         } else {
401             (false, None)
402         }
403     }
404
405     /// Creates the relevant generic argument substitutions
406     /// corresponding to a set of generic parameters. This is a
407     /// rather complex little function. Let me try to explain the
408     /// role of each of its parameters:
409     ///
410     /// To start, we are given the `def_id` of the thing we are
411     /// creating the substitutions for, and a partial set of
412     /// substitutions `parent_substs`. In general, the substitutions
413     /// for an item begin with substitutions for all the "parents" of
414     /// that item -- so e.g. for a method it might include the
415     /// parameters from the impl.
416     ///
417     /// Therefore, the method begins by walking down these parents,
418     /// starting with the outermost parent and proceed inwards until
419     /// it reaches `def_id`. For each parent P, it will check `parent_substs`
420     /// first to see if the parent's substitutions are listed in there. If so,
421     /// we can append those and move on. Otherwise, it invokes the
422     /// three callback functions:
423     ///
424     /// - `args_for_def_id`: given the def-id P, supplies back the
425     ///   generic arguments that were given to that parent from within
426     ///   the path; so e.g. if you have `<T as Foo>::Bar`, the def-id
427     ///   might refer to the trait `Foo`, and the arguments might be
428     ///   `[T]`. The boolean value indicates whether to infer values
429     ///   for arguments whose values were not explicitly provided.
430     /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
431     ///   instantiate a `Kind`
432     /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
433     ///   creates a suitable inference variable.
434     pub fn create_substs_for_generic_args<'a, 'b>(
435         tcx: TyCtxt<'a, 'gcx, 'tcx>,
436         def_id: DefId,
437         parent_substs: &[Kind<'tcx>],
438         has_self: bool,
439         self_ty: Option<Ty<'tcx>>,
440         args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
441         provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
442         inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
443     ) -> &'tcx Substs<'tcx> {
444         // Collect the segments of the path: we need to substitute arguments
445         // for parameters throughout the entire path (wherever there are
446         // generic parameters).
447         let mut parent_defs = tcx.generics_of(def_id);
448         let count = parent_defs.count();
449         let mut stack = vec![(def_id, parent_defs)];
450         while let Some(def_id) = parent_defs.parent {
451             parent_defs = tcx.generics_of(def_id);
452             stack.push((def_id, parent_defs));
453         }
454
455         // We manually build up the substitution, rather than using convenience
456         // methods in `subst.rs` so that we can iterate over the arguments and
457         // parameters in lock-step linearly, rather than trying to match each pair.
458         let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
459
460         // Iterate over each segment of the path.
461         while let Some((def_id, defs)) = stack.pop() {
462             let mut params = defs.params.iter().peekable();
463
464             // If we have already computed substitutions for parents, we can use those directly.
465             while let Some(&param) = params.peek() {
466                 if let Some(&kind) = parent_substs.get(param.index as usize) {
467                     substs.push(kind);
468                     params.next();
469                 } else {
470                     break;
471                 }
472             }
473
474             // `Self` is handled first, unless it's been handled in `parent_substs`.
475             if has_self {
476                 if let Some(&param) = params.peek() {
477                     if param.index == 0 {
478                         if let GenericParamDefKind::Type { .. } = param.kind {
479                             substs.push(self_ty.map(|ty| ty.into())
480                                 .unwrap_or_else(|| inferred_kind(None, param, true)));
481                             params.next();
482                         }
483                     }
484                 }
485             }
486
487             // Check whether this segment takes generic arguments and the user has provided any.
488             let (generic_args, infer_types) = args_for_def_id(def_id);
489
490             let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
491                 .peekable();
492
493             loop {
494                 // We're going to iterate through the generic arguments that the user
495                 // provided, matching them with the generic parameters we expect.
496                 // Mismatches can occur as a result of elided lifetimes, or for malformed
497                 // input. We try to handle both sensibly.
498                 match (args.peek(), params.peek()) {
499                     (Some(&arg), Some(&param)) => {
500                         match (arg, &param.kind) {
501                             (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
502                             | (GenericArg::Type(_), GenericParamDefKind::Type { .. }) => {
503                                 substs.push(provided_kind(param, arg));
504                                 args.next();
505                                 params.next();
506                             }
507                             (GenericArg::Lifetime(_), GenericParamDefKind::Type { .. }) => {
508                                 // We expected a type argument, but got a lifetime
509                                 // argument. This is an error, but we need to handle it
510                                 // gracefully so we can report sensible errors. In this
511                                 // case, we're simply going to infer this argument.
512                                 args.next();
513                             }
514                             (GenericArg::Type(_), GenericParamDefKind::Lifetime) => {
515                                 // We expected a lifetime argument, but got a type
516                                 // argument. That means we're inferring the lifetimes.
517                                 substs.push(inferred_kind(None, param, infer_types));
518                                 params.next();
519                             }
520                         }
521                     }
522                     (Some(_), None) => {
523                         // We should never be able to reach this point with well-formed input.
524                         // Getting to this point means the user supplied more arguments than
525                         // there are parameters.
526                         args.next();
527                     }
528                     (None, Some(&param)) => {
529                         // If there are fewer arguments than parameters, it means
530                         // we're inferring the remaining arguments.
531                         match param.kind {
532                             GenericParamDefKind::Lifetime | GenericParamDefKind::Type { .. } => {
533                                 let kind = inferred_kind(Some(&substs), param, infer_types);
534                                 substs.push(kind);
535                             }
536                         }
537                         args.next();
538                         params.next();
539                     }
540                     (None, None) => break,
541                 }
542             }
543         }
544
545         tcx.intern_substs(&substs)
546     }
547
548     /// Given the type/region arguments provided to some path (along with
549     /// an implicit `Self`, if this is a trait reference) returns the complete
550     /// set of substitutions. This may involve applying defaulted type parameters.
551     ///
552     /// Note that the type listing given here is *exactly* what the user provided.
553     fn create_substs_for_ast_path(&self,
554         span: Span,
555         def_id: DefId,
556         generic_args: &hir::GenericArgs,
557         infer_types: bool,
558         self_ty: Option<Ty<'tcx>>)
559         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
560     {
561         // If the type is parameterized by this region, then replace this
562         // region with the current anon region binding (in other words,
563         // whatever & would get replaced with).
564         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
565                 generic_args={:?})",
566                def_id, self_ty, generic_args);
567
568         let tcx = self.tcx();
569         let generic_params = tcx.generics_of(def_id);
570
571         // If a self-type was declared, one should be provided.
572         assert_eq!(generic_params.has_self, self_ty.is_some());
573
574         let has_self = generic_params.has_self;
575         let (_, potential_assoc_types) = Self::check_generic_arg_count(
576             self.tcx(),
577             span,
578             &generic_params,
579             &generic_args,
580             GenericArgPosition::Type,
581             has_self,
582             infer_types,
583         );
584
585         let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
586         let default_needs_object_self = |param: &ty::GenericParamDef| {
587             if let GenericParamDefKind::Type { has_default, .. } = param.kind {
588                 if is_object && has_default {
589                     if tcx.at(span).type_of(param.def_id).has_self_ty() {
590                         // There is no suitable inference default for a type parameter
591                         // that references self, in an object type.
592                         return true;
593                     }
594                 }
595             }
596
597             false
598         };
599
600         let substs = Self::create_substs_for_generic_args(
601             self.tcx(),
602             def_id,
603             &[][..],
604             self_ty.is_some(),
605             self_ty,
606             // Provide the generic args, and whether types should be inferred.
607             |_| (Some(generic_args), infer_types),
608             // Provide substitutions for parameters for which (valid) arguments have been provided.
609             |param, arg| {
610                 match (&param.kind, arg) {
611                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
612                         self.ast_region_to_region(&lt, Some(param)).into()
613                     }
614                     (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
615                         self.ast_ty_to_ty(&ty).into()
616                     }
617                     _ => unreachable!(),
618                 }
619             },
620             // Provide substitutions for parameters for which arguments are inferred.
621             |substs, param, infer_types| {
622                 match param.kind {
623                     GenericParamDefKind::Lifetime => tcx.types.re_static.into(),
624                     GenericParamDefKind::Type { has_default, .. } => {
625                         if !infer_types && has_default {
626                             // No type parameter provided, but a default exists.
627
628                             // If we are converting an object type, then the
629                             // `Self` parameter is unknown. However, some of the
630                             // other type parameters may reference `Self` in their
631                             // defaults. This will lead to an ICE if we are not
632                             // careful!
633                             if default_needs_object_self(param) {
634                                 struct_span_err!(tcx.sess, span, E0393,
635                                                     "the type parameter `{}` must be explicitly \
636                                                      specified",
637                                                     param.name)
638                                     .span_label(span,
639                                                 format!("missing reference to `{}`", param.name))
640                                     .note(&format!("because of the default `Self` reference, \
641                                                     type parameters must be specified on object \
642                                                     types"))
643                                     .emit();
644                                 tcx.types.err.into()
645                             } else {
646                                 // This is a default type parameter.
647                                 self.normalize_ty(
648                                     span,
649                                     tcx.at(span).type_of(param.def_id)
650                                        .subst_spanned(tcx, substs.unwrap(), Some(span))
651                                 ).into()
652                             }
653                         } else if infer_types {
654                             // No type parameters were provided, we can infer all.
655                             if !default_needs_object_self(param) {
656                                 self.ty_infer_for_def(param, span).into()
657                             } else {
658                                 self.ty_infer(span).into()
659                             }
660                         } else {
661                             // We've already errored above about the mismatch.
662                             tcx.types.err.into()
663                         }
664                     }
665                 }
666             },
667         );
668
669         let assoc_bindings = generic_args.bindings.iter().map(|binding| {
670             ConvertedBinding {
671                 item_name: binding.ident,
672                 ty: self.ast_ty_to_ty(&binding.ty),
673                 span: binding.span,
674             }
675         }).collect();
676
677         debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
678                generic_params, self_ty, substs);
679
680         (substs, assoc_bindings, potential_assoc_types)
681     }
682
683     /// Instantiates the path for the given trait reference, assuming that it's
684     /// bound to a valid trait type. Returns the def_id for the defining trait.
685     /// The type _cannot_ be a type other than a trait type.
686     ///
687     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
688     /// are disallowed. Otherwise, they are pushed onto the vector given.
689     pub fn instantiate_mono_trait_ref(&self,
690         trait_ref: &hir::TraitRef,
691         self_ty: Ty<'tcx>)
692         -> ty::TraitRef<'tcx>
693     {
694         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
695
696         let trait_def_id = self.trait_def_id(trait_ref);
697         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
698                                         trait_def_id,
699                                         self_ty,
700                                         trait_ref.path.segments.last().unwrap())
701     }
702
703     /// Get the `DefId` of the given trait ref. It _must_ actually be a trait.
704     fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
705         let path = &trait_ref.path;
706         match path.def {
707             Def::Trait(trait_def_id) => trait_def_id,
708             Def::TraitAlias(alias_def_id) => alias_def_id,
709             Def::Err => {
710                 FatalError.raise();
711             }
712             _ => unreachable!(),
713         }
714     }
715
716     /// The given trait ref must actually be a trait.
717     pub(super) fn instantiate_poly_trait_ref_inner(&self,
718         trait_ref: &hir::TraitRef,
719         self_ty: Ty<'tcx>,
720         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
721         speculative: bool)
722         -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
723     {
724         let trait_def_id = self.trait_def_id(trait_ref);
725
726         debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
727
728         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
729
730         let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
731             trait_ref.path.span,
732             trait_def_id,
733             self_ty,
734             trait_ref.path.segments.last().unwrap(),
735         );
736         let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
737
738         let mut dup_bindings = FxHashMap::default();
739         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
740             // specify type to assert that error was already reported in Err case:
741             let predicate: Result<_, ErrorReported> =
742                 self.ast_type_binding_to_poly_projection_predicate(
743                     trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
744             // okay to ignore Err because of ErrorReported (see above)
745             Some((predicate.ok()?, binding.span))
746         }));
747
748         debug!("instantiate_poly_trait_ref({:?}, projections={:?}) -> {:?}",
749                trait_ref, poly_projections, poly_trait_ref);
750         (poly_trait_ref, potential_assoc_types)
751     }
752
753     pub fn instantiate_poly_trait_ref(&self,
754         poly_trait_ref: &hir::PolyTraitRef,
755         self_ty: Ty<'tcx>,
756         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
757         -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
758     {
759         self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
760                                               poly_projections, false)
761     }
762
763     fn ast_path_to_mono_trait_ref(&self,
764                                   span: Span,
765                                   trait_def_id: DefId,
766                                   self_ty: Ty<'tcx>,
767                                   trait_segment: &hir::PathSegment)
768                                   -> ty::TraitRef<'tcx>
769     {
770         let (substs, assoc_bindings, _) =
771             self.create_substs_for_ast_trait_ref(span,
772                                                  trait_def_id,
773                                                  self_ty,
774                                                  trait_segment);
775         assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
776         ty::TraitRef::new(trait_def_id, substs)
777     }
778
779     fn create_substs_for_ast_trait_ref(
780         &self,
781         span: Span,
782         trait_def_id: DefId,
783         self_ty: Ty<'tcx>,
784         trait_segment: &hir::PathSegment,
785     ) -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
786         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
787                trait_segment);
788
789         let trait_def = self.tcx().trait_def(trait_def_id);
790
791         if !self.tcx().features().unboxed_closures &&
792             trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
793             != trait_def.paren_sugar {
794             // For now, require that parenthetical notation be used only with `Fn()` etc.
795             let msg = if trait_def.paren_sugar {
796                 "the precise format of `Fn`-family traits' type parameters is subject to change. \
797                  Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
798             } else {
799                 "parenthetical notation is only stable when used with `Fn`-family traits"
800             };
801             emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
802                              span, GateIssue::Language, msg);
803         }
804
805         trait_segment.with_generic_args(|generic_args| {
806             self.create_substs_for_ast_path(span,
807                                             trait_def_id,
808                                             generic_args,
809                                             trait_segment.infer_types,
810                                             Some(self_ty))
811         })
812     }
813
814     fn trait_defines_associated_type_named(&self,
815                                            trait_def_id: DefId,
816                                            assoc_name: ast::Ident)
817                                            -> bool
818     {
819         self.tcx().associated_items(trait_def_id).any(|item| {
820             item.kind == ty::AssociatedKind::Type &&
821             self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
822         })
823     }
824
825     fn ast_type_binding_to_poly_projection_predicate(
826         &self,
827         ref_id: ast::NodeId,
828         trait_ref: ty::PolyTraitRef<'tcx>,
829         binding: &ConvertedBinding<'tcx>,
830         speculative: bool,
831         dup_bindings: &mut FxHashMap<DefId, Span>)
832         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
833     {
834         let tcx = self.tcx();
835
836         if !speculative {
837             // Given something like `U: SomeTrait<T = X>`, we want to produce a
838             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
839             // subtle in the event that `T` is defined in a supertrait of
840             // `SomeTrait`, because in that case we need to upcast.
841             //
842             // That is, consider this case:
843             //
844             // ```
845             // trait SubTrait: SuperTrait<int> { }
846             // trait SuperTrait<A> { type T; }
847             //
848             // ... B : SubTrait<T=foo> ...
849             // ```
850             //
851             // We want to produce `<B as SuperTrait<int>>::T == foo`.
852
853             // Find any late-bound regions declared in `ty` that are not
854             // declared in the trait-ref. These are not wellformed.
855             //
856             // Example:
857             //
858             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
859             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
860             let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
861             let late_bound_in_ty =
862                 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
863             debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
864             debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
865             for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
866                 let br_name = match *br {
867                     ty::BrNamed(_, name) => name,
868                     _ => {
869                         span_bug!(
870                             binding.span,
871                             "anonymous bound region {:?} in binding but not trait ref",
872                             br);
873                     }
874                 };
875                 struct_span_err!(tcx.sess,
876                                 binding.span,
877                                 E0582,
878                                 "binding for associated type `{}` references lifetime `{}`, \
879                                  which does not appear in the trait input types",
880                                 binding.item_name, br_name)
881                     .emit();
882             }
883         }
884
885         let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
886                                                                     binding.item_name) {
887             // Simple case: X is defined in the current trait.
888             Ok(trait_ref)
889         } else {
890             // Otherwise, we have to walk through the supertraits to find
891             // those that do.
892             let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
893                 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
894             });
895             self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
896                                           binding.item_name, binding.span)
897         }?;
898
899         let (assoc_ident, def_scope) =
900             tcx.adjust_ident(binding.item_name, candidate.def_id(), ref_id);
901         let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
902             i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
903         }).expect("missing associated type");
904
905         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
906             let msg = format!("associated type `{}` is private", binding.item_name);
907             tcx.sess.span_err(binding.span, &msg);
908         }
909         tcx.check_stability(assoc_ty.def_id, Some(ref_id), binding.span);
910
911         if !speculative {
912             dup_bindings.entry(assoc_ty.def_id)
913                 .and_modify(|prev_span| {
914                     struct_span_err!(self.tcx().sess, binding.span, E0719,
915                                      "the value of the associated type `{}` (from the trait `{}`) \
916                                       is already specified",
917                                      binding.item_name,
918                                      tcx.item_path_str(assoc_ty.container.id()))
919                         .span_label(binding.span, "re-bound here")
920                         .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
921                         .emit();
922                 })
923                 .or_insert(binding.span);
924         }
925
926         Ok(candidate.map_bound(|trait_ref| {
927             ty::ProjectionPredicate {
928                 projection_ty: ty::ProjectionTy::from_ref_and_name(
929                     tcx,
930                     trait_ref,
931                     binding.item_name,
932                 ),
933                 ty: binding.ty,
934             }
935         }))
936     }
937
938     fn ast_path_to_ty(&self,
939         span: Span,
940         did: DefId,
941         item_segment: &hir::PathSegment)
942         -> Ty<'tcx>
943     {
944         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
945         self.normalize_ty(
946             span,
947             self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
948         )
949     }
950
951     /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
952     /// removing the dummy `Self` type (`TRAIT_OBJECT_DUMMY_SELF`).
953     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
954                                 -> ty::ExistentialTraitRef<'tcx> {
955         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
956         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
957     }
958
959     fn conv_object_ty_poly_trait_ref(&self,
960         span: Span,
961         trait_bounds: &[hir::PolyTraitRef],
962         lifetime: &hir::Lifetime)
963         -> Ty<'tcx>
964     {
965         let tcx = self.tcx();
966
967         if trait_bounds.is_empty() {
968             span_err!(tcx.sess, span, E0224,
969                       "at least one non-builtin trait is required for an object type");
970             return tcx.types.err;
971         }
972
973         let mut projection_bounds = Vec::new();
974         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
975         let (principal, potential_assoc_types) = self.instantiate_poly_trait_ref(
976             &trait_bounds[0],
977             dummy_self,
978             &mut projection_bounds,
979         );
980         debug!("principal: {:?}", principal);
981
982         for trait_bound in trait_bounds[1..].iter() {
983             // sanity check for non-principal trait bounds
984             self.instantiate_poly_trait_ref(trait_bound,
985                                             dummy_self,
986                                             &mut vec![]);
987         }
988
989         let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
990
991         if !trait_bounds.is_empty() {
992             let b = &trait_bounds[0];
993             let span = b.trait_ref.path.span;
994             struct_span_err!(self.tcx().sess, span, E0225,
995                 "only auto traits can be used as additional traits in a trait object")
996                 .span_label(span, "non-auto additional trait")
997                 .emit();
998         }
999
1000         // Check that there are no gross object safety violations;
1001         // most importantly, that the supertraits don't contain `Self`,
1002         // to avoid ICEs.
1003         let object_safety_violations =
1004             tcx.global_tcx().astconv_object_safety_violations(principal.def_id());
1005         if !object_safety_violations.is_empty() {
1006             tcx.report_object_safety_error(
1007                 span, principal.def_id(), object_safety_violations)
1008                .emit();
1009             return tcx.types.err;
1010         }
1011
1012         // Use a `BTreeSet` to keep output in a more consistent order.
1013         let mut associated_types = BTreeSet::default();
1014
1015         for tr in traits::elaborate_trait_ref(tcx, principal) {
1016             match tr {
1017                 ty::Predicate::Trait(pred) => {
1018                     associated_types.extend(tcx.associated_items(pred.def_id())
1019                                     .filter(|item| item.kind == ty::AssociatedKind::Type)
1020                                     .map(|item| item.def_id));
1021                 }
1022                 ty::Predicate::Projection(pred) => {
1023                     // Include projections defined on supertraits.
1024                     projection_bounds.push((pred, DUMMY_SP))
1025                 }
1026                 _ => ()
1027             }
1028         }
1029
1030         for (projection_bound, _) in &projection_bounds {
1031             associated_types.remove(&projection_bound.projection_def_id());
1032         }
1033
1034         if !associated_types.is_empty() {
1035             let names = associated_types.iter().map(|item_def_id| {
1036                 let assoc_item = tcx.associated_item(*item_def_id);
1037                 let trait_def_id = assoc_item.container.id();
1038                 format!(
1039                     "`{}` (from the trait `{}`)",
1040                     assoc_item.ident,
1041                     tcx.item_path_str(trait_def_id),
1042                 )
1043             }).collect::<Vec<_>>().join(", ");
1044             let mut err = struct_span_err!(
1045                 tcx.sess,
1046                 span,
1047                 E0191,
1048                 "the value of the associated type{} {} must be specified",
1049                 if associated_types.len() == 1 { "" } else { "s" },
1050                 names,
1051             );
1052             let mut suggest = false;
1053             let mut potential_assoc_types_spans = vec![];
1054             if let Some(potential_assoc_types) = potential_assoc_types {
1055                 if potential_assoc_types.len() == associated_types.len() {
1056                     // Only suggest when the amount of missing associated types is equals to the
1057                     // extra type arguments present, as that gives us a relatively high confidence
1058                     // that the user forgot to give the associtated type's name. The canonical
1059                     // example would be trying to use `Iterator<isize>` instead of
1060                     // `Iterator<Item=isize>`.
1061                     suggest = true;
1062                     potential_assoc_types_spans = potential_assoc_types;
1063                 }
1064             }
1065             let mut suggestions = vec![];
1066             for (i, item_def_id) in associated_types.iter().enumerate() {
1067                 let assoc_item = tcx.associated_item(*item_def_id);
1068                 err.span_label(
1069                     span,
1070                     format!("associated type `{}` must be specified", assoc_item.ident),
1071                 );
1072                 if item_def_id.is_local() {
1073                     err.span_label(
1074                         tcx.def_span(*item_def_id),
1075                         format!("`{}` defined here", assoc_item.ident),
1076                     );
1077                 }
1078                 if suggest {
1079                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1080                         potential_assoc_types_spans[i],
1081                     ) {
1082                         suggestions.push((
1083                             potential_assoc_types_spans[i],
1084                             format!("{} = {}", assoc_item.ident, snippet),
1085                         ));
1086                     }
1087                 }
1088             }
1089             if !suggestions.is_empty() {
1090                 let msg = if suggestions.len() == 1 {
1091                     "if you meant to specify the associated type, write"
1092                 } else {
1093                     "if you meant to specify the associated types, write"
1094                 };
1095                 err.multipart_suggestion_with_applicability(
1096                     msg,
1097                     suggestions,
1098                     Applicability::MaybeIncorrect,
1099                 );
1100             }
1101             err.emit();
1102         }
1103
1104         // Erase the `dummy_self` (`TRAIT_OBJECT_DUMMY_SELF`) used above.
1105         let existential_principal = principal.map_bound(|trait_ref| {
1106             self.trait_ref_to_existential(trait_ref)
1107         });
1108         let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1109             bound.map_bound(|b| {
1110                 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1111                 ty::ExistentialProjection {
1112                     ty: b.ty,
1113                     item_def_id: b.projection_ty.item_def_id,
1114                     substs: trait_ref.substs,
1115                 }
1116             })
1117         });
1118
1119         // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
1120         auto_traits.sort();
1121         auto_traits.dedup();
1122
1123         // Calling `skip_binder` is okay, because the predicates are re-bound.
1124         let mut v =
1125             iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
1126             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1127             .chain(existential_projections
1128                 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1129             .collect::<SmallVec<[_; 8]>>();
1130         v.sort_by(|a, b| a.stable_cmp(tcx, b));
1131         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1132
1133         // Use explicitly-specified region bound.
1134         let region_bound = if !lifetime.is_elided() {
1135             self.ast_region_to_region(lifetime, None)
1136         } else {
1137             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1138                 let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
1139                 if tcx.named_region(hir_id).is_some() {
1140                     self.ast_region_to_region(lifetime, None)
1141                 } else {
1142                     self.re_infer(span, None).unwrap_or_else(|| {
1143                         span_err!(tcx.sess, span, E0228,
1144                                   "the lifetime bound for this object type cannot be deduced \
1145                                    from context; please supply an explicit bound");
1146                         tcx.types.re_static
1147                     })
1148                 }
1149             })
1150         };
1151
1152         debug!("region_bound: {:?}", region_bound);
1153
1154         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1155         debug!("trait_object_type: {:?}", ty);
1156         ty
1157     }
1158
1159     fn report_ambiguous_associated_type(&self,
1160                                         span: Span,
1161                                         type_str: &str,
1162                                         trait_str: &str,
1163                                         name: &str) {
1164         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1165             .span_suggestion_with_applicability(
1166                 span,
1167                 "use fully-qualified syntax",
1168                 format!("<{} as {}>::{}", type_str, trait_str, name),
1169                 Applicability::HasPlaceholders
1170             ).emit();
1171     }
1172
1173     // Search for a bound on a type parameter which includes the associated item
1174     // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
1175     // This function will fail if there are no suitable bounds or there is
1176     // any ambiguity.
1177     fn find_bound_for_assoc_item(&self,
1178                                  ty_param_def_id: DefId,
1179                                  assoc_name: ast::Ident,
1180                                  span: Span)
1181                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1182     {
1183         let tcx = self.tcx();
1184
1185         let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1186         let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1187
1188         // Check that there is exactly one way to find an associated type with the
1189         // correct name.
1190         let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1191             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1192
1193         let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
1194         let param_name = tcx.hir.ty_param_name(param_node_id);
1195         self.one_bound_for_assoc_type(suitable_bounds,
1196                                       &param_name.as_str(),
1197                                       assoc_name,
1198                                       span)
1199     }
1200
1201     // Checks that `bounds` contains exactly one element and reports appropriate
1202     // errors otherwise.
1203     fn one_bound_for_assoc_type<I>(&self,
1204                                    mut bounds: I,
1205                                    ty_param_name: &str,
1206                                    assoc_name: ast::Ident,
1207                                    span: Span)
1208         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1209         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1210     {
1211         let bound = match bounds.next() {
1212             Some(bound) => bound,
1213             None => {
1214                 struct_span_err!(self.tcx().sess, span, E0220,
1215                                  "associated type `{}` not found for `{}`",
1216                                  assoc_name,
1217                                  ty_param_name)
1218                   .span_label(span, format!("associated type `{}` not found", assoc_name))
1219                   .emit();
1220                 return Err(ErrorReported);
1221             }
1222         };
1223
1224         if let Some(bound2) = bounds.next() {
1225             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1226             let mut err = struct_span_err!(
1227                 self.tcx().sess, span, E0221,
1228                 "ambiguous associated type `{}` in bounds of `{}`",
1229                 assoc_name,
1230                 ty_param_name);
1231             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1232
1233             for bound in bounds {
1234                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1235                     item.kind == ty::AssociatedKind::Type &&
1236                         self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1237                 })
1238                 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
1239
1240                 if let Some(span) = bound_span {
1241                     err.span_label(span, format!("ambiguous `{}` from `{}`",
1242                                                  assoc_name,
1243                                                  bound));
1244                 } else {
1245                     span_note!(&mut err, span,
1246                                "associated type `{}` could derive from `{}`",
1247                                ty_param_name,
1248                                bound);
1249                 }
1250             }
1251             err.emit();
1252         }
1253
1254         return Ok(bound);
1255     }
1256
1257     // Create a type from a path to an associated type.
1258     // For a path `A::B::C::D`, `ty` and `ty_path_def` are the type and def for `A::B::C`
1259     // and item_segment is the path segment for `D`. We return a type and a def for
1260     // the whole path.
1261     // Will fail except for `T::A` and `Self::A`; i.e., if `ty`/`ty_path_def` are not a type
1262     // parameter or `Self`.
1263     pub fn associated_path_def_to_ty(&self,
1264                                      ref_id: ast::NodeId,
1265                                      span: Span,
1266                                      ty: Ty<'tcx>,
1267                                      ty_path_def: Def,
1268                                      item_segment: &hir::PathSegment)
1269                                      -> (Ty<'tcx>, Def)
1270     {
1271         let tcx = self.tcx();
1272         let assoc_name = item_segment.ident;
1273
1274         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1275
1276         self.prohibit_generics(slice::from_ref(item_segment));
1277
1278         // Find the type of the associated item, and the trait where the associated
1279         // item is declared.
1280         let bound = match (&ty.sty, ty_path_def) {
1281             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1282                 // `Self` in an impl of a trait - we have a concrete `self` type and a
1283                 // trait reference.
1284                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1285                     Some(trait_ref) => trait_ref,
1286                     None => {
1287                         // A cycle error occurred, most likely.
1288                         return (tcx.types.err, Def::Err);
1289                     }
1290                 };
1291
1292                 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1293                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1294
1295                 match self.one_bound_for_assoc_type(candidates, "Self", assoc_name, span) {
1296                     Ok(bound) => bound,
1297                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1298                 }
1299             }
1300             (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1301             (&ty::Param(_), Def::TyParam(param_did)) => {
1302                 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
1303                     Ok(bound) => bound,
1304                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1305                 }
1306             }
1307             (&ty::Adt(adt_def, _substs), Def::Enum(_did)) => {
1308                 let ty_str = ty.to_string();
1309                 // Incorrect enum variant
1310                 let mut err = tcx.sess.struct_span_err(
1311                     span,
1312                     &format!("no variant `{}` on enum `{}`", &assoc_name.as_str(), ty_str),
1313                 );
1314                 // Check if it was a typo
1315                 let input = adt_def.variants.iter().map(|variant| &variant.name);
1316                 if let Some(suggested_name) = find_best_match_for_name(
1317                     input,
1318                     &assoc_name.as_str(),
1319                     None,
1320                 ) {
1321                     err.span_suggestion_with_applicability(
1322                         span,
1323                         "did you mean",
1324                         format!("{}::{}", ty_str, suggested_name.to_string()),
1325                         Applicability::MaybeIncorrect,
1326                     );
1327                 } else {
1328                     err.span_label(span, "unknown variant");
1329                 }
1330                 err.emit();
1331                 return (tcx.types.err, Def::Err);
1332             }
1333             _ => {
1334                 // Don't print TyErr to the user.
1335                 if !ty.references_error() {
1336                     self.report_ambiguous_associated_type(span,
1337                                                           &ty.to_string(),
1338                                                           "Trait",
1339                                                           &assoc_name.as_str());
1340                 }
1341                 return (tcx.types.err, Def::Err);
1342             }
1343         };
1344
1345         let trait_did = bound.def_id();
1346         let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_name, trait_did, ref_id);
1347         let item = tcx.associated_items(trait_did).find(|i| {
1348             Namespace::from(i.kind) == Namespace::Type &&
1349                 i.ident.modern() == assoc_ident
1350         })
1351         .expect("missing associated type");
1352
1353         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1354         let ty = self.normalize_ty(span, ty);
1355
1356         let def = Def::AssociatedTy(item.def_id);
1357         if !item.vis.is_accessible_from(def_scope, tcx) {
1358             let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
1359             tcx.sess.span_err(span, &msg);
1360         }
1361         tcx.check_stability(item.def_id, Some(ref_id), span);
1362
1363         (ty, def)
1364     }
1365
1366     fn qpath_to_ty(&self,
1367                    span: Span,
1368                    opt_self_ty: Option<Ty<'tcx>>,
1369                    item_def_id: DefId,
1370                    trait_segment: &hir::PathSegment,
1371                    item_segment: &hir::PathSegment)
1372                    -> Ty<'tcx>
1373     {
1374         let tcx = self.tcx();
1375         let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
1376
1377         self.prohibit_generics(slice::from_ref(item_segment));
1378
1379         let self_ty = if let Some(ty) = opt_self_ty {
1380             ty
1381         } else {
1382             let path_str = tcx.item_path_str(trait_def_id);
1383             self.report_ambiguous_associated_type(span,
1384                                                   "Type",
1385                                                   &path_str,
1386                                                   &item_segment.ident.as_str());
1387             return tcx.types.err;
1388         };
1389
1390         debug!("qpath_to_ty: self_type={:?}", self_ty);
1391
1392         let trait_ref = self.ast_path_to_mono_trait_ref(span,
1393                                                         trait_def_id,
1394                                                         self_ty,
1395                                                         trait_segment);
1396
1397         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1398
1399         self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1400     }
1401
1402     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(&self, segments: T) {
1403         for segment in segments {
1404             segment.with_generic_args(|generic_args| {
1405                 let (mut err_for_lt, mut err_for_ty) = (false, false);
1406                 for arg in &generic_args.args {
1407                     let (mut span_err, span, kind) = match arg {
1408                         hir::GenericArg::Lifetime(lt) => {
1409                             if err_for_lt { continue }
1410                             err_for_lt = true;
1411                             (struct_span_err!(self.tcx().sess, lt.span, E0110,
1412                                               "lifetime parameters are not allowed on this type"),
1413                              lt.span,
1414                              "lifetime")
1415                         }
1416                         hir::GenericArg::Type(ty) => {
1417                             if err_for_ty { continue }
1418                             err_for_ty = true;
1419                             (struct_span_err!(self.tcx().sess, ty.span, E0109,
1420                                               "type parameters are not allowed on this type"),
1421                              ty.span,
1422                              "type")
1423                         }
1424                     };
1425                     span_err.span_label(span, format!("{} parameter not allowed", kind))
1426                             .emit();
1427                     if err_for_lt && err_for_ty {
1428                         break;
1429                     }
1430                 }
1431                 for binding in &generic_args.bindings {
1432                     Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1433                     break;
1434                 }
1435             })
1436         }
1437     }
1438
1439     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt, span: Span) {
1440         let mut err = struct_span_err!(tcx.sess, span, E0229,
1441                                        "associated type bindings are not allowed here");
1442         err.span_label(span, "associated type not allowed here").emit();
1443     }
1444
1445     // Check a type `Path` and convert it to a `Ty`.
1446     pub fn def_to_ty(&self,
1447                      opt_self_ty: Option<Ty<'tcx>>,
1448                      path: &hir::Path,
1449                      permit_variants: bool)
1450                      -> Ty<'tcx> {
1451         let tcx = self.tcx();
1452
1453         debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1454                path.def, opt_self_ty, path.segments);
1455
1456         let span = path.span;
1457         match path.def {
1458             Def::Existential(did) => {
1459                 // Check for desugared impl trait.
1460                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1461                 let item_segment = path.segments.split_last().unwrap();
1462                 self.prohibit_generics(item_segment.1);
1463                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1464                 self.normalize_ty(
1465                     span,
1466                     tcx.mk_opaque(did, substs),
1467                 )
1468             }
1469             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1470             Def::Union(did) | Def::ForeignTy(did) => {
1471                 assert_eq!(opt_self_ty, None);
1472                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1473                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1474             }
1475             Def::Variant(did) if permit_variants => {
1476                 // Convert "variant type" as if it were a real type.
1477                 // The resulting `Ty` is type of the variant's enum for now.
1478                 assert_eq!(opt_self_ty, None);
1479                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1480                 self.ast_path_to_ty(span,
1481                                     tcx.parent_def_id(did).unwrap(),
1482                                     path.segments.last().unwrap())
1483             }
1484             Def::TyParam(did) => {
1485                 assert_eq!(opt_self_ty, None);
1486                 self.prohibit_generics(&path.segments);
1487
1488                 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1489                 let item_id = tcx.hir.get_parent_node(node_id);
1490                 let item_def_id = tcx.hir.local_def_id(item_id);
1491                 let generics = tcx.generics_of(item_def_id);
1492                 let index = generics.param_def_id_to_index[&tcx.hir.local_def_id(node_id)];
1493                 tcx.mk_ty_param(index, tcx.hir.name(node_id).as_interned_str())
1494             }
1495             Def::SelfTy(_, Some(def_id)) => {
1496                 // `Self` in impl (we know the concrete type)
1497
1498                 assert_eq!(opt_self_ty, None);
1499                 self.prohibit_generics(&path.segments);
1500
1501                 tcx.at(span).type_of(def_id)
1502             }
1503             Def::SelfTy(Some(_), None) => {
1504                 // `Self` in trait
1505                 assert_eq!(opt_self_ty, None);
1506                 self.prohibit_generics(&path.segments);
1507                 tcx.mk_self_type()
1508             }
1509             Def::AssociatedTy(def_id) => {
1510                 self.prohibit_generics(&path.segments[..path.segments.len()-2]);
1511                 self.qpath_to_ty(span,
1512                                  opt_self_ty,
1513                                  def_id,
1514                                  &path.segments[path.segments.len()-2],
1515                                  path.segments.last().unwrap())
1516             }
1517             Def::PrimTy(prim_ty) => {
1518                 assert_eq!(opt_self_ty, None);
1519                 self.prohibit_generics(&path.segments);
1520                 match prim_ty {
1521                     hir::Bool => tcx.types.bool,
1522                     hir::Char => tcx.types.char,
1523                     hir::Int(it) => tcx.mk_mach_int(it),
1524                     hir::Uint(uit) => tcx.mk_mach_uint(uit),
1525                     hir::Float(ft) => tcx.mk_mach_float(ft),
1526                     hir::Str => tcx.mk_str()
1527                 }
1528             }
1529             Def::Err => {
1530                 self.set_tainted_by_errors();
1531                 return self.tcx().types.err;
1532             }
1533             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1534         }
1535     }
1536
1537     /// Parses the programmer's textual representation of a type into our
1538     /// internal notion of a type.
1539     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1540         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
1541                ast_ty.id, ast_ty, ast_ty.node);
1542
1543         let tcx = self.tcx();
1544
1545         let result_ty = match ast_ty.node {
1546             hir::TyKind::Slice(ref ty) => {
1547                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1548             }
1549             hir::TyKind::Ptr(ref mt) => {
1550                 tcx.mk_ptr(ty::TypeAndMut {
1551                     ty: self.ast_ty_to_ty(&mt.ty),
1552                     mutbl: mt.mutbl
1553                 })
1554             }
1555             hir::TyKind::Rptr(ref region, ref mt) => {
1556                 let r = self.ast_region_to_region(region, None);
1557                 debug!("Ref r={:?}", r);
1558                 let t = self.ast_ty_to_ty(&mt.ty);
1559                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1560             }
1561             hir::TyKind::Never => {
1562                 tcx.types.never
1563             },
1564             hir::TyKind::Tup(ref fields) => {
1565                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1566             }
1567             hir::TyKind::BareFn(ref bf) => {
1568                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1569                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1570             }
1571             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1572                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1573             }
1574             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1575                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1576                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1577                     self.ast_ty_to_ty(qself)
1578                 });
1579                 self.def_to_ty(opt_self_ty, path, false)
1580             }
1581             hir::TyKind::Def(item_id, ref lifetimes) => {
1582                 let did = tcx.hir.local_def_id(item_id.id);
1583                 self.impl_trait_ty_to_ty(did, lifetimes)
1584             },
1585             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1586                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1587                 let ty = self.ast_ty_to_ty(qself);
1588
1589                 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1590                     path.def
1591                 } else {
1592                     Def::Err
1593                 };
1594                 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1595             }
1596             hir::TyKind::Array(ref ty, ref length) => {
1597                 let length_def_id = tcx.hir.local_def_id(length.id);
1598                 let substs = Substs::identity_for_item(tcx, length_def_id);
1599                 let length = ty::Const::unevaluated(tcx, length_def_id, substs, tcx.types.usize);
1600                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1601                 self.normalize_ty(ast_ty.span, array_ty)
1602             }
1603             hir::TyKind::Typeof(ref _e) => {
1604                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1605                                  "`typeof` is a reserved keyword but unimplemented")
1606                     .span_label(ast_ty.span, "reserved keyword")
1607                     .emit();
1608
1609                 tcx.types.err
1610             }
1611             hir::TyKind::Infer => {
1612                 // Infer also appears as the type of arguments or return
1613                 // values in a ExprKind::Closure, or as
1614                 // the type of local variables. Both of these cases are
1615                 // handled specially and will not descend into this routine.
1616                 self.ty_infer(ast_ty.span)
1617             }
1618             hir::TyKind::Err => {
1619                 tcx.types.err
1620             }
1621         };
1622
1623         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1624         result_ty
1625     }
1626
1627     pub fn impl_trait_ty_to_ty(
1628         &self,
1629         def_id: DefId,
1630         lifetimes: &[hir::GenericArg],
1631     ) -> Ty<'tcx> {
1632         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1633         let tcx = self.tcx();
1634
1635         let generics = tcx.generics_of(def_id);
1636
1637         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1638         let substs = Substs::for_item(tcx, def_id, |param, _| {
1639             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1640                 // Our own parameters are the resolved lifetimes.
1641                 match param.kind {
1642                     GenericParamDefKind::Lifetime => {
1643                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1644                             self.ast_region_to_region(lifetime, None).into()
1645                         } else {
1646                             bug!()
1647                         }
1648                     }
1649                     _ => bug!()
1650                 }
1651             } else {
1652                 // Replace all parent lifetimes with 'static.
1653                 match param.kind {
1654                     GenericParamDefKind::Lifetime => {
1655                         tcx.types.re_static.into()
1656                     }
1657                     _ => tcx.mk_param_from_def(param)
1658                 }
1659             }
1660         });
1661         debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1662
1663         let ty = tcx.mk_opaque(def_id, substs);
1664         debug!("impl_trait_ty_to_ty: {}", ty);
1665         ty
1666     }
1667
1668     pub fn ty_of_arg(&self,
1669                      ty: &hir::Ty,
1670                      expected_ty: Option<Ty<'tcx>>)
1671                      -> Ty<'tcx>
1672     {
1673         match ty.node {
1674             hir::TyKind::Infer if expected_ty.is_some() => {
1675                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1676                 expected_ty.unwrap()
1677             }
1678             _ => self.ast_ty_to_ty(ty),
1679         }
1680     }
1681
1682     pub fn ty_of_fn(&self,
1683                     unsafety: hir::Unsafety,
1684                     abi: abi::Abi,
1685                     decl: &hir::FnDecl)
1686                     -> ty::PolyFnSig<'tcx> {
1687         debug!("ty_of_fn");
1688
1689         let tcx = self.tcx();
1690         let input_tys =
1691             decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
1692
1693         let output_ty = match decl.output {
1694             hir::Return(ref output) => self.ast_ty_to_ty(output),
1695             hir::DefaultReturn(..) => tcx.mk_unit(),
1696         };
1697
1698         debug!("ty_of_fn: output_ty={:?}", output_ty);
1699
1700         let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1701             input_tys,
1702             output_ty,
1703             decl.variadic,
1704             unsafety,
1705             abi
1706         ));
1707
1708         // Find any late-bound regions declared in return type that do
1709         // not appear in the arguments. These are not well-formed.
1710         //
1711         // Example:
1712         //     for<'a> fn() -> &'a str <-- 'a is bad
1713         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1714         let inputs = bare_fn_ty.inputs();
1715         let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1716             &inputs.map_bound(|i| i.to_owned()));
1717         let output = bare_fn_ty.output();
1718         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1719         for br in late_bound_in_ret.difference(&late_bound_in_args) {
1720             let lifetime_name = match *br {
1721                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1722                 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
1723             };
1724             let mut err = struct_span_err!(tcx.sess,
1725                                            decl.output.span(),
1726                                            E0581,
1727                                            "return type references {} \
1728                                             which is not constrained by the fn input types",
1729                                            lifetime_name);
1730             if let ty::BrAnon(_) = *br {
1731                 // The only way for an anonymous lifetime to wind up
1732                 // in the return type but **also** be unconstrained is
1733                 // if it only appears in "associated types" in the
1734                 // input. See #47511 for an example. In this case,
1735                 // though we can easily give a hint that ought to be
1736                 // relevant.
1737                 err.note("lifetimes appearing in an associated type \
1738                           are not considered constrained");
1739             }
1740             err.emit();
1741         }
1742
1743         bare_fn_ty
1744     }
1745
1746     /// Given the bounds on an object, determines what single region bound (if any) we can
1747     /// use to summarize this type. The basic idea is that we will use the bound the user
1748     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1749     /// for region bounds. It may be that we can derive no bound at all, in which case
1750     /// we return `None`.
1751     fn compute_object_lifetime_bound(&self,
1752         span: Span,
1753         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
1754         -> Option<ty::Region<'tcx>> // if None, use the default
1755     {
1756         let tcx = self.tcx();
1757
1758         debug!("compute_opt_region_bound(existential_predicates={:?})",
1759                existential_predicates);
1760
1761         // No explicit region bound specified. Therefore, examine trait
1762         // bounds and see if we can derive region bounds from those.
1763         let derived_region_bounds =
1764             object_region_bounds(tcx, existential_predicates);
1765
1766         // If there are no derived region bounds, then report back that we
1767         // can find no region bound. The caller will use the default.
1768         if derived_region_bounds.is_empty() {
1769             return None;
1770         }
1771
1772         // If any of the derived region bounds are 'static, that is always
1773         // the best choice.
1774         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1775             return Some(tcx.types.re_static);
1776         }
1777
1778         // Determine whether there is exactly one unique region in the set
1779         // of derived region bounds. If so, use that. Otherwise, report an
1780         // error.
1781         let r = derived_region_bounds[0];
1782         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1783             span_err!(tcx.sess, span, E0227,
1784                       "ambiguous lifetime bound, explicit lifetime bound required");
1785         }
1786         return Some(r);
1787     }
1788 }
1789
1790 /// Divides a list of general trait bounds into two groups: auto traits (e.g. Sync and Send) and the
1791 /// remaining general trait bounds.
1792 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1793                                          trait_bounds: &'b [hir::PolyTraitRef])
1794     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1795 {
1796     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1797         // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
1798         match bound.trait_ref.path.def {
1799             Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
1800                 true
1801             }
1802             _ => false
1803         }
1804     });
1805
1806     let auto_traits = auto_traits.into_iter().map(|tr| {
1807         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1808             trait_did
1809         } else {
1810             unreachable!()
1811         }
1812     }).collect::<Vec<_>>();
1813
1814     (auto_traits, trait_bounds)
1815 }
1816
1817 // A helper struct for conveniently grouping a set of bounds which we pass to
1818 // and return from functions in multiple places.
1819 #[derive(PartialEq, Eq, Clone, Debug)]
1820 pub struct Bounds<'tcx> {
1821     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
1822     pub implicitly_sized: Option<Span>,
1823     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
1824     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
1825 }
1826
1827 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1828     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1829                       -> Vec<(ty::Predicate<'tcx>, Span)>
1830     {
1831         // If it could be sized, and is, add the sized predicate
1832         let sized_predicate = self.implicitly_sized.and_then(|span| {
1833             tcx.lang_items().sized_trait().map(|sized| {
1834                 let trait_ref = ty::TraitRef {
1835                     def_id: sized,
1836                     substs: tcx.mk_substs_trait(param_ty, &[])
1837                 };
1838                 (trait_ref.to_predicate(), span)
1839             })
1840         });
1841
1842         sized_predicate.into_iter().chain(
1843             self.region_bounds.iter().map(|&(region_bound, span)| {
1844                 // account for the binder being introduced below; no need to shift `param_ty`
1845                 // because, at present at least, it can only refer to early-bound regions
1846                 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
1847                 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
1848                 (ty::Binder::dummy(outlives).to_predicate(), span)
1849             }).chain(
1850                 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
1851                     (bound_trait_ref.to_predicate(), span)
1852                 })
1853             ).chain(
1854                 self.projection_bounds.iter().map(|&(projection, span)| {
1855                     (projection.to_predicate(), span)
1856                 })
1857             )
1858         ).collect()
1859     }
1860 }