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