]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[rust.git] / src / librustc_typeck / astconv.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Conversion from AST representation of types to the ty.rs
12 //! representation.  The main routine here is `ast_ty_to_ty()`: each use
13 //! is parameterized by an instance of `AstConv`.
14 //!
15 //! The parameterization of `ast_ty_to_ty()` is because it behaves
16 //! somewhat differently during the collect and check phases,
17 //! particularly with respect to looking up the types of top-level
18 //! items.  In the collect phase, the crate context is used as the
19 //! `AstConv` instance; in this phase, the `get_item_type()`
20 //! function triggers a recursive call to `type_of_item()`
21 //! (note that `ast_ty_to_ty()` will detect recursive types and report
22 //! an error).  In the check phase, when the FnCtxt is used as the
23 //! `AstConv`, `get_item_type()` just looks up the item type in
24 //! `tcx.types` (using `TyCtxt::item_type`).
25
26 use rustc_const_eval::eval_length;
27 use rustc_data_structures::accumulate_vec::AccumulateVec;
28 use hir;
29 use hir::def::Def;
30 use hir::def_id::DefId;
31 use middle::resolve_lifetime as rl;
32 use rustc::ty::subst::{Kind, Subst, Substs};
33 use rustc::traits;
34 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
35 use rustc::ty::wf::object_region_bounds;
36 use rustc_back::slice;
37 use require_c_abi_if_variadic;
38 use util::common::{ErrorReported, FN_OUTPUT_NAME};
39 use util::nodemap::{NodeMap, FxHashSet};
40
41 use std::cell::RefCell;
42 use std::iter;
43 use syntax::{abi, ast};
44 use syntax::feature_gate::{GateIssue, emit_feature_err};
45 use syntax::symbol::{Symbol, keywords};
46 use syntax_pos::Span;
47
48 pub trait AstConv<'gcx, 'tcx> {
49     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
50
51     /// A cache used for the result of `ast_ty_to_ty_cache`
52     fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
53
54     /// Returns the generic type and lifetime parameters for an item.
55     fn get_generics(&self, span: Span, id: DefId)
56                     -> Result<&'tcx ty::Generics<'tcx>, ErrorReported>;
57
58     /// Identify the type for an item, like a type alias, fn, or struct.
59     fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported>;
60
61     /// Returns the `TraitDef` for a given trait. This allows you to
62     /// figure out the set of type parameters defined on the trait.
63     fn get_trait_def(&self, span: Span, id: DefId)
64                      -> Result<&'tcx ty::TraitDef, ErrorReported>;
65
66     /// Ensure that the super-predicates for the trait with the given
67     /// id are available and also for the transitive set of
68     /// super-predicates.
69     fn ensure_super_predicates(&self, span: Span, id: DefId)
70                                -> Result<(), ErrorReported>;
71
72     /// Returns the set of bounds in scope for the type parameter with
73     /// the given id.
74     fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
75                                  -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
76
77     /// Return an (optional) substitution to convert bound type parameters that
78     /// are in scope into free ones. This function should only return Some
79     /// within a fn body.
80     /// See ParameterEnvironment::free_substs for more information.
81     fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
82
83     /// What lifetime should we use when a lifetime is omitted (and not elided)?
84     fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
85                 -> Option<&'tcx ty::Region>;
86
87     /// What type should we use when a type is omitted?
88     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
89
90     /// Same as ty_infer, but with a known type parameter definition.
91     fn ty_infer_for_def(&self,
92                         _def: &ty::TypeParameterDef<'tcx>,
93                         _substs: &[Kind<'tcx>],
94                         span: Span) -> Ty<'tcx> {
95         self.ty_infer(span)
96     }
97
98     /// Projecting an associated type from a (potentially)
99     /// higher-ranked trait reference is more complicated, because of
100     /// the possibility of late-bound regions appearing in the
101     /// associated type binding. This is not legal in function
102     /// signatures for that reason. In a function body, we can always
103     /// handle it because we can use inference variables to remove the
104     /// late-bound regions.
105     fn projected_ty_from_poly_trait_ref(&self,
106                                         span: Span,
107                                         poly_trait_ref: ty::PolyTraitRef<'tcx>,
108                                         item_name: ast::Name)
109                                         -> Ty<'tcx>;
110
111     /// Project an associated type from a non-higher-ranked trait reference.
112     /// This is fairly straightforward and can be accommodated in any context.
113     fn projected_ty(&self,
114                     span: Span,
115                     _trait_ref: ty::TraitRef<'tcx>,
116                     _item_name: ast::Name)
117                     -> Ty<'tcx>;
118
119     /// Invoked when we encounter an error from some prior pass
120     /// (e.g. resolve) that is translated into a ty-error. This is
121     /// used to help suppress derived errors typeck might otherwise
122     /// report.
123     fn set_tainted_by_errors(&self);
124 }
125
126 struct ConvertedBinding<'tcx> {
127     item_name: ast::Name,
128     ty: Ty<'tcx>,
129     span: Span,
130 }
131
132 /// Dummy type used for the `Self` of a `TraitRef` created for converting
133 /// a trait object, and which gets removed in `ExistentialTraitRef`.
134 /// This type must not appear anywhere in other converted types.
135 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
136
137 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
138     pub fn ast_region_to_region(&self,
139         lifetime: &hir::Lifetime,
140         def: Option<&ty::RegionParameterDef>)
141         -> &'tcx ty::Region
142     {
143         let tcx = self.tcx();
144         let r = match tcx.named_region_map.defs.get(&lifetime.id) {
145             Some(&rl::Region::Static) => {
146                 tcx.mk_region(ty::ReStatic)
147             }
148
149             Some(&rl::Region::LateBound(debruijn, id)) => {
150                 let name = tcx.hir.name(id);
151                 tcx.mk_region(ty::ReLateBound(debruijn,
152                     ty::BrNamed(tcx.hir.local_def_id(id), name)))
153             }
154
155             Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
156                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
157             }
158
159             Some(&rl::Region::EarlyBound(index, id)) => {
160                 let name = tcx.hir.name(id);
161                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
162                     index: index,
163                     name: name
164                 }))
165             }
166
167             Some(&rl::Region::Free(scope, id)) => {
168                 let name = tcx.hir.name(id);
169                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
170                     scope: scope.to_code_extent(&tcx.region_maps),
171                     bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name)
172                 }))
173
174                     // (*) -- not late-bound, won't change
175             }
176
177             None => {
178                 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
179             }
180         };
181
182         debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
183                 lifetime,
184                 r);
185
186         r
187     }
188
189     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
190     /// returns an appropriate set of substitutions for this particular reference to `I`.
191     pub fn ast_path_substs_for_ty(&self,
192         span: Span,
193         def_id: DefId,
194         item_segment: &hir::PathSegment)
195         -> &'tcx Substs<'tcx>
196     {
197         let tcx = self.tcx();
198
199         match item_segment.parameters {
200             hir::AngleBracketedParameters(_) => {}
201             hir::ParenthesizedParameters(..) => {
202                 struct_span_err!(tcx.sess, span, E0214,
203                           "parenthesized parameters may only be used with a trait")
204                     .span_label(span, &format!("only traits may use parentheses"))
205                     .emit();
206
207                 return Substs::for_item(tcx, def_id, |_, _| {
208                     tcx.mk_region(ty::ReStatic)
209                 }, |_, _| {
210                     tcx.types.err
211                 });
212             }
213         }
214
215         let (substs, assoc_bindings) =
216             self.create_substs_for_ast_path(span,
217                                             def_id,
218                                             &item_segment.parameters,
219                                             None);
220
221         assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
222
223         substs
224     }
225
226     /// Given the type/region arguments provided to some path (along with
227     /// an implicit Self, if this is a trait reference) returns the complete
228     /// set of substitutions. This may involve applying defaulted type parameters.
229     ///
230     /// Note that the type listing given here is *exactly* what the user provided.
231     fn create_substs_for_ast_path(&self,
232         span: Span,
233         def_id: DefId,
234         parameters: &hir::PathParameters,
235         self_ty: Option<Ty<'tcx>>)
236         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
237     {
238         let tcx = self.tcx();
239
240         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
241                parameters={:?})",
242                def_id, self_ty, parameters);
243
244         let (lifetimes, num_types_provided, infer_types) = match *parameters {
245             hir::AngleBracketedParameters(ref data) => {
246                 (&data.lifetimes[..], data.types.len(), data.infer_types)
247             }
248             hir::ParenthesizedParameters(_) => (&[][..], 1, false)
249         };
250
251         // If the type is parameterized by this region, then replace this
252         // region with the current anon region binding (in other words,
253         // whatever & would get replaced with).
254         let decl_generics = match self.get_generics(span, def_id) {
255             Ok(generics) => generics,
256             Err(ErrorReported) => {
257                 // No convenient way to recover from a cycle here. Just bail. Sorry!
258                 self.tcx().sess.abort_if_errors();
259                 bug!("ErrorReported returned, but no errors reports?")
260             }
261         };
262         let expected_num_region_params = decl_generics.regions.len();
263         let supplied_num_region_params = lifetimes.len();
264         if expected_num_region_params != supplied_num_region_params {
265             report_lifetime_number_error(tcx, span,
266                                          supplied_num_region_params,
267                                          expected_num_region_params);
268         }
269
270         // If a self-type was declared, one should be provided.
271         assert_eq!(decl_generics.has_self, self_ty.is_some());
272
273         // Check the number of type parameters supplied by the user.
274         let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
275         if !infer_types || num_types_provided > ty_param_defs.len() {
276             check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
277         }
278
279         let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
280         let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
281             if let Some(ref default) = p.default {
282                 if is_object && default.has_self_ty() {
283                     // There is no suitable inference default for a type parameter
284                     // that references self, in an object type.
285                     return true;
286                 }
287             }
288
289             false
290         };
291
292         let mut output_assoc_binding = None;
293         let substs = Substs::for_item(tcx, def_id, |def, _| {
294             let i = def.index as usize - self_ty.is_some() as usize;
295             if let Some(lifetime) = lifetimes.get(i) {
296                 self.ast_region_to_region(lifetime, Some(def))
297             } else {
298                 tcx.mk_region(ty::ReStatic)
299             }
300         }, |def, substs| {
301             let i = def.index as usize;
302
303             // Handle Self first, so we can adjust the index to match the AST.
304             if let (0, Some(ty)) = (i, self_ty) {
305                 return ty;
306             }
307
308             let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
309             if i < num_types_provided {
310                 // A provided type parameter.
311                 match *parameters {
312                     hir::AngleBracketedParameters(ref data) => {
313                         self.ast_ty_to_ty(&data.types[i])
314                     }
315                     hir::ParenthesizedParameters(ref data) => {
316                         assert_eq!(i, 0);
317                         let (ty, assoc) = self.convert_parenthesized_parameters(data);
318                         output_assoc_binding = Some(assoc);
319                         ty
320                     }
321                 }
322             } else if infer_types {
323                 // No type parameters were provided, we can infer all.
324                 let ty_var = if !default_needs_object_self(def) {
325                     self.ty_infer_for_def(def, substs, span)
326                 } else {
327                     self.ty_infer(span)
328                 };
329                 ty_var
330             } else if let Some(default) = def.default {
331                 // No type parameter provided, but a default exists.
332
333                 // If we are converting an object type, then the
334                 // `Self` parameter is unknown. However, some of the
335                 // other type parameters may reference `Self` in their
336                 // defaults. This will lead to an ICE if we are not
337                 // careful!
338                 if default_needs_object_self(def) {
339                     struct_span_err!(tcx.sess, span, E0393,
340                                      "the type parameter `{}` must be explicitly specified",
341                                      def.name)
342                         .span_label(span, &format!("missing reference to `{}`", def.name))
343                         .note(&format!("because of the default `Self` reference, \
344                                         type parameters must be specified on object types"))
345                         .emit();
346                     tcx.types.err
347                 } else {
348                     // This is a default type parameter.
349                     default.subst_spanned(tcx, substs, Some(span))
350                 }
351             } else {
352                 // We've already errored above about the mismatch.
353                 tcx.types.err
354             }
355         });
356
357         let assoc_bindings = match *parameters {
358             hir::AngleBracketedParameters(ref data) => {
359                 data.bindings.iter().map(|b| {
360                     ConvertedBinding {
361                         item_name: b.name,
362                         ty: self.ast_ty_to_ty(&b.ty),
363                         span: b.span
364                     }
365                 }).collect()
366             }
367             hir::ParenthesizedParameters(ref data) => {
368                 vec![output_assoc_binding.unwrap_or_else(|| {
369                     // This is an error condition, but we should
370                     // get the associated type binding anyway.
371                     self.convert_parenthesized_parameters(data).1
372                 })]
373             }
374         };
375
376         debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
377                decl_generics, self_ty, substs);
378
379         (substs, assoc_bindings)
380     }
381
382     fn convert_parenthesized_parameters(&self,
383                                         data: &hir::ParenthesizedParameterData)
384                                         -> (Ty<'tcx>, ConvertedBinding<'tcx>)
385     {
386         let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
387             self.ast_ty_to_ty(a_t)
388         }));
389
390         let (output, output_span) = match data.output {
391             Some(ref output_ty) => {
392                 (self.ast_ty_to_ty(output_ty), output_ty.span)
393             }
394             None => {
395                 (self.tcx().mk_nil(), data.span)
396             }
397         };
398
399         let output_binding = ConvertedBinding {
400             item_name: Symbol::intern(FN_OUTPUT_NAME),
401             ty: output,
402             span: output_span
403         };
404
405         (self.tcx().mk_ty(ty::TyTuple(inputs, false)), output_binding)
406     }
407
408     /// Instantiates the path for the given trait reference, assuming that it's
409     /// bound to a valid trait type. Returns the def_id for the defining trait.
410     /// Fails if the type is a type other than a trait type.
411     ///
412     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
413     /// are disallowed. Otherwise, they are pushed onto the vector given.
414     pub fn instantiate_mono_trait_ref(&self,
415         trait_ref: &hir::TraitRef,
416         self_ty: Ty<'tcx>)
417         -> ty::TraitRef<'tcx>
418     {
419         let trait_def_id = self.trait_def_id(trait_ref);
420         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
421                                         trait_def_id,
422                                         self_ty,
423                                         trait_ref.path.segments.last().unwrap())
424     }
425
426     fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
427         let path = &trait_ref.path;
428         match path.def {
429             Def::Trait(trait_def_id) => trait_def_id,
430             Def::Err => {
431                 self.tcx().sess.fatal("cannot continue compilation due to previous error");
432             }
433             _ => {
434                 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
435                             self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
436             }
437         }
438     }
439
440     pub fn instantiate_poly_trait_ref(&self,
441         ast_trait_ref: &hir::PolyTraitRef,
442         self_ty: Ty<'tcx>,
443         poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
444         -> ty::PolyTraitRef<'tcx>
445     {
446         let trait_ref = &ast_trait_ref.trait_ref;
447         let trait_def_id = self.trait_def_id(trait_ref);
448
449         debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
450
451         let (substs, assoc_bindings) =
452             self.create_substs_for_ast_trait_ref(trait_ref.path.span,
453                                                  trait_def_id,
454                                                  self_ty,
455                                                  trait_ref.path.segments.last().unwrap());
456         let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
457
458         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
459             // specify type to assert that error was already reported in Err case:
460             let predicate: Result<_, ErrorReported> =
461                 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
462                                                                    poly_trait_ref,
463                                                                    binding);
464             predicate.ok() // ok to ignore Err() because ErrorReported (see above)
465         }));
466
467         debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
468                trait_ref, poly_projections, poly_trait_ref);
469         poly_trait_ref
470     }
471
472     fn ast_path_to_mono_trait_ref(&self,
473                                   span: Span,
474                                   trait_def_id: DefId,
475                                   self_ty: Ty<'tcx>,
476                                   trait_segment: &hir::PathSegment)
477                                   -> ty::TraitRef<'tcx>
478     {
479         let (substs, assoc_bindings) =
480             self.create_substs_for_ast_trait_ref(span,
481                                                  trait_def_id,
482                                                  self_ty,
483                                                  trait_segment);
484         assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
485         ty::TraitRef::new(trait_def_id, substs)
486     }
487
488     fn create_substs_for_ast_trait_ref(&self,
489                                        span: Span,
490                                        trait_def_id: DefId,
491                                        self_ty: Ty<'tcx>,
492                                        trait_segment: &hir::PathSegment)
493                                        -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
494     {
495         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
496                trait_segment);
497
498         let trait_def = match self.get_trait_def(span, trait_def_id) {
499             Ok(trait_def) => trait_def,
500             Err(ErrorReported) => {
501                 // No convenient way to recover from a cycle here. Just bail. Sorry!
502                 self.tcx().sess.abort_if_errors();
503                 bug!("ErrorReported returned, but no errors reports?")
504             }
505         };
506
507         match trait_segment.parameters {
508             hir::AngleBracketedParameters(_) => {
509                 // For now, require that parenthetical notation be used
510                 // only with `Fn()` etc.
511                 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
512                     emit_feature_err(&self.tcx().sess.parse_sess,
513                                      "unboxed_closures", span, GateIssue::Language,
514                                      "\
515                         the precise format of `Fn`-family traits' \
516                         type parameters is subject to change. \
517                         Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
518                 }
519             }
520             hir::ParenthesizedParameters(_) => {
521                 // For now, require that parenthetical notation be used
522                 // only with `Fn()` etc.
523                 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
524                     emit_feature_err(&self.tcx().sess.parse_sess,
525                                      "unboxed_closures", span, GateIssue::Language,
526                                      "\
527                         parenthetical notation is only stable when used with `Fn`-family traits");
528                 }
529             }
530         }
531
532         self.create_substs_for_ast_path(span,
533                                         trait_def_id,
534                                         &trait_segment.parameters,
535                                         Some(self_ty))
536     }
537
538     fn trait_defines_associated_type_named(&self,
539                                            trait_def_id: DefId,
540                                            assoc_name: ast::Name)
541                                            -> bool
542     {
543         self.tcx().associated_items(trait_def_id).any(|item| {
544             item.kind == ty::AssociatedKind::Type && item.name == assoc_name
545         })
546     }
547
548     fn ast_type_binding_to_poly_projection_predicate(
549         &self,
550         _path_id: ast::NodeId,
551         trait_ref: ty::PolyTraitRef<'tcx>,
552         binding: &ConvertedBinding<'tcx>)
553         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
554     {
555         let tcx = self.tcx();
556
557         // Given something like `U : SomeTrait<T=X>`, we want to produce a
558         // predicate like `<U as SomeTrait>::T = X`. This is somewhat
559         // subtle in the event that `T` is defined in a supertrait of
560         // `SomeTrait`, because in that case we need to upcast.
561         //
562         // That is, consider this case:
563         //
564         // ```
565         // trait SubTrait : SuperTrait<int> { }
566         // trait SuperTrait<A> { type T; }
567         //
568         // ... B : SubTrait<T=foo> ...
569         // ```
570         //
571         // We want to produce `<B as SuperTrait<int>>::T == foo`.
572
573         // Find any late-bound regions declared in `ty` that are not
574         // declared in the trait-ref. These are not wellformed.
575         //
576         // Example:
577         //
578         //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
579         //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
580         let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
581         let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
582         debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
583         debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
584         for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
585             let br_name = match *br {
586                 ty::BrNamed(_, name) => name,
587                 _ => {
588                     span_bug!(
589                         binding.span,
590                         "anonymous bound region {:?} in binding but not trait ref",
591                         br);
592                 }
593             };
594             struct_span_err!(tcx.sess,
595                              binding.span,
596                              E0582,
597                              "binding for associated type `{}` references lifetime `{}`, \
598                               which does not appear in the trait input types",
599                              binding.item_name, br_name)
600                 .emit();
601         }
602
603         // Simple case: X is defined in the current trait.
604         if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
605             return Ok(trait_ref.map_bound(|trait_ref| {
606                 ty::ProjectionPredicate {
607                     projection_ty: ty::ProjectionTy {
608                         trait_ref: trait_ref,
609                         item_name: binding.item_name,
610                     },
611                     ty: binding.ty,
612                 }
613             }));
614         }
615
616         // Otherwise, we have to walk through the supertraits to find
617         // those that do.
618         self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
619
620         let candidates =
621             traits::supertraits(tcx, trait_ref.clone())
622             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
623
624         let candidate = self.one_bound_for_assoc_type(candidates,
625                                                       &trait_ref.to_string(),
626                                                       &binding.item_name.as_str(),
627                                                       binding.span)?;
628
629         Ok(candidate.map_bound(|trait_ref| {
630             ty::ProjectionPredicate {
631                 projection_ty: ty::ProjectionTy {
632                     trait_ref: trait_ref,
633                     item_name: binding.item_name,
634                 },
635                 ty: binding.ty,
636             }
637         }))
638     }
639
640     fn ast_path_to_ty(&self,
641         span: Span,
642         did: DefId,
643         item_segment: &hir::PathSegment)
644         -> Ty<'tcx>
645     {
646         let tcx = self.tcx();
647         let decl_ty = match self.get_item_type(span, did) {
648             Ok(ty) => ty,
649             Err(ErrorReported) => {
650                 return tcx.types.err;
651             }
652         };
653
654         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
655         decl_ty.subst(self.tcx(), substs)
656     }
657
658     /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
659     /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
660     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
661                                 -> ty::ExistentialTraitRef<'tcx> {
662         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
663         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
664     }
665
666     fn conv_object_ty_poly_trait_ref(&self,
667         span: Span,
668         trait_bounds: &[hir::PolyTraitRef],
669         lifetime: &hir::Lifetime)
670         -> Ty<'tcx>
671     {
672         let tcx = self.tcx();
673
674         if trait_bounds.is_empty() {
675             span_err!(tcx.sess, span, E0224,
676                       "at least one non-builtin trait is required for an object type");
677             return tcx.types.err;
678         }
679
680         let mut projection_bounds = vec![];
681         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
682         let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
683                                                         dummy_self,
684                                                         &mut projection_bounds);
685
686         let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
687
688         if !trait_bounds.is_empty() {
689             let b = &trait_bounds[0];
690             let span = b.trait_ref.path.span;
691             struct_span_err!(self.tcx().sess, span, E0225,
692                 "only Send/Sync traits can be used as additional traits in a trait object")
693                 .span_label(span, &format!("non-Send/Sync additional trait"))
694                 .emit();
695         }
696
697         // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
698         let existential_principal = principal.map_bound(|trait_ref| {
699             self.trait_ref_to_existential(trait_ref)
700         });
701         let existential_projections = projection_bounds.iter().map(|bound| {
702             bound.map_bound(|b| {
703                 let p = b.projection_ty;
704                 ty::ExistentialProjection {
705                     trait_ref: self.trait_ref_to_existential(p.trait_ref),
706                     item_name: p.item_name,
707                     ty: b.ty
708                 }
709             })
710         });
711
712         // ensure the super predicates and stop if we encountered an error
713         if self.ensure_super_predicates(span, principal.def_id()).is_err() {
714             return tcx.types.err;
715         }
716
717         // check that there are no gross object safety violations,
718         // most importantly, that the supertraits don't contain Self,
719         // to avoid ICE-s.
720         let object_safety_violations =
721             tcx.astconv_object_safety_violations(principal.def_id());
722         if !object_safety_violations.is_empty() {
723             tcx.report_object_safety_error(
724                 span, principal.def_id(), object_safety_violations)
725                 .emit();
726             return tcx.types.err;
727         }
728
729         let mut associated_types = FxHashSet::default();
730         for tr in traits::supertraits(tcx, principal) {
731             associated_types.extend(tcx.associated_items(tr.def_id())
732                 .filter(|item| item.kind == ty::AssociatedKind::Type)
733                 .map(|item| (tr.def_id(), item.name)));
734         }
735
736         for projection_bound in &projection_bounds {
737             let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
738                         projection_bound.0.projection_ty.item_name);
739             associated_types.remove(&pair);
740         }
741
742         for (trait_def_id, name) in associated_types {
743             struct_span_err!(tcx.sess, span, E0191,
744                 "the value of the associated type `{}` (from the trait `{}`) must be specified",
745                         name,
746                         tcx.item_path_str(trait_def_id))
747                         .span_label(span, &format!(
748                             "missing associated type `{}` value", name))
749                         .emit();
750         }
751
752         let mut v =
753             iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
754             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
755             .chain(existential_projections
756                    .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
757             .collect::<AccumulateVec<[_; 8]>>();
758         v.sort_by(|a, b| a.cmp(tcx, b));
759         let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
760
761
762         // Explicitly specified region bound. Use that.
763         let region_bound = if !lifetime.is_elided() {
764             self.ast_region_to_region(lifetime, None)
765         } else {
766             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
767                 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
768                     self.ast_region_to_region(lifetime, None)
769                 } else {
770                     self.re_infer(span, None).unwrap_or_else(|| {
771                         span_err!(tcx.sess, span, E0228,
772                                   "the lifetime bound for this object type cannot be deduced \
773                                    from context; please supply an explicit bound");
774                         tcx.mk_region(ty::ReStatic)
775                     })
776                 }
777             })
778         };
779
780         debug!("region_bound: {:?}", region_bound);
781
782         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
783         debug!("trait_object_type: {:?}", ty);
784         ty
785     }
786
787     fn report_ambiguous_associated_type(&self,
788                                         span: Span,
789                                         type_str: &str,
790                                         trait_str: &str,
791                                         name: &str) {
792         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
793             .span_label(span, &format!("ambiguous associated type"))
794             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
795                   type_str, trait_str, name))
796             .emit();
797
798     }
799
800     // Search for a bound on a type parameter which includes the associated item
801     // given by assoc_name. ty_param_node_id is the node id for the type parameter
802     // (which might be `Self`, but only if it is the `Self` of a trait, not an
803     // impl). This function will fail if there are no suitable bounds or there is
804     // any ambiguity.
805     fn find_bound_for_assoc_item(&self,
806                                  ty_param_node_id: ast::NodeId,
807                                  ty_param_name: ast::Name,
808                                  assoc_name: ast::Name,
809                                  span: Span)
810                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
811     {
812         let tcx = self.tcx();
813
814         let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
815             Ok(v) => v,
816             Err(ErrorReported) => {
817                 return Err(ErrorReported);
818             }
819         };
820
821         // Ensure the super predicates and stop if we encountered an error.
822         if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
823             return Err(ErrorReported);
824         }
825
826         // Check that there is exactly one way to find an associated type with the
827         // correct name.
828         let suitable_bounds =
829             traits::transitive_bounds(tcx, &bounds)
830             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
831
832         self.one_bound_for_assoc_type(suitable_bounds,
833                                       &ty_param_name.as_str(),
834                                       &assoc_name.as_str(),
835                                       span)
836     }
837
838
839     // Checks that bounds contains exactly one element and reports appropriate
840     // errors otherwise.
841     fn one_bound_for_assoc_type<I>(&self,
842                                 mut bounds: I,
843                                 ty_param_name: &str,
844                                 assoc_name: &str,
845                                 span: Span)
846         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
847         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
848     {
849         let bound = match bounds.next() {
850             Some(bound) => bound,
851             None => {
852                 struct_span_err!(self.tcx().sess, span, E0220,
853                           "associated type `{}` not found for `{}`",
854                           assoc_name,
855                           ty_param_name)
856                   .span_label(span, &format!("associated type `{}` not found", assoc_name))
857                   .emit();
858                 return Err(ErrorReported);
859             }
860         };
861
862         if let Some(bound2) = bounds.next() {
863             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
864             let mut err = struct_span_err!(
865                 self.tcx().sess, span, E0221,
866                 "ambiguous associated type `{}` in bounds of `{}`",
867                 assoc_name,
868                 ty_param_name);
869             err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
870
871             for bound in bounds {
872                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
873                     item.kind == ty::AssociatedKind::Type && item.name == assoc_name
874                 })
875                 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
876
877                 if let Some(span) = bound_span {
878                     err.span_label(span, &format!("ambiguous `{}` from `{}`",
879                                                   assoc_name,
880                                                   bound));
881                 } else {
882                     span_note!(&mut err, span,
883                                "associated type `{}` could derive from `{}`",
884                                ty_param_name,
885                                bound);
886                 }
887             }
888             err.emit();
889         }
890
891         return Ok(bound);
892     }
893
894     // Create a type from a path to an associated type.
895     // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
896     // and item_segment is the path segment for D. We return a type and a def for
897     // the whole path.
898     // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
899     // parameter or Self.
900     pub fn associated_path_def_to_ty(&self,
901                                      ref_id: ast::NodeId,
902                                      span: Span,
903                                      ty: Ty<'tcx>,
904                                      ty_path_def: Def,
905                                      item_segment: &hir::PathSegment)
906                                      -> (Ty<'tcx>, Def)
907     {
908         let tcx = self.tcx();
909         let assoc_name = item_segment.name;
910
911         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
912
913         tcx.prohibit_type_params(slice::ref_slice(item_segment));
914
915         // Find the type of the associated item, and the trait where the associated
916         // item is declared.
917         let bound = match (&ty.sty, ty_path_def) {
918             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
919                 // `Self` in an impl of a trait - we have a concrete self type and a
920                 // trait reference.
921                 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
922                 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
923                     trait_ref.subst(tcx, free_substs)
924                 } else {
925                     trait_ref
926                 };
927
928                 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
929                     return (tcx.types.err, Def::Err);
930                 }
931
932                 let candidates =
933                     traits::supertraits(tcx, ty::Binder(trait_ref))
934                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
935                                                                          assoc_name));
936
937                 match self.one_bound_for_assoc_type(candidates,
938                                                     "Self",
939                                                     &assoc_name.as_str(),
940                                                     span) {
941                     Ok(bound) => bound,
942                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
943                 }
944             }
945             (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
946                 let trait_node_id = tcx.hir.as_local_node_id(trait_did).unwrap();
947                 match self.find_bound_for_assoc_item(trait_node_id,
948                                                      keywords::SelfType.name(),
949                                                      assoc_name,
950                                                      span) {
951                     Ok(bound) => bound,
952                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
953                 }
954             }
955             (&ty::TyParam(_), Def::TyParam(param_did)) => {
956                 let param_node_id = tcx.hir.as_local_node_id(param_did).unwrap();
957                 let param_name = tcx.type_parameter_def(param_node_id).name;
958                 match self.find_bound_for_assoc_item(param_node_id,
959                                                      param_name,
960                                                      assoc_name,
961                                                      span) {
962                     Ok(bound) => bound,
963                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
964                 }
965             }
966             _ => {
967                 // Don't print TyErr to the user.
968                 if !ty.references_error() {
969                     self.report_ambiguous_associated_type(span,
970                                                           &ty.to_string(),
971                                                           "Trait",
972                                                           &assoc_name.as_str());
973                 }
974                 return (tcx.types.err, Def::Err);
975             }
976         };
977
978         let trait_did = bound.0.def_id;
979         let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
980
981         let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
982         let def_id = item.expect("missing associated type").def_id;
983         tcx.check_stability(def_id, ref_id, span);
984         (ty, Def::AssociatedTy(def_id))
985     }
986
987     fn qpath_to_ty(&self,
988                    span: Span,
989                    opt_self_ty: Option<Ty<'tcx>>,
990                    trait_def_id: DefId,
991                    trait_segment: &hir::PathSegment,
992                    item_segment: &hir::PathSegment)
993                    -> Ty<'tcx>
994     {
995         let tcx = self.tcx();
996
997         tcx.prohibit_type_params(slice::ref_slice(item_segment));
998
999         let self_ty = if let Some(ty) = opt_self_ty {
1000             ty
1001         } else {
1002             let path_str = tcx.item_path_str(trait_def_id);
1003             self.report_ambiguous_associated_type(span,
1004                                                   "Type",
1005                                                   &path_str,
1006                                                   &item_segment.name.as_str());
1007             return tcx.types.err;
1008         };
1009
1010         debug!("qpath_to_ty: self_type={:?}", self_ty);
1011
1012         let trait_ref = self.ast_path_to_mono_trait_ref(span,
1013                                                         trait_def_id,
1014                                                         self_ty,
1015                                                         trait_segment);
1016
1017         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1018
1019         self.projected_ty(span, trait_ref, item_segment.name)
1020     }
1021
1022     // Check a type Path and convert it to a Ty.
1023     pub fn def_to_ty(&self,
1024                      opt_self_ty: Option<Ty<'tcx>>,
1025                      path: &hir::Path,
1026                      permit_variants: bool)
1027                      -> Ty<'tcx> {
1028         let tcx = self.tcx();
1029
1030         debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1031                path.def, opt_self_ty, path.segments);
1032
1033         let span = path.span;
1034         match path.def {
1035             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1036                 assert_eq!(opt_self_ty, None);
1037                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1038                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1039             }
1040             Def::Variant(did) if permit_variants => {
1041                 // Convert "variant type" as if it were a real type.
1042                 // The resulting `Ty` is type of the variant's enum for now.
1043                 assert_eq!(opt_self_ty, None);
1044                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1045                 self.ast_path_to_ty(span,
1046                                     tcx.parent_def_id(did).unwrap(),
1047                                     path.segments.last().unwrap())
1048             }
1049             Def::TyParam(did) => {
1050                 assert_eq!(opt_self_ty, None);
1051                 tcx.prohibit_type_params(&path.segments);
1052
1053                 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1054                 let param = tcx.ty_param_defs.borrow().get(&node_id)
1055                                .map(ty::ParamTy::for_def);
1056                 if let Some(p) = param {
1057                     p.to_ty(tcx)
1058                 } else {
1059                     // Only while computing defaults of earlier type
1060                     // parameters can a type parameter be missing its def.
1061                     struct_span_err!(tcx.sess, span, E0128,
1062                                      "type parameters with a default cannot use \
1063                                       forward declared identifiers")
1064                         .span_label(span, &format!("defaulted type parameters \
1065                                                     cannot be forward declared"))
1066                         .emit();
1067                     tcx.types.err
1068                 }
1069             }
1070             Def::SelfTy(_, Some(def_id)) => {
1071                 // Self in impl (we know the concrete type).
1072
1073                 assert_eq!(opt_self_ty, None);
1074                 tcx.prohibit_type_params(&path.segments);
1075
1076                 // FIXME: Self type is not always computed when we are here because type parameter
1077                 // bounds may affect Self type and have to be converted before it.
1078                 let ty = if def_id.is_local() {
1079                     tcx.item_types.borrow().get(&def_id).cloned()
1080                 } else {
1081                     Some(tcx.item_type(def_id))
1082                 };
1083                 if let Some(ty) = ty {
1084                     if let Some(free_substs) = self.get_free_substs() {
1085                         ty.subst(tcx, free_substs)
1086                     } else {
1087                         ty
1088                     }
1089                 } else {
1090                     tcx.sess.span_err(span, "`Self` type is used before it's determined");
1091                     tcx.types.err
1092                 }
1093             }
1094             Def::SelfTy(Some(_), None) => {
1095                 // Self in trait.
1096                 assert_eq!(opt_self_ty, None);
1097                 tcx.prohibit_type_params(&path.segments);
1098                 tcx.mk_self_type()
1099             }
1100             Def::AssociatedTy(def_id) => {
1101                 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1102                 let trait_did = tcx.parent_def_id(def_id).unwrap();
1103                 self.qpath_to_ty(span,
1104                                  opt_self_ty,
1105                                  trait_did,
1106                                  &path.segments[path.segments.len()-2],
1107                                  path.segments.last().unwrap())
1108             }
1109             Def::PrimTy(prim_ty) => {
1110                 assert_eq!(opt_self_ty, None);
1111                 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1112             }
1113             Def::Err => {
1114                 self.set_tainted_by_errors();
1115                 return self.tcx().types.err;
1116             }
1117             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1118         }
1119     }
1120
1121     /// Parses the programmer's textual representation of a type into our
1122     /// internal notion of a type.
1123     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1124         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1125                ast_ty.id, ast_ty);
1126
1127         let tcx = self.tcx();
1128
1129         let cache = self.ast_ty_to_ty_cache();
1130         if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1131             return ty;
1132         }
1133
1134         let result_ty = match ast_ty.node {
1135             hir::TySlice(ref ty) => {
1136                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1137             }
1138             hir::TyPtr(ref mt) => {
1139                 tcx.mk_ptr(ty::TypeAndMut {
1140                     ty: self.ast_ty_to_ty(&mt.ty),
1141                     mutbl: mt.mutbl
1142                 })
1143             }
1144             hir::TyRptr(ref region, ref mt) => {
1145                 let r = self.ast_region_to_region(region, None);
1146                 debug!("TyRef r={:?}", r);
1147                 let t = self.ast_ty_to_ty(&mt.ty);
1148                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1149             }
1150             hir::TyNever => {
1151                 tcx.types.never
1152             },
1153             hir::TyTup(ref fields) => {
1154                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1155             }
1156             hir::TyBareFn(ref bf) => {
1157                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1158                 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1159
1160                 // Find any late-bound regions declared in return type that do
1161                 // not appear in the arguments. These are not wellformed.
1162                 //
1163                 // Example:
1164                 //
1165                 //     for<'a> fn() -> &'a str <-- 'a is bad
1166                 //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1167                 //
1168                 // Note that we do this check **here** and not in
1169                 // `ty_of_bare_fn` because the latter is also used to make
1170                 // the types for fn items, and we do not want to issue a
1171                 // warning then. (Once we fix #32330, the regions we are
1172                 // checking for here would be considered early bound
1173                 // anyway.)
1174                 let inputs = bare_fn_ty.sig.inputs();
1175                 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1176                     &inputs.map_bound(|i| i.to_owned()));
1177                 let output = bare_fn_ty.sig.output();
1178                 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1179                 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1180                     let br_name = match *br {
1181                         ty::BrNamed(_, name) => name,
1182                         _ => {
1183                             span_bug!(
1184                                 bf.decl.output.span(),
1185                                 "anonymous bound region {:?} in return but not args",
1186                                 br);
1187                         }
1188                     };
1189                     struct_span_err!(tcx.sess,
1190                                      ast_ty.span,
1191                                      E0581,
1192                                      "return type references lifetime `{}`, \
1193                                       which does not appear in the fn input types",
1194                                      br_name)
1195                         .emit();
1196                 }
1197                 tcx.mk_fn_ptr(bare_fn_ty)
1198             }
1199             hir::TyTraitObject(ref bounds, ref lifetime) => {
1200                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1201             }
1202             hir::TyImplTrait(ref bounds) => {
1203                 use collect::{compute_bounds, SizedByDefault};
1204
1205                 // Figure out if we can allow an `impl Trait` here, by walking up
1206                 // to a `fn` or inherent `impl` method, going only through `Ty`
1207                 // or `TraitRef` nodes (as nothing else should be in types) and
1208                 // ensuring that we reach the `fn`/method signature's return type.
1209                 let mut node_id = ast_ty.id;
1210                 let fn_decl = loop {
1211                     let parent = tcx.hir.get_parent_node(node_id);
1212                     match tcx.hir.get(parent) {
1213                         hir::map::NodeItem(&hir::Item {
1214                             node: hir::ItemFn(ref fn_decl, ..), ..
1215                         }) => break Some(fn_decl),
1216
1217                         hir::map::NodeImplItem(&hir::ImplItem {
1218                             node: hir::ImplItemKind::Method(ref sig, _), ..
1219                         }) => {
1220                             match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1221                                 hir::ItemImpl(.., None, _, _) => {
1222                                     break Some(&sig.decl)
1223                                 }
1224                                 _ => break None
1225                             }
1226                         }
1227
1228                         hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1229
1230                         _ => break None
1231                     }
1232                     node_id = parent;
1233                 };
1234                 let allow = fn_decl.map_or(false, |fd| {
1235                     match fd.output {
1236                         hir::DefaultReturn(_) => false,
1237                         hir::Return(ref ty) => ty.id == node_id
1238                     }
1239                 });
1240
1241                 // Create the anonymized type.
1242                 if allow {
1243                     let def_id = tcx.hir.local_def_id(ast_ty.id);
1244                     if let Err(ErrorReported) = self.get_generics(ast_ty.span, def_id) {
1245                         return tcx.types.err;
1246                     }
1247                     let substs = Substs::identity_for_item(tcx, def_id);
1248                     let ty = tcx.mk_anon(tcx.hir.local_def_id(ast_ty.id), substs);
1249
1250                     // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1251                     let bounds = compute_bounds(self, ty, bounds,
1252                                                 SizedByDefault::Yes,
1253                                                 ast_ty.span);
1254                     let predicates = bounds.predicates(tcx, ty);
1255                     let predicates = tcx.lift_to_global(&predicates).unwrap();
1256                     tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1257                         parent: None,
1258                         predicates: predicates
1259                     });
1260
1261                     ty
1262                 } else {
1263                     span_err!(tcx.sess, ast_ty.span, E0562,
1264                               "`impl Trait` not allowed outside of function \
1265                                and inherent method return types");
1266                     tcx.types.err
1267                 }
1268             }
1269             hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1270                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1271                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1272                     self.ast_ty_to_ty(qself)
1273                 });
1274                 self.def_to_ty(opt_self_ty, path, false)
1275             }
1276             hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1277                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1278                 let ty = self.ast_ty_to_ty(qself);
1279
1280                 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1281                     path.def
1282                 } else {
1283                     Def::Err
1284                 };
1285                 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1286             }
1287             hir::TyArray(ref ty, length) => {
1288                 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1289                     tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1290                 } else {
1291                     self.tcx().types.err
1292                 }
1293             }
1294             hir::TyTypeof(ref _e) => {
1295                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1296                                  "`typeof` is a reserved keyword but unimplemented")
1297                     .span_label(ast_ty.span, &format!("reserved keyword"))
1298                     .emit();
1299
1300                 tcx.types.err
1301             }
1302             hir::TyInfer => {
1303                 // TyInfer also appears as the type of arguments or return
1304                 // values in a ExprClosure, or as
1305                 // the type of local variables. Both of these cases are
1306                 // handled specially and will not descend into this routine.
1307                 self.ty_infer(ast_ty.span)
1308             }
1309         };
1310
1311         cache.borrow_mut().insert(ast_ty.id, result_ty);
1312
1313         result_ty
1314     }
1315
1316     pub fn ty_of_arg(&self,
1317                      ty: &hir::Ty,
1318                      expected_ty: Option<Ty<'tcx>>)
1319                      -> Ty<'tcx>
1320     {
1321         match ty.node {
1322             hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1323             hir::TyInfer => self.ty_infer(ty.span),
1324             _ => self.ast_ty_to_ty(ty),
1325         }
1326     }
1327
1328     pub fn ty_of_fn(&self,
1329                     unsafety: hir::Unsafety,
1330                     abi: abi::Abi,
1331                     decl: &hir::FnDecl)
1332                     -> &'tcx ty::BareFnTy<'tcx> {
1333         debug!("ty_of_fn");
1334
1335         let input_tys: Vec<Ty> =
1336             decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1337
1338         let output_ty = match decl.output {
1339             hir::Return(ref output) => self.ast_ty_to_ty(output),
1340             hir::DefaultReturn(..) => self.tcx().mk_nil(),
1341         };
1342
1343         debug!("ty_of_fn: output_ty={:?}", output_ty);
1344
1345         self.tcx().mk_bare_fn(ty::BareFnTy {
1346             unsafety: unsafety,
1347             abi: abi,
1348             sig: ty::Binder(self.tcx().mk_fn_sig(
1349                 input_tys.into_iter(),
1350                 output_ty,
1351                 decl.variadic
1352             )),
1353         })
1354     }
1355
1356     pub fn ty_of_closure(&self,
1357         unsafety: hir::Unsafety,
1358         decl: &hir::FnDecl,
1359         abi: abi::Abi,
1360         expected_sig: Option<ty::FnSig<'tcx>>)
1361         -> ty::ClosureTy<'tcx>
1362     {
1363         debug!("ty_of_closure(expected_sig={:?})",
1364                expected_sig);
1365
1366         let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1367             let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1368                 // no guarantee that the correct number of expected args
1369                 // were supplied
1370                 if i < e.inputs().len() {
1371                     Some(e.inputs()[i])
1372                 } else {
1373                     None
1374                 }
1375             });
1376             self.ty_of_arg(a, expected_arg_ty)
1377         });
1378
1379         let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1380
1381         let is_infer = match decl.output {
1382             hir::Return(ref output) if output.node == hir::TyInfer => true,
1383             hir::DefaultReturn(..) => true,
1384             _ => false
1385         };
1386
1387         let output_ty = match decl.output {
1388             _ if is_infer && expected_ret_ty.is_some() =>
1389                 expected_ret_ty.unwrap(),
1390             _ if is_infer => self.ty_infer(decl.output.span()),
1391             hir::Return(ref output) =>
1392                 self.ast_ty_to_ty(&output),
1393             hir::DefaultReturn(..) => bug!(),
1394         };
1395
1396         debug!("ty_of_closure: output_ty={:?}", output_ty);
1397
1398         ty::ClosureTy {
1399             unsafety: unsafety,
1400             abi: abi,
1401             sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1402         }
1403     }
1404
1405     /// Given the bounds on an object, determines what single region bound (if any) we can
1406     /// use to summarize this type. The basic idea is that we will use the bound the user
1407     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1408     /// for region bounds. It may be that we can derive no bound at all, in which case
1409     /// we return `None`.
1410     fn compute_object_lifetime_bound(&self,
1411         span: Span,
1412         existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1413         -> Option<&'tcx ty::Region> // if None, use the default
1414     {
1415         let tcx = self.tcx();
1416
1417         debug!("compute_opt_region_bound(existential_predicates={:?})",
1418                existential_predicates);
1419
1420         if let Some(principal) = existential_predicates.principal() {
1421             if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1422                 return Some(tcx.mk_region(ty::ReStatic));
1423             }
1424         }
1425
1426         // No explicit region bound specified. Therefore, examine trait
1427         // bounds and see if we can derive region bounds from those.
1428         let derived_region_bounds =
1429             object_region_bounds(tcx, existential_predicates);
1430
1431         // If there are no derived region bounds, then report back that we
1432         // can find no region bound. The caller will use the default.
1433         if derived_region_bounds.is_empty() {
1434             return None;
1435         }
1436
1437         // If any of the derived region bounds are 'static, that is always
1438         // the best choice.
1439         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1440             return Some(tcx.mk_region(ty::ReStatic));
1441         }
1442
1443         // Determine whether there is exactly one unique region in the set
1444         // of derived region bounds. If so, use that. Otherwise, report an
1445         // error.
1446         let r = derived_region_bounds[0];
1447         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1448             span_err!(tcx.sess, span, E0227,
1449                       "ambiguous lifetime bound, explicit lifetime bound required");
1450         }
1451         return Some(r);
1452     }
1453 }
1454
1455 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1456 /// remaining general trait bounds.
1457 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1458                                          trait_bounds: &'b [hir::PolyTraitRef])
1459     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1460 {
1461     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1462         match bound.trait_ref.path.def {
1463             Def::Trait(trait_did) => {
1464                 // Checks whether `trait_did` refers to one of the builtin
1465                 // traits, like `Send`, and adds it to `auto_traits` if so.
1466                 if Some(trait_did) == tcx.lang_items.send_trait() ||
1467                     Some(trait_did) == tcx.lang_items.sync_trait() {
1468                     let segments = &bound.trait_ref.path.segments;
1469                     let parameters = &segments[segments.len() - 1].parameters;
1470                     if !parameters.types().is_empty() {
1471                         check_type_argument_count(tcx, bound.trait_ref.path.span,
1472                                                   parameters.types().len(), &[]);
1473                     }
1474                     if !parameters.lifetimes().is_empty() {
1475                         report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1476                                                      parameters.lifetimes().len(), 0);
1477                     }
1478                     true
1479                 } else {
1480                     false
1481                 }
1482             }
1483             _ => false
1484         }
1485     });
1486
1487     let auto_traits = auto_traits.into_iter().map(|tr| {
1488         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1489             trait_did
1490         } else {
1491             unreachable!()
1492         }
1493     }).collect::<Vec<_>>();
1494
1495     (auto_traits, trait_bounds)
1496 }
1497
1498 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1499                              ty_param_defs: &[ty::TypeParameterDef]) {
1500     let accepted = ty_param_defs.len();
1501     let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
1502     if supplied < required {
1503         let expected = if required < accepted {
1504             "expected at least"
1505         } else {
1506             "expected"
1507         };
1508         let arguments_plural = if required == 1 { "" } else { "s" };
1509
1510         struct_span_err!(tcx.sess, span, E0243,
1511                 "wrong number of type arguments: {} {}, found {}",
1512                 expected, required, supplied)
1513             .span_label(span,
1514                 &format!("{} {} type argument{}",
1515                     expected,
1516                     required,
1517                     arguments_plural))
1518             .emit();
1519     } else if supplied > accepted {
1520         let expected = if required < accepted {
1521             format!("expected at most {}", accepted)
1522         } else {
1523             format!("expected {}", accepted)
1524         };
1525         let arguments_plural = if accepted == 1 { "" } else { "s" };
1526
1527         struct_span_err!(tcx.sess, span, E0244,
1528                 "wrong number of type arguments: {}, found {}",
1529                 expected, supplied)
1530             .span_label(
1531                 span,
1532                 &format!("{} type argument{}",
1533                     if accepted == 0 { "expected no" } else { &expected },
1534                     arguments_plural)
1535             )
1536             .emit();
1537     }
1538 }
1539
1540 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1541     let label = if number < expected {
1542         if expected == 1 {
1543             format!("expected {} lifetime parameter", expected)
1544         } else {
1545             format!("expected {} lifetime parameters", expected)
1546         }
1547     } else {
1548         let additional = number - expected;
1549         if additional == 1 {
1550             "unexpected lifetime parameter".to_string()
1551         } else {
1552             format!("{} unexpected lifetime parameters", additional)
1553         }
1554     };
1555     struct_span_err!(tcx.sess, span, E0107,
1556                      "wrong number of lifetime parameters: expected {}, found {}",
1557                      expected, number)
1558         .span_label(span, &label)
1559         .emit();
1560 }
1561
1562 // A helper struct for conveniently grouping a set of bounds which we pass to
1563 // and return from functions in multiple places.
1564 #[derive(PartialEq, Eq, Clone, Debug)]
1565 pub struct Bounds<'tcx> {
1566     pub region_bounds: Vec<&'tcx ty::Region>,
1567     pub implicitly_sized: bool,
1568     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1569     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1570 }
1571
1572 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1573     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1574                       -> Vec<ty::Predicate<'tcx>>
1575     {
1576         let mut vec = Vec::new();
1577
1578         // If it could be sized, and is, add the sized predicate
1579         if self.implicitly_sized {
1580             if let Some(sized) = tcx.lang_items.sized_trait() {
1581                 let trait_ref = ty::TraitRef {
1582                     def_id: sized,
1583                     substs: tcx.mk_substs_trait(param_ty, &[])
1584                 };
1585                 vec.push(trait_ref.to_predicate());
1586             }
1587         }
1588
1589         for &region_bound in &self.region_bounds {
1590             // account for the binder being introduced below; no need to shift `param_ty`
1591             // because, at present at least, it can only refer to early-bound regions
1592             let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1593             vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1594         }
1595
1596         for bound_trait_ref in &self.trait_bounds {
1597             vec.push(bound_trait_ref.to_predicate());
1598         }
1599
1600         for projection in &self.projection_bounds {
1601             vec.push(projection.to_predicate());
1602         }
1603
1604         vec
1605     }
1606 }
1607
1608 pub enum ExplicitSelf<'tcx> {
1609     ByValue,
1610     ByReference(&'tcx ty::Region, hir::Mutability),
1611     ByBox
1612 }
1613
1614 impl<'tcx> ExplicitSelf<'tcx> {
1615     /// We wish to (for now) categorize an explicit self
1616     /// declaration like `self: SomeType` into either `self`,
1617     /// `&self`, `&mut self`, or `Box<self>`. We do this here
1618     /// by some simple pattern matching. A more precise check
1619     /// is done later in `check_method_self_type()`.
1620     ///
1621     /// Examples:
1622     ///
1623     /// ```
1624     /// impl Foo for &T {
1625     ///     // Legal declarations:
1626     ///     fn method1(self: &&T); // ExplicitSelf::ByReference
1627     ///     fn method2(self: &T); // ExplicitSelf::ByValue
1628     ///     fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1629     ///
1630     ///     // Invalid cases will be caught later by `check_method_self_type`:
1631     ///     fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1632     /// }
1633     /// ```
1634     ///
1635     /// To do the check we just count the number of "modifiers"
1636     /// on each type and compare them. If they are the same or
1637     /// the impl has more, we call it "by value". Otherwise, we
1638     /// look at the outermost modifier on the method decl and
1639     /// call it by-ref, by-box as appropriate. For method1, for
1640     /// example, the impl type has one modifier, but the method
1641     /// type has two, so we end up with
1642     /// ExplicitSelf::ByReference.
1643     pub fn determine(untransformed_self_ty: Ty<'tcx>,
1644                      self_arg_ty: Ty<'tcx>)
1645                      -> ExplicitSelf<'tcx> {
1646         fn count_modifiers(ty: Ty) -> usize {
1647             match ty.sty {
1648                 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1649                 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1650                 _ => 0,
1651             }
1652         }
1653
1654         let impl_modifiers = count_modifiers(untransformed_self_ty);
1655         let method_modifiers = count_modifiers(self_arg_ty);
1656
1657         if impl_modifiers >= method_modifiers {
1658             ExplicitSelf::ByValue
1659         } else {
1660             match self_arg_ty.sty {
1661                 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1662                 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1663                 _ => ExplicitSelf::ByValue,
1664             }
1665         }
1666     }
1667 }