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