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