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