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