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