]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
hir: remove NodeId from Expr
[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(hir_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
1280         debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1281
1282         self.prohibit_generics(slice::from_ref(assoc_segment));
1283
1284         // Check if we have an enum variant.
1285         let mut variant_resolution = None;
1286         if let ty::Adt(adt_def, _) = qself_ty.sty {
1287             if adt_def.is_enum() {
1288                 let variant_def = adt_def.variants.iter().find(|vd| {
1289                     tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1290                 });
1291                 if let Some(variant_def) = variant_def {
1292                     let def = Def::Variant(variant_def.did);
1293                     if permit_variants {
1294                         check_type_alias_enum_variants_enabled(tcx, span);
1295                         tcx.check_stability(variant_def.did, Some(hir_ref_id), span);
1296                         return (qself_ty, def);
1297                     } else {
1298                         variant_resolution = Some(def);
1299                     }
1300                 }
1301             }
1302         }
1303
1304         // Find the type of the associated item, and the trait where the associated
1305         // item is declared.
1306         let bound = match (&qself_ty.sty, qself_def) {
1307             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1308                 // `Self` in an impl of a trait -- we have a concrete self type and a
1309                 // trait reference.
1310                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1311                     Some(trait_ref) => trait_ref,
1312                     None => {
1313                         // A cycle error occurred, most likely.
1314                         return (tcx.types.err, Def::Err);
1315                     }
1316                 };
1317
1318                 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1319                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1320
1321                 match self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span) {
1322                     Ok(bound) => bound,
1323                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1324                 }
1325             }
1326             (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1327             (&ty::Param(_), Def::TyParam(param_did)) => {
1328                 match self.find_bound_for_assoc_item(param_did, assoc_ident, span) {
1329                     Ok(bound) => bound,
1330                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1331                 }
1332             }
1333             _ => {
1334                 if variant_resolution.is_some() {
1335                     // Variant in type position
1336                     let msg = format!("expected type, found variant `{}`", assoc_ident);
1337                     tcx.sess.span_err(span, &msg);
1338                 } else if qself_ty.is_enum() {
1339                     // Report as incorrect enum variant rather than ambiguous type.
1340                     let mut err = tcx.sess.struct_span_err(
1341                         span,
1342                         &format!("no variant `{}` on enum `{}`", &assoc_ident.as_str(), qself_ty),
1343                     );
1344                     // Check if it was a typo.
1345                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1346                     if let Some(suggested_name) = find_best_match_for_name(
1347                         adt_def.variants.iter().map(|variant| &variant.ident.name),
1348                         &assoc_ident.as_str(),
1349                         None,
1350                     ) {
1351                         err.span_suggestion(
1352                             span,
1353                             "did you mean",
1354                             format!("{}::{}", qself_ty, suggested_name),
1355                             Applicability::MaybeIncorrect,
1356                         );
1357                     } else {
1358                         err.span_label(span, "unknown variant");
1359                     }
1360                     err.emit();
1361                 } else if !qself_ty.references_error() {
1362                     // Don't print `TyErr` to the user.
1363                     self.report_ambiguous_associated_type(span,
1364                                                           &qself_ty.to_string(),
1365                                                           "Trait",
1366                                                           &assoc_ident.as_str());
1367                 }
1368                 return (tcx.types.err, Def::Err);
1369             }
1370         };
1371
1372         let trait_did = bound.def_id();
1373         let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_ident, trait_did, hir_ref_id);
1374         let item = tcx.associated_items(trait_did).find(|i| {
1375             Namespace::from(i.kind) == Namespace::Type &&
1376                 i.ident.modern() == assoc_ident
1377         }).expect("missing associated type");
1378
1379         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1380         let ty = self.normalize_ty(span, ty);
1381
1382         let def = Def::AssociatedTy(item.def_id);
1383         if !item.vis.is_accessible_from(def_scope, tcx) {
1384             let msg = format!("{} `{}` is private", def.kind_name(), assoc_ident);
1385             tcx.sess.span_err(span, &msg);
1386         }
1387         tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1388
1389         if let Some(variant_def) = variant_resolution {
1390             let mut err = tcx.struct_span_lint_hir(
1391                 AMBIGUOUS_ASSOCIATED_ITEMS,
1392                 hir_ref_id,
1393                 span,
1394                 "ambiguous associated item",
1395             );
1396
1397             let mut could_refer_to = |def: Def, also| {
1398                 let note_msg = format!("`{}` could{} refer to {} defined here",
1399                                        assoc_ident, also, def.kind_name());
1400                 err.span_note(tcx.def_span(def.def_id()), &note_msg);
1401             };
1402             could_refer_to(variant_def, "");
1403             could_refer_to(def, " also");
1404
1405             err.span_suggestion(
1406                 span,
1407                 "use fully-qualified syntax",
1408                 format!("<{} as {}>::{}", qself_ty, "Trait", assoc_ident),
1409                 Applicability::HasPlaceholders,
1410             ).emit();
1411         }
1412
1413         (ty, def)
1414     }
1415
1416     fn qpath_to_ty(&self,
1417                    span: Span,
1418                    opt_self_ty: Option<Ty<'tcx>>,
1419                    item_def_id: DefId,
1420                    trait_segment: &hir::PathSegment,
1421                    item_segment: &hir::PathSegment)
1422                    -> Ty<'tcx>
1423     {
1424         let tcx = self.tcx();
1425         let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
1426
1427         self.prohibit_generics(slice::from_ref(item_segment));
1428
1429         let self_ty = if let Some(ty) = opt_self_ty {
1430             ty
1431         } else {
1432             let path_str = tcx.item_path_str(trait_def_id);
1433             self.report_ambiguous_associated_type(span,
1434                                                   "Type",
1435                                                   &path_str,
1436                                                   &item_segment.ident.as_str());
1437             return tcx.types.err;
1438         };
1439
1440         debug!("qpath_to_ty: self_type={:?}", self_ty);
1441
1442         let trait_ref = self.ast_path_to_mono_trait_ref(span,
1443                                                         trait_def_id,
1444                                                         self_ty,
1445                                                         trait_segment);
1446
1447         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1448
1449         self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1450     }
1451
1452     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1453             &self, segments: T) -> bool {
1454         let mut has_err = false;
1455         for segment in segments {
1456             segment.with_generic_args(|generic_args| {
1457                 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1458                 for arg in &generic_args.args {
1459                     let (mut span_err, span, kind) = match arg {
1460                         // FIXME(varkor): unify E0109, E0110 and E0111.
1461                         hir::GenericArg::Lifetime(lt) => {
1462                             if err_for_lt { continue }
1463                             err_for_lt = true;
1464                             has_err = true;
1465                             (struct_span_err!(self.tcx().sess, lt.span, E0110,
1466                                               "lifetime arguments are not allowed on this entity"),
1467                              lt.span,
1468                              "lifetime")
1469                         }
1470                         hir::GenericArg::Type(ty) => {
1471                             if err_for_ty { continue }
1472                             err_for_ty = true;
1473                             has_err = true;
1474                             (struct_span_err!(self.tcx().sess, ty.span, E0109,
1475                                               "type arguments are not allowed on this entity"),
1476                              ty.span,
1477                              "type")
1478                         }
1479                         hir::GenericArg::Const(ct) => {
1480                             if err_for_ct { continue }
1481                             err_for_ct = true;
1482                             (struct_span_err!(self.tcx().sess, ct.span, E0111,
1483                                               "const parameters are not allowed on this type"),
1484                              ct.span,
1485                              "const")
1486                         }
1487                     };
1488                     span_err.span_label(span, format!("{} argument not allowed", kind))
1489                             .emit();
1490                     if err_for_lt && err_for_ty && err_for_ct {
1491                         break;
1492                     }
1493                 }
1494                 for binding in &generic_args.bindings {
1495                     has_err = true;
1496                     Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1497                     break;
1498                 }
1499             })
1500         }
1501         has_err
1502     }
1503
1504     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt, span: Span) {
1505         let mut err = struct_span_err!(tcx.sess, span, E0229,
1506                                        "associated type bindings are not allowed here");
1507         err.span_label(span, "associated type not allowed here").emit();
1508     }
1509
1510     pub fn def_ids_for_path_segments(&self,
1511                                      segments: &[hir::PathSegment],
1512                                      self_ty: Option<Ty<'tcx>>,
1513                                      def: Def)
1514                                      -> Vec<PathSeg> {
1515         // We need to extract the type parameters supplied by the user in
1516         // the path `path`. Due to the current setup, this is a bit of a
1517         // tricky-process; the problem is that resolve only tells us the
1518         // end-point of the path resolution, and not the intermediate steps.
1519         // Luckily, we can (at least for now) deduce the intermediate steps
1520         // just from the end-point.
1521         //
1522         // There are basically five cases to consider:
1523         //
1524         // 1. Reference to a constructor of a struct:
1525         //
1526         //        struct Foo<T>(...)
1527         //
1528         //    In this case, the parameters are declared in the type space.
1529         //
1530         // 2. Reference to a constructor of an enum variant:
1531         //
1532         //        enum E<T> { Foo(...) }
1533         //
1534         //    In this case, the parameters are defined in the type space,
1535         //    but may be specified either on the type or the variant.
1536         //
1537         // 3. Reference to a fn item or a free constant:
1538         //
1539         //        fn foo<T>() { }
1540         //
1541         //    In this case, the path will again always have the form
1542         //    `a::b::foo::<T>` where only the final segment should have
1543         //    type parameters. However, in this case, those parameters are
1544         //    declared on a value, and hence are in the `FnSpace`.
1545         //
1546         // 4. Reference to a method or an associated constant:
1547         //
1548         //        impl<A> SomeStruct<A> {
1549         //            fn foo<B>(...)
1550         //        }
1551         //
1552         //    Here we can have a path like
1553         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1554         //    may appear in two places. The penultimate segment,
1555         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1556         //    final segment, `foo::<B>` contains parameters in fn space.
1557         //
1558         // 5. Reference to a local variable
1559         //
1560         //    Local variables can't have any type parameters.
1561         //
1562         // The first step then is to categorize the segments appropriately.
1563
1564         let tcx = self.tcx();
1565
1566         assert!(!segments.is_empty());
1567         let last = segments.len() - 1;
1568
1569         let mut path_segs = vec![];
1570
1571         match def {
1572             // Case 1. Reference to a struct constructor.
1573             Def::StructCtor(def_id, ..) |
1574             Def::SelfCtor(.., def_id) => {
1575                 // Everything but the final segment should have no
1576                 // parameters at all.
1577                 let generics = tcx.generics_of(def_id);
1578                 // Variant and struct constructors use the
1579                 // generics of their parent type definition.
1580                 let generics_def_id = generics.parent.unwrap_or(def_id);
1581                 path_segs.push(PathSeg(generics_def_id, last));
1582             }
1583
1584             // Case 2. Reference to a variant constructor.
1585             Def::Variant(def_id) |
1586             Def::VariantCtor(def_id, ..) => {
1587                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1588                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1589                     debug_assert!(adt_def.is_enum());
1590                     (adt_def.did, last)
1591                 } else if last >= 1 && segments[last - 1].args.is_some() {
1592                     // Everything but the penultimate segment should have no
1593                     // parameters at all.
1594                     let enum_def_id = tcx.parent_def_id(def_id).unwrap();
1595                     (enum_def_id, last - 1)
1596                 } else {
1597                     // FIXME: lint here recommending `Enum::<...>::Variant` form
1598                     // instead of `Enum::Variant::<...>` form.
1599
1600                     // Everything but the final segment should have no
1601                     // parameters at all.
1602                     let generics = tcx.generics_of(def_id);
1603                     // Variant and struct constructors use the
1604                     // generics of their parent type definition.
1605                     (generics.parent.unwrap_or(def_id), last)
1606                 };
1607                 path_segs.push(PathSeg(generics_def_id, index));
1608             }
1609
1610             // Case 3. Reference to a top-level value.
1611             Def::Fn(def_id) |
1612             Def::Const(def_id) |
1613             Def::Static(def_id, _) => {
1614                 path_segs.push(PathSeg(def_id, last));
1615             }
1616
1617             // Case 4. Reference to a method or associated const.
1618             Def::Method(def_id) |
1619             Def::AssociatedConst(def_id) => {
1620                 if segments.len() >= 2 {
1621                     let generics = tcx.generics_of(def_id);
1622                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1623                 }
1624                 path_segs.push(PathSeg(def_id, last));
1625             }
1626
1627             // Case 5. Local variable, no generics.
1628             Def::Local(..) | Def::Upvar(..) => {}
1629
1630             _ => bug!("unexpected definition: {:?}", def),
1631         }
1632
1633         debug!("path_segs = {:?}", path_segs);
1634
1635         path_segs
1636     }
1637
1638     // Check a type `Path` and convert it to a `Ty`.
1639     pub fn def_to_ty(&self,
1640                      opt_self_ty: Option<Ty<'tcx>>,
1641                      path: &hir::Path,
1642                      permit_variants: bool)
1643                      -> Ty<'tcx> {
1644         let tcx = self.tcx();
1645
1646         debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1647                path.def, opt_self_ty, path.segments);
1648
1649         let span = path.span;
1650         match path.def {
1651             Def::Existential(did) => {
1652                 // Check for desugared impl trait.
1653                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1654                 let item_segment = path.segments.split_last().unwrap();
1655                 self.prohibit_generics(item_segment.1);
1656                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1657                 self.normalize_ty(
1658                     span,
1659                     tcx.mk_opaque(did, substs),
1660                 )
1661             }
1662             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1663             Def::Union(did) | Def::ForeignTy(did) => {
1664                 assert_eq!(opt_self_ty, None);
1665                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1666                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1667             }
1668             Def::Variant(_) if permit_variants => {
1669                 // Convert "variant type" as if it were a real type.
1670                 // The resulting `Ty` is type of the variant's enum for now.
1671                 assert_eq!(opt_self_ty, None);
1672
1673                 let path_segs = self.def_ids_for_path_segments(&path.segments, None, path.def);
1674                 let generic_segs: FxHashSet<_> =
1675                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
1676                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1677                     if !generic_segs.contains(&index) {
1678                         Some(seg)
1679                     } else {
1680                         None
1681                     }
1682                 }));
1683
1684                 let PathSeg(def_id, index) = path_segs.last().unwrap();
1685                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1686             }
1687             Def::TyParam(did) => {
1688                 assert_eq!(opt_self_ty, None);
1689                 self.prohibit_generics(&path.segments);
1690
1691                 let hir_id = tcx.hir().as_local_hir_id(did).unwrap();
1692                 let item_id = tcx.hir().get_parent_node_by_hir_id(hir_id);
1693                 let item_def_id = tcx.hir().local_def_id_from_hir_id(item_id);
1694                 let generics = tcx.generics_of(item_def_id);
1695                 let index = generics.param_def_id_to_index[
1696                     &tcx.hir().local_def_id_from_hir_id(hir_id)];
1697                 tcx.mk_ty_param(index, tcx.hir().name_by_hir_id(hir_id).as_interned_str())
1698             }
1699             Def::SelfTy(_, Some(def_id)) => {
1700                 // `Self` in impl (we know the concrete type).
1701                 assert_eq!(opt_self_ty, None);
1702                 self.prohibit_generics(&path.segments);
1703                 tcx.at(span).type_of(def_id)
1704             }
1705             Def::SelfTy(Some(_), None) => {
1706                 // `Self` in trait.
1707                 assert_eq!(opt_self_ty, None);
1708                 self.prohibit_generics(&path.segments);
1709                 tcx.mk_self_type()
1710             }
1711             Def::AssociatedTy(def_id) => {
1712                 debug_assert!(path.segments.len() >= 2);
1713                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
1714                 self.qpath_to_ty(span,
1715                                  opt_self_ty,
1716                                  def_id,
1717                                  &path.segments[path.segments.len() - 2],
1718                                  path.segments.last().unwrap())
1719             }
1720             Def::PrimTy(prim_ty) => {
1721                 assert_eq!(opt_self_ty, None);
1722                 self.prohibit_generics(&path.segments);
1723                 match prim_ty {
1724                     hir::Bool => tcx.types.bool,
1725                     hir::Char => tcx.types.char,
1726                     hir::Int(it) => tcx.mk_mach_int(it),
1727                     hir::Uint(uit) => tcx.mk_mach_uint(uit),
1728                     hir::Float(ft) => tcx.mk_mach_float(ft),
1729                     hir::Str => tcx.mk_str()
1730                 }
1731             }
1732             Def::Err => {
1733                 self.set_tainted_by_errors();
1734                 return self.tcx().types.err;
1735             }
1736             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1737         }
1738     }
1739
1740     /// Parses the programmer's textual representation of a type into our
1741     /// internal notion of a type.
1742     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1743         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
1744                ast_ty.hir_id, ast_ty, ast_ty.node);
1745
1746         let tcx = self.tcx();
1747
1748         let result_ty = match ast_ty.node {
1749             hir::TyKind::Slice(ref ty) => {
1750                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1751             }
1752             hir::TyKind::Ptr(ref mt) => {
1753                 tcx.mk_ptr(ty::TypeAndMut {
1754                     ty: self.ast_ty_to_ty(&mt.ty),
1755                     mutbl: mt.mutbl
1756                 })
1757             }
1758             hir::TyKind::Rptr(ref region, ref mt) => {
1759                 let r = self.ast_region_to_region(region, None);
1760                 debug!("Ref r={:?}", r);
1761                 let t = self.ast_ty_to_ty(&mt.ty);
1762                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1763             }
1764             hir::TyKind::Never => {
1765                 tcx.types.never
1766             },
1767             hir::TyKind::Tup(ref fields) => {
1768                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1769             }
1770             hir::TyKind::BareFn(ref bf) => {
1771                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1772                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1773             }
1774             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1775                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1776             }
1777             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1778                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1779                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1780                     self.ast_ty_to_ty(qself)
1781                 });
1782                 self.def_to_ty(opt_self_ty, path, false)
1783             }
1784             hir::TyKind::Def(item_id, ref lifetimes) => {
1785                 let did = tcx.hir().local_def_id(item_id.id);
1786                 self.impl_trait_ty_to_ty(did, lifetimes)
1787             },
1788             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1789                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1790                 let ty = self.ast_ty_to_ty(qself);
1791
1792                 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1793                     path.def
1794                 } else {
1795                     Def::Err
1796                 };
1797                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, def, segment, false).0
1798             }
1799             hir::TyKind::Array(ref ty, ref length) => {
1800                 let length_def_id = tcx.hir().local_def_id(length.id);
1801                 let substs = Substs::identity_for_item(tcx, length_def_id);
1802                 let length = ty::LazyConst::Unevaluated(length_def_id, substs);
1803                 let length = tcx.mk_lazy_const(length);
1804                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1805                 self.normalize_ty(ast_ty.span, array_ty)
1806             }
1807             hir::TyKind::Typeof(ref _e) => {
1808                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1809                                  "`typeof` is a reserved keyword but unimplemented")
1810                     .span_label(ast_ty.span, "reserved keyword")
1811                     .emit();
1812
1813                 tcx.types.err
1814             }
1815             hir::TyKind::Infer => {
1816                 // Infer also appears as the type of arguments or return
1817                 // values in a ExprKind::Closure, or as
1818                 // the type of local variables. Both of these cases are
1819                 // handled specially and will not descend into this routine.
1820                 self.ty_infer(ast_ty.span)
1821             }
1822             hir::TyKind::Err => {
1823                 tcx.types.err
1824             }
1825         };
1826
1827         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1828         result_ty
1829     }
1830
1831     pub fn impl_trait_ty_to_ty(
1832         &self,
1833         def_id: DefId,
1834         lifetimes: &[hir::GenericArg],
1835     ) -> Ty<'tcx> {
1836         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1837         let tcx = self.tcx();
1838
1839         let generics = tcx.generics_of(def_id);
1840
1841         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1842         let substs = Substs::for_item(tcx, def_id, |param, _| {
1843             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1844                 // Our own parameters are the resolved lifetimes.
1845                 match param.kind {
1846                     GenericParamDefKind::Lifetime => {
1847                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1848                             self.ast_region_to_region(lifetime, None).into()
1849                         } else {
1850                             bug!()
1851                         }
1852                     }
1853                     _ => bug!()
1854                 }
1855             } else {
1856                 // Replace all parent lifetimes with 'static.
1857                 match param.kind {
1858                     GenericParamDefKind::Lifetime => {
1859                         tcx.types.re_static.into()
1860                     }
1861                     _ => tcx.mk_param_from_def(param)
1862                 }
1863             }
1864         });
1865         debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1866
1867         let ty = tcx.mk_opaque(def_id, substs);
1868         debug!("impl_trait_ty_to_ty: {}", ty);
1869         ty
1870     }
1871
1872     pub fn ty_of_arg(&self,
1873                      ty: &hir::Ty,
1874                      expected_ty: Option<Ty<'tcx>>)
1875                      -> Ty<'tcx>
1876     {
1877         match ty.node {
1878             hir::TyKind::Infer if expected_ty.is_some() => {
1879                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1880                 expected_ty.unwrap()
1881             }
1882             _ => self.ast_ty_to_ty(ty),
1883         }
1884     }
1885
1886     pub fn ty_of_fn(&self,
1887                     unsafety: hir::Unsafety,
1888                     abi: abi::Abi,
1889                     decl: &hir::FnDecl)
1890                     -> ty::PolyFnSig<'tcx> {
1891         debug!("ty_of_fn");
1892
1893         let tcx = self.tcx();
1894         let input_tys =
1895             decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
1896
1897         let output_ty = match decl.output {
1898             hir::Return(ref output) => self.ast_ty_to_ty(output),
1899             hir::DefaultReturn(..) => tcx.mk_unit(),
1900         };
1901
1902         debug!("ty_of_fn: output_ty={:?}", output_ty);
1903
1904         let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1905             input_tys,
1906             output_ty,
1907             decl.variadic,
1908             unsafety,
1909             abi
1910         ));
1911
1912         // Find any late-bound regions declared in return type that do
1913         // not appear in the arguments. These are not well-formed.
1914         //
1915         // Example:
1916         //     for<'a> fn() -> &'a str <-- 'a is bad
1917         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1918         let inputs = bare_fn_ty.inputs();
1919         let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1920             &inputs.map_bound(|i| i.to_owned()));
1921         let output = bare_fn_ty.output();
1922         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1923         for br in late_bound_in_ret.difference(&late_bound_in_args) {
1924             let lifetime_name = match *br {
1925                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1926                 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
1927             };
1928             let mut err = struct_span_err!(tcx.sess,
1929                                            decl.output.span(),
1930                                            E0581,
1931                                            "return type references {} \
1932                                             which is not constrained by the fn input types",
1933                                            lifetime_name);
1934             if let ty::BrAnon(_) = *br {
1935                 // The only way for an anonymous lifetime to wind up
1936                 // in the return type but **also** be unconstrained is
1937                 // if it only appears in "associated types" in the
1938                 // input. See #47511 for an example. In this case,
1939                 // though we can easily give a hint that ought to be
1940                 // relevant.
1941                 err.note("lifetimes appearing in an associated type \
1942                           are not considered constrained");
1943             }
1944             err.emit();
1945         }
1946
1947         bare_fn_ty
1948     }
1949
1950     /// Given the bounds on an object, determines what single region bound (if any) we can
1951     /// use to summarize this type. The basic idea is that we will use the bound the user
1952     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1953     /// for region bounds. It may be that we can derive no bound at all, in which case
1954     /// we return `None`.
1955     fn compute_object_lifetime_bound(&self,
1956         span: Span,
1957         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
1958         -> Option<ty::Region<'tcx>> // if None, use the default
1959     {
1960         let tcx = self.tcx();
1961
1962         debug!("compute_opt_region_bound(existential_predicates={:?})",
1963                existential_predicates);
1964
1965         // No explicit region bound specified. Therefore, examine trait
1966         // bounds and see if we can derive region bounds from those.
1967         let derived_region_bounds =
1968             object_region_bounds(tcx, existential_predicates);
1969
1970         // If there are no derived region bounds, then report back that we
1971         // can find no region bound. The caller will use the default.
1972         if derived_region_bounds.is_empty() {
1973             return None;
1974         }
1975
1976         // If any of the derived region bounds are 'static, that is always
1977         // the best choice.
1978         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1979             return Some(tcx.types.re_static);
1980         }
1981
1982         // Determine whether there is exactly one unique region in the set
1983         // of derived region bounds. If so, use that. Otherwise, report an
1984         // error.
1985         let r = derived_region_bounds[0];
1986         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1987             span_err!(tcx.sess, span, E0227,
1988                       "ambiguous lifetime bound, explicit lifetime bound required");
1989         }
1990         return Some(r);
1991     }
1992 }
1993
1994 /// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and
1995 /// the remaining general trait bounds.
1996 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1997                                          trait_bounds: &'b [hir::PolyTraitRef])
1998     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1999 {
2000     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
2001         // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
2002         match bound.trait_ref.path.def {
2003             Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
2004                 true
2005             }
2006             _ => false
2007         }
2008     });
2009
2010     let auto_traits = auto_traits.into_iter().map(|tr| {
2011         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
2012             trait_did
2013         } else {
2014             unreachable!()
2015         }
2016     }).collect::<Vec<_>>();
2017
2018     (auto_traits, trait_bounds)
2019 }
2020
2021 // A helper struct for conveniently grouping a set of bounds which we pass to
2022 // and return from functions in multiple places.
2023 #[derive(PartialEq, Eq, Clone, Debug)]
2024 pub struct Bounds<'tcx> {
2025     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2026     pub implicitly_sized: Option<Span>,
2027     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2028     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2029 }
2030
2031 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2032     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2033                       -> Vec<(ty::Predicate<'tcx>, Span)>
2034     {
2035         // If it could be sized, and is, add the sized predicate.
2036         let sized_predicate = self.implicitly_sized.and_then(|span| {
2037             tcx.lang_items().sized_trait().map(|sized| {
2038                 let trait_ref = ty::TraitRef {
2039                     def_id: sized,
2040                     substs: tcx.mk_substs_trait(param_ty, &[])
2041                 };
2042                 (trait_ref.to_predicate(), span)
2043             })
2044         });
2045
2046         sized_predicate.into_iter().chain(
2047             self.region_bounds.iter().map(|&(region_bound, span)| {
2048                 // Account for the binder being introduced below; no need to shift `param_ty`
2049                 // because, at present at least, it can only refer to early-bound regions.
2050                 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2051                 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2052                 (ty::Binder::dummy(outlives).to_predicate(), span)
2053             }).chain(
2054                 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2055                     (bound_trait_ref.to_predicate(), span)
2056                 })
2057             ).chain(
2058                 self.projection_bounds.iter().map(|&(projection, span)| {
2059                     (projection.to_predicate(), span)
2060                 })
2061             )
2062         ).collect()
2063     }
2064 }