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