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