]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
rustc: always include elidable lifetimes in HIR types.
[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` and a `RegionScope`.
14 //!
15 //! The parameterization of `ast_ty_to_ty()` is because it behaves
16 //! somewhat differently during the collect and check phases,
17 //! particularly with respect to looking up the types of top-level
18 //! items.  In the collect phase, the crate context is used as the
19 //! `AstConv` instance; in this phase, the `get_item_type()`
20 //! function triggers a recursive call to `type_of_item()`
21 //! (note that `ast_ty_to_ty()` will detect recursive types and report
22 //! an error).  In the check phase, when the FnCtxt is used as the
23 //! `AstConv`, `get_item_type()` just looks up the item type in
24 //! `tcx.types` (using `TyCtxt::item_type`).
25 //!
26 //! The `RegionScope` trait controls what happens when the user does
27 //! not specify a region in some location where a region is required
28 //! (e.g., if the user writes `&Foo` as a type rather than `&'a Foo`).
29 //! See the `rscope` module for more details.
30 //!
31 //! Unlike the `AstConv` trait, the region scope can change as we descend
32 //! the type.  This is to accommodate the fact that (a) fn types are binding
33 //! scopes and (b) the default region may change.  To understand case (a),
34 //! consider something like:
35 //!
36 //!   type foo = { x: &a.int, y: |&a.int| }
37 //!
38 //! The type of `x` is an error because there is no region `a` in scope.
39 //! In the type of `y`, however, region `a` is considered a bound region
40 //! as it does not already appear in scope.
41 //!
42 //! Case (b) says that if you have a type:
43 //!   type foo<'a> = ...;
44 //!   type bar = fn(&foo, &a.foo)
45 //! The fully expanded version of type bar is:
46 //!   type bar = fn(&'foo &, &a.foo<'a>)
47 //! Note that the self region for the `foo` defaulted to `&` in the first
48 //! case but `&a` in the second.  Basically, defaults that appear inside
49 //! an rptr (`&r.T`) use the region `r` that appears in the rptr.
50
51 use rustc_const_eval::eval_length;
52 use rustc_data_structures::accumulate_vec::AccumulateVec;
53 use hir;
54 use hir::def::Def;
55 use hir::def_id::DefId;
56 use middle::resolve_lifetime as rl;
57 use rustc::lint;
58 use rustc::ty::subst::{Kind, Subst, Substs};
59 use rustc::traits;
60 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
61 use rustc::ty::wf::object_region_bounds;
62 use rustc_back::slice;
63 use require_c_abi_if_variadic;
64 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
65              ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
66              ElisionFailureInfo, ElidedLifetime};
67 use rscope::{AnonTypeScope, MaybeWithAnonTypes, ExplicitRscope};
68 use util::common::{ErrorReported, FN_OUTPUT_NAME};
69 use util::nodemap::{NodeMap, FxHashSet};
70
71 use std::cell::RefCell;
72 use std::iter;
73 use syntax::{abi, ast};
74 use syntax::feature_gate::{GateIssue, emit_feature_err};
75 use syntax::symbol::{Symbol, keywords};
76 use syntax_pos::Span;
77 use errors::DiagnosticBuilder;
78
79 pub trait AstConv<'gcx, 'tcx> {
80     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
81
82     /// A cache used for the result of `ast_ty_to_ty_cache`
83     fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
84
85     /// Returns the generic type and lifetime parameters for an item.
86     fn get_generics(&self, span: Span, id: DefId)
87                     -> Result<&'tcx ty::Generics<'tcx>, ErrorReported>;
88
89     /// Identify the type for an item, like a type alias, fn, or struct.
90     fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported>;
91
92     /// Returns the `TraitDef` for a given trait. This allows you to
93     /// figure out the set of type parameters defined on the trait.
94     fn get_trait_def(&self, span: Span, id: DefId)
95                      -> Result<&'tcx ty::TraitDef, ErrorReported>;
96
97     /// Ensure that the super-predicates for the trait with the given
98     /// id are available and also for the transitive set of
99     /// super-predicates.
100     fn ensure_super_predicates(&self, span: Span, id: DefId)
101                                -> Result<(), ErrorReported>;
102
103     /// Returns the set of bounds in scope for the type parameter with
104     /// the given id.
105     fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
106                                  -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
107
108     /// Return an (optional) substitution to convert bound type parameters that
109     /// are in scope into free ones. This function should only return Some
110     /// within a fn body.
111     /// See ParameterEnvironment::free_substs for more information.
112     fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
113
114     /// What type should we use when a type is omitted?
115     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
116
117     /// Same as ty_infer, but with a known type parameter definition.
118     fn ty_infer_for_def(&self,
119                         _def: &ty::TypeParameterDef<'tcx>,
120                         _substs: &[Kind<'tcx>],
121                         span: Span) -> Ty<'tcx> {
122         self.ty_infer(span)
123     }
124
125     /// Projecting an associated type from a (potentially)
126     /// higher-ranked trait reference is more complicated, because of
127     /// the possibility of late-bound regions appearing in the
128     /// associated type binding. This is not legal in function
129     /// signatures for that reason. In a function body, we can always
130     /// handle it because we can use inference variables to remove the
131     /// late-bound regions.
132     fn projected_ty_from_poly_trait_ref(&self,
133                                         span: Span,
134                                         poly_trait_ref: ty::PolyTraitRef<'tcx>,
135                                         item_name: ast::Name)
136                                         -> Ty<'tcx>;
137
138     /// Project an associated type from a non-higher-ranked trait reference.
139     /// This is fairly straightforward and can be accommodated in any context.
140     fn projected_ty(&self,
141                     span: Span,
142                     _trait_ref: ty::TraitRef<'tcx>,
143                     _item_name: ast::Name)
144                     -> Ty<'tcx>;
145
146     /// Invoked when we encounter an error from some prior pass
147     /// (e.g. resolve) that is translated into a ty-error. This is
148     /// used to help suppress derived errors typeck might otherwise
149     /// report.
150     fn set_tainted_by_errors(&self);
151 }
152
153 struct ConvertedBinding<'tcx> {
154     item_name: ast::Name,
155     ty: Ty<'tcx>,
156     span: Span,
157 }
158
159 /// Dummy type used for the `Self` of a `TraitRef` created for converting
160 /// a trait object, and which gets removed in `ExistentialTraitRef`.
161 /// This type must not appear anywhere in other converted types.
162 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
163
164 fn report_elision_failure(
165     tcx: TyCtxt,
166     db: &mut DiagnosticBuilder,
167     params: Vec<ElisionFailureInfo>)
168 {
169     let mut m = String::new();
170     let len = params.len();
171
172     let elided_params: Vec<_> = params.into_iter()
173                                        .filter(|info| info.lifetime_count > 0)
174                                        .collect();
175
176     let elided_len = elided_params.len();
177
178     for (i, info) in elided_params.into_iter().enumerate() {
179         let ElisionFailureInfo {
180             parent, index, lifetime_count: n, have_bound_regions
181         } = info;
182
183         let help_name = if let Some(body) = parent {
184             let arg = &tcx.hir.body(body).arguments[index];
185             format!("`{}`", tcx.hir.node_to_pretty_string(arg.pat.id))
186         } else {
187             format!("argument {}", index + 1)
188         };
189
190         m.push_str(&(if n == 1 {
191             help_name
192         } else {
193             format!("one of {}'s {} elided {}lifetimes", help_name, n,
194                     if have_bound_regions { "free " } else { "" } )
195         })[..]);
196
197         if elided_len == 2 && i == 0 {
198             m.push_str(" or ");
199         } else if i + 2 == elided_len {
200             m.push_str(", or ");
201         } else if i != elided_len - 1 {
202             m.push_str(", ");
203         }
204
205     }
206
207     if len == 0 {
208         help!(db,
209                    "this function's return type contains a borrowed value, but \
210                     there is no value for it to be borrowed from");
211         help!(db,
212                    "consider giving it a 'static lifetime");
213     } else if elided_len == 0 {
214         help!(db,
215                    "this function's return type contains a borrowed value with \
216                     an elided lifetime, but the lifetime cannot be derived from \
217                     the arguments");
218         help!(db,
219                    "consider giving it an explicit bounded or 'static \
220                     lifetime");
221     } else if elided_len == 1 {
222         help!(db,
223                    "this function's return type contains a borrowed value, but \
224                     the signature does not say which {} it is borrowed from",
225                    m);
226     } else {
227         help!(db,
228                    "this function's return type contains a borrowed value, but \
229                     the signature does not say whether it is borrowed from {}",
230                    m);
231     }
232 }
233
234 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
235     pub fn ast_region_to_region(&self, lifetime: &hir::Lifetime) -> &'tcx ty::Region {
236         self.opt_ast_region_to_region(&ExplicitRscope, lifetime.span, Some(lifetime), None)
237     }
238
239     fn try_opt_ast_region_to_region(&self,
240         rscope: &RegionScope,
241         default_span: Span,
242         opt_lifetime: Option<&hir::Lifetime>,
243         def: Option<&ty::RegionParameterDef>)
244         -> Result<&'tcx ty::Region, Option<Vec<ElisionFailureInfo>>>
245     {
246         let tcx = self.tcx();
247         let name = opt_lifetime.map(|l| l.name);
248         let resolved = opt_lifetime.and_then(|l| tcx.named_region_map.defs.get(&l.id));
249         let r = tcx.mk_region(match resolved {
250             Some(&rl::DefStaticRegion) => {
251                 ty::ReStatic
252             }
253
254             Some(&rl::DefLateBoundRegion(debruijn, id)) => {
255                 // If this region is declared on a function, it will have
256                 // an entry in `late_bound`, but if it comes from
257                 // `for<'a>` in some type or something, it won't
258                 // necessarily have one. In that case though, we won't be
259                 // changed from late to early bound, so we can just
260                 // substitute false.
261                 let issue_32330 = tcx.named_region_map
262                                      .late_bound
263                                      .get(&id)
264                                      .cloned()
265                                      .unwrap_or(ty::Issue32330::WontChange);
266                 ty::ReLateBound(debruijn, ty::BrNamed(tcx.hir.local_def_id(id),
267                                                       name.unwrap(),
268                                                       issue_32330))
269             }
270
271             Some(&rl::DefEarlyBoundRegion(index, _)) => {
272                 ty::ReEarlyBound(ty::EarlyBoundRegion {
273                     index: index,
274                     name: name.unwrap()
275                 })
276             }
277
278             Some(&rl::DefFreeRegion(scope, id)) => {
279                 // As in DefLateBoundRegion above, could be missing for some late-bound
280                 // regions, but also for early-bound regions.
281                 let issue_32330 = tcx.named_region_map
282                                      .late_bound
283                                      .get(&id)
284                                      .cloned()
285                                      .unwrap_or(ty::Issue32330::WontChange);
286                 ty::ReFree(ty::FreeRegion {
287                         scope: scope.to_code_extent(&tcx.region_maps),
288                         bound_region: ty::BrNamed(tcx.hir.local_def_id(id),
289                                                   name.unwrap(),
290                                                   issue_32330)
291                 })
292
293                     // (*) -- not late-bound, won't change
294             }
295
296             None => rscope.anon_region(default_span, def)?
297         });
298
299         debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
300                 opt_lifetime,
301                 r);
302
303         Ok(r)
304     }
305
306     pub fn opt_ast_region_to_region(&self,
307         rscope: &RegionScope,
308         default_span: Span,
309         opt_lifetime: Option<&hir::Lifetime>,
310         def: Option<&ty::RegionParameterDef>) -> &'tcx ty::Region
311     {
312         let tcx = self.tcx();
313         self.try_opt_ast_region_to_region(rscope, default_span, opt_lifetime, def)
314             .unwrap_or_else(|params| {
315                 let ampersand_span = Span { hi: default_span.lo, ..default_span};
316
317                 let mut err = struct_span_err!(tcx.sess, ampersand_span, E0106,
318                                                "missing lifetime specifier");
319                 err.span_label(ampersand_span, &format!("expected lifetime parameter"));
320
321                 if let Some(params) = params {
322                     report_elision_failure(tcx, &mut err, params);
323                 }
324                 err.emit();
325                 tcx.mk_region(ty::ReStatic)
326             })
327     }
328
329     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
330     /// returns an appropriate set of substitutions for this particular reference to `I`.
331     pub fn ast_path_substs_for_ty(&self,
332         rscope: &RegionScope,
333         span: Span,
334         def_id: DefId,
335         item_segment: &hir::PathSegment)
336         -> &'tcx Substs<'tcx>
337     {
338         let tcx = self.tcx();
339
340         match item_segment.parameters {
341             hir::AngleBracketedParameters(_) => {}
342             hir::ParenthesizedParameters(..) => {
343                 struct_span_err!(tcx.sess, span, E0214,
344                           "parenthesized parameters may only be used with a trait")
345                     .span_label(span, &format!("only traits may use parentheses"))
346                     .emit();
347
348                 return Substs::for_item(tcx, def_id, |_, _| {
349                     tcx.mk_region(ty::ReStatic)
350                 }, |_, _| {
351                     tcx.types.err
352                 });
353             }
354         }
355
356         let (substs, assoc_bindings) =
357             self.create_substs_for_ast_path(rscope,
358                                             span,
359                                             def_id,
360                                             &item_segment.parameters,
361                                             None);
362
363         assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
364
365         substs
366     }
367
368     /// Given the type/region arguments provided to some path (along with
369     /// an implicit Self, if this is a trait reference) returns the complete
370     /// set of substitutions. This may involve applying defaulted type parameters.
371     ///
372     /// Note that the type listing given here is *exactly* what the user provided.
373     fn create_substs_for_ast_path(&self,
374         rscope: &RegionScope,
375         span: Span,
376         def_id: DefId,
377         parameters: &hir::PathParameters,
378         self_ty: Option<Ty<'tcx>>)
379         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
380     {
381         let tcx = self.tcx();
382
383         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
384                parameters={:?})",
385                def_id, self_ty, parameters);
386
387         let (lifetimes, num_types_provided, infer_types) = match *parameters {
388             hir::AngleBracketedParameters(ref data) => {
389                 (&data.lifetimes[..], data.types.len(), data.infer_types)
390             }
391             hir::ParenthesizedParameters(_) => (&[][..], 1, false)
392         };
393
394         // If the type is parameterized by this region, then replace this
395         // region with the current anon region binding (in other words,
396         // whatever & would get replaced with).
397         let decl_generics = match self.get_generics(span, def_id) {
398             Ok(generics) => generics,
399             Err(ErrorReported) => {
400                 // No convenient way to recover from a cycle here. Just bail. Sorry!
401                 self.tcx().sess.abort_if_errors();
402                 bug!("ErrorReported returned, but no errors reports?")
403             }
404         };
405         let expected_num_region_params = decl_generics.regions.len();
406         let supplied_num_region_params = lifetimes.len();
407         let mut reported_lifetime_count_mismatch = false;
408         let mut report_lifetime_count_mismatch = || {
409             if !reported_lifetime_count_mismatch {
410                 reported_lifetime_count_mismatch = true;
411                 let all_infer = lifetimes.iter().all(|lt| lt.is_elided());
412                 let supplied = if all_infer { 0 } else { supplied_num_region_params };
413                 report_lifetime_number_error(tcx, span,
414                                              supplied,
415                                              expected_num_region_params);
416             }
417         };
418
419         if expected_num_region_params != supplied_num_region_params {
420             report_lifetime_count_mismatch();
421         }
422
423         // If a self-type was declared, one should be provided.
424         assert_eq!(decl_generics.has_self, self_ty.is_some());
425
426         // Check the number of type parameters supplied by the user.
427         let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
428         if !infer_types || num_types_provided > ty_param_defs.len() {
429             check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
430         }
431
432         let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
433         let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
434             if let Some(ref default) = p.default {
435                 if is_object && default.has_self_ty() {
436                     // There is no suitable inference default for a type parameter
437                     // that references self, in an object type.
438                     return true;
439                 }
440             }
441
442             false
443         };
444
445         let mut output_assoc_binding = None;
446         let substs = Substs::for_item(tcx, def_id, |def, _| {
447             let i = def.index as usize - self_ty.is_some() as usize;
448             let l = lifetimes.get(i);
449             self.try_opt_ast_region_to_region(rscope, span, l, Some(def)).unwrap_or_else(|_| {
450                 report_lifetime_count_mismatch();
451                 tcx.mk_region(ty::ReStatic)
452             })
453         }, |def, substs| {
454             let i = def.index as usize;
455
456             // Handle Self first, so we can adjust the index to match the AST.
457             if let (0, Some(ty)) = (i, self_ty) {
458                 return ty;
459             }
460
461             let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
462             if i < num_types_provided {
463                 // A provided type parameter.
464                 match *parameters {
465                     hir::AngleBracketedParameters(ref data) => {
466                         self.ast_ty_arg_to_ty(rscope, Some(def), substs, &data.types[i])
467                     }
468                     hir::ParenthesizedParameters(ref data) => {
469                         assert_eq!(i, 0);
470                         let (ty, assoc) =
471                             self.convert_parenthesized_parameters(rscope, substs, data);
472                         output_assoc_binding = Some(assoc);
473                         ty
474                     }
475                 }
476             } else if infer_types {
477                 // No type parameters were provided, we can infer all.
478                 let ty_var = if !default_needs_object_self(def) {
479                     self.ty_infer_for_def(def, substs, span)
480                 } else {
481                     self.ty_infer(span)
482                 };
483                 ty_var
484             } else if let Some(default) = def.default {
485                 // No type parameter provided, but a default exists.
486
487                 // If we are converting an object type, then the
488                 // `Self` parameter is unknown. However, some of the
489                 // other type parameters may reference `Self` in their
490                 // defaults. This will lead to an ICE if we are not
491                 // careful!
492                 if default_needs_object_self(def) {
493                     struct_span_err!(tcx.sess, span, E0393,
494                                      "the type parameter `{}` must be explicitly specified",
495                                      def.name)
496                         .span_label(span, &format!("missing reference to `{}`", def.name))
497                         .note(&format!("because of the default `Self` reference, \
498                                         type parameters must be specified on object types"))
499                         .emit();
500                     tcx.types.err
501                 } else {
502                     // This is a default type parameter.
503                     default.subst_spanned(tcx, substs, Some(span))
504                 }
505             } else {
506                 // We've already errored above about the mismatch.
507                 tcx.types.err
508             }
509         });
510
511         let assoc_bindings = match *parameters {
512             hir::AngleBracketedParameters(ref data) => {
513                 data.bindings.iter().map(|b| {
514                     ConvertedBinding {
515                         item_name: b.name,
516                         ty: self.ast_ty_to_ty(rscope, &b.ty),
517                         span: b.span
518                     }
519                 }).collect()
520             }
521             hir::ParenthesizedParameters(ref data) => {
522                 vec![output_assoc_binding.unwrap_or_else(|| {
523                     // This is an error condition, but we should
524                     // get the associated type binding anyway.
525                     self.convert_parenthesized_parameters(rscope, substs, data).1
526                 })]
527             }
528         };
529
530         debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
531                decl_generics, self_ty, substs);
532
533         (substs, assoc_bindings)
534     }
535
536     /// Returns the appropriate lifetime to use for any output lifetimes
537     /// (if one exists) and a vector of the (pattern, number of lifetimes)
538     /// corresponding to each input type/pattern.
539     fn find_implied_output_region<I>(&self,
540                                      input_tys: &[Ty<'tcx>],
541                                      parent: Option<hir::BodyId>,
542                                      input_indices: I) -> ElidedLifetime
543         where I: Iterator<Item=usize>
544     {
545         let tcx = self.tcx();
546         let mut lifetimes_for_params = Vec::with_capacity(input_tys.len());
547         let mut possible_implied_output_region = None;
548         let mut lifetimes = 0;
549
550         for (input_type, index) in input_tys.iter().zip(input_indices) {
551             let mut regions = FxHashSet();
552             let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
553
554             debug!("find_implied_output_regions: collected {:?} from {:?} \
555                     have_bound_regions={:?}", &regions, input_type, have_bound_regions);
556
557             lifetimes += regions.len();
558
559             if lifetimes == 1 && regions.len() == 1 {
560                 // there's a chance that the unique lifetime of this
561                 // iteration will be the appropriate lifetime for output
562                 // parameters, so lets store it.
563                 possible_implied_output_region = regions.iter().cloned().next();
564             }
565
566             lifetimes_for_params.push(ElisionFailureInfo {
567                 parent: parent,
568                 index: index,
569                 lifetime_count: regions.len(),
570                 have_bound_regions: have_bound_regions
571             });
572         }
573
574         if lifetimes == 1 {
575             Ok(*possible_implied_output_region.unwrap())
576         } else {
577             Err(Some(lifetimes_for_params))
578         }
579     }
580
581     fn convert_ty_with_lifetime_elision(&self,
582                                         elided_lifetime: ElidedLifetime,
583                                         ty: &hir::Ty,
584                                         anon_scope: Option<AnonTypeScope>)
585                                         -> Ty<'tcx>
586     {
587         match elided_lifetime {
588             Ok(implied_output_region) => {
589                 let rb = ElidableRscope::new(implied_output_region);
590                 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
591             }
592             Err(param_lifetimes) => {
593                 // All regions must be explicitly specified in the output
594                 // if the lifetime elision rules do not apply. This saves
595                 // the user from potentially-confusing errors.
596                 let rb = UnelidableRscope::new(param_lifetimes);
597                 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
598             }
599         }
600     }
601
602     fn convert_parenthesized_parameters(&self,
603                                         rscope: &RegionScope,
604                                         region_substs: &[Kind<'tcx>],
605                                         data: &hir::ParenthesizedParameterData)
606                                         -> (Ty<'tcx>, ConvertedBinding<'tcx>)
607     {
608         let anon_scope = rscope.anon_type_scope();
609         let binding_rscope = MaybeWithAnonTypes::new(BindingRscope::new(), anon_scope);
610         let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
611             self.ast_ty_arg_to_ty(&binding_rscope, None, region_substs, a_t)
612         }));
613         let input_params = 0..inputs.len();
614         let implied_output_region = self.find_implied_output_region(&inputs, None, input_params);
615
616         let (output, output_span) = match data.output {
617             Some(ref output_ty) => {
618                 (self.convert_ty_with_lifetime_elision(implied_output_region,
619                                                        &output_ty,
620                                                        anon_scope),
621                  output_ty.span)
622             }
623             None => {
624                 (self.tcx().mk_nil(), data.span)
625             }
626         };
627
628         let output_binding = ConvertedBinding {
629             item_name: Symbol::intern(FN_OUTPUT_NAME),
630             ty: output,
631             span: output_span
632         };
633
634         (self.tcx().mk_ty(ty::TyTuple(inputs)), output_binding)
635     }
636
637     pub fn instantiate_poly_trait_ref(&self,
638         rscope: &RegionScope,
639         ast_trait_ref: &hir::PolyTraitRef,
640         self_ty: Ty<'tcx>,
641         poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
642         -> ty::PolyTraitRef<'tcx>
643     {
644         let trait_ref = &ast_trait_ref.trait_ref;
645         let trait_def_id = self.trait_def_id(trait_ref);
646         self.ast_path_to_poly_trait_ref(rscope,
647                                         trait_ref.path.span,
648                                         trait_def_id,
649                                         self_ty,
650                                         trait_ref.ref_id,
651                                         trait_ref.path.segments.last().unwrap(),
652                                         poly_projections)
653     }
654
655     /// Instantiates the path for the given trait reference, assuming that it's
656     /// bound to a valid trait type. Returns the def_id for the defining trait.
657     /// Fails if the type is a type other than a trait type.
658     ///
659     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
660     /// are disallowed. Otherwise, they are pushed onto the vector given.
661     pub fn instantiate_mono_trait_ref(&self,
662         rscope: &RegionScope,
663         trait_ref: &hir::TraitRef,
664         self_ty: Ty<'tcx>)
665         -> ty::TraitRef<'tcx>
666     {
667         let trait_def_id = self.trait_def_id(trait_ref);
668         self.ast_path_to_mono_trait_ref(rscope,
669                                         trait_ref.path.span,
670                                         trait_def_id,
671                                         self_ty,
672                                         trait_ref.path.segments.last().unwrap())
673     }
674
675     fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
676         let path = &trait_ref.path;
677         match path.def {
678             Def::Trait(trait_def_id) => trait_def_id,
679             Def::Err => {
680                 self.tcx().sess.fatal("cannot continue compilation due to previous error");
681             }
682             _ => {
683                 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
684                             self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
685             }
686         }
687     }
688
689     fn ast_path_to_poly_trait_ref(&self,
690         rscope: &RegionScope,
691         span: Span,
692         trait_def_id: DefId,
693         self_ty: Ty<'tcx>,
694         path_id: ast::NodeId,
695         trait_segment: &hir::PathSegment,
696         poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
697         -> ty::PolyTraitRef<'tcx>
698     {
699         debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
700         // The trait reference introduces a binding level here, so
701         // we need to shift the `rscope`. It'd be nice if we could
702         // do away with this rscope stuff and work this knowledge
703         // into resolve_lifetimes, as we do with non-omitted
704         // lifetimes. Oh well, not there yet.
705         let shifted_rscope = &ShiftedRscope::new(rscope);
706
707         let (substs, assoc_bindings) =
708             self.create_substs_for_ast_trait_ref(shifted_rscope,
709                                                  span,
710                                                  trait_def_id,
711                                                  self_ty,
712                                                  trait_segment);
713         let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
714
715         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
716             // specify type to assert that error was already reported in Err case:
717             let predicate: Result<_, ErrorReported> =
718                 self.ast_type_binding_to_poly_projection_predicate(path_id,
719                                                                    poly_trait_ref,
720                                                                    binding);
721             predicate.ok() // ok to ignore Err() because ErrorReported (see above)
722         }));
723
724         debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
725                trait_segment, poly_projections, poly_trait_ref);
726         poly_trait_ref
727     }
728
729     fn ast_path_to_mono_trait_ref(&self,
730                                   rscope: &RegionScope,
731                                   span: Span,
732                                   trait_def_id: DefId,
733                                   self_ty: Ty<'tcx>,
734                                   trait_segment: &hir::PathSegment)
735                                   -> ty::TraitRef<'tcx>
736     {
737         let (substs, assoc_bindings) =
738             self.create_substs_for_ast_trait_ref(rscope,
739                                                  span,
740                                                  trait_def_id,
741                                                  self_ty,
742                                                  trait_segment);
743         assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
744         ty::TraitRef::new(trait_def_id, substs)
745     }
746
747     fn create_substs_for_ast_trait_ref(&self,
748                                        rscope: &RegionScope,
749                                        span: Span,
750                                        trait_def_id: DefId,
751                                        self_ty: Ty<'tcx>,
752                                        trait_segment: &hir::PathSegment)
753                                        -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
754     {
755         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
756                trait_segment);
757
758         let trait_def = match self.get_trait_def(span, trait_def_id) {
759             Ok(trait_def) => trait_def,
760             Err(ErrorReported) => {
761                 // No convenient way to recover from a cycle here. Just bail. Sorry!
762                 self.tcx().sess.abort_if_errors();
763                 bug!("ErrorReported returned, but no errors reports?")
764             }
765         };
766
767         match trait_segment.parameters {
768             hir::AngleBracketedParameters(_) => {
769                 // For now, require that parenthetical notation be used
770                 // only with `Fn()` etc.
771                 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
772                     emit_feature_err(&self.tcx().sess.parse_sess,
773                                      "unboxed_closures", span, GateIssue::Language,
774                                      "\
775                         the precise format of `Fn`-family traits' \
776                         type parameters is subject to change. \
777                         Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
778                 }
779             }
780             hir::ParenthesizedParameters(_) => {
781                 // For now, require that parenthetical notation be used
782                 // only with `Fn()` etc.
783                 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
784                     emit_feature_err(&self.tcx().sess.parse_sess,
785                                      "unboxed_closures", span, GateIssue::Language,
786                                      "\
787                         parenthetical notation is only stable when used with `Fn`-family traits");
788                 }
789             }
790         }
791
792         self.create_substs_for_ast_path(rscope,
793                                         span,
794                                         trait_def_id,
795                                         &trait_segment.parameters,
796                                         Some(self_ty))
797     }
798
799     fn trait_defines_associated_type_named(&self,
800                                            trait_def_id: DefId,
801                                            assoc_name: ast::Name)
802                                            -> bool
803     {
804         self.tcx().associated_items(trait_def_id).any(|item| {
805             item.kind == ty::AssociatedKind::Type && item.name == assoc_name
806         })
807     }
808
809     fn ast_type_binding_to_poly_projection_predicate(
810         &self,
811         path_id: ast::NodeId,
812         trait_ref: ty::PolyTraitRef<'tcx>,
813         binding: &ConvertedBinding<'tcx>)
814         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
815     {
816         let tcx = self.tcx();
817
818         // Given something like `U : SomeTrait<T=X>`, we want to produce a
819         // predicate like `<U as SomeTrait>::T = X`. This is somewhat
820         // subtle in the event that `T` is defined in a supertrait of
821         // `SomeTrait`, because in that case we need to upcast.
822         //
823         // That is, consider this case:
824         //
825         // ```
826         // trait SubTrait : SuperTrait<int> { }
827         // trait SuperTrait<A> { type T; }
828         //
829         // ... B : SubTrait<T=foo> ...
830         // ```
831         //
832         // We want to produce `<B as SuperTrait<int>>::T == foo`.
833
834         // Find any late-bound regions declared in `ty` that are not
835         // declared in the trait-ref. These are not wellformed.
836         //
837         // Example:
838         //
839         //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
840         //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
841         let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
842         let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
843         debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
844         debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
845         for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
846             let br_name = match *br {
847                 ty::BrNamed(_, name, _) => name,
848                 _ => {
849                     span_bug!(
850                         binding.span,
851                         "anonymous bound region {:?} in binding but not trait ref",
852                         br);
853                 }
854             };
855             tcx.sess.add_lint(
856                 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
857                 path_id,
858                 binding.span,
859                 format!("binding for associated type `{}` references lifetime `{}`, \
860                          which does not appear in the trait input types",
861                         binding.item_name, br_name));
862         }
863
864         // Simple case: X is defined in the current trait.
865         if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
866             return Ok(trait_ref.map_bound(|trait_ref| {
867                 ty::ProjectionPredicate {
868                     projection_ty: ty::ProjectionTy {
869                         trait_ref: trait_ref,
870                         item_name: binding.item_name,
871                     },
872                     ty: binding.ty,
873                 }
874             }));
875         }
876
877         // Otherwise, we have to walk through the supertraits to find
878         // those that do.
879         self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
880
881         let candidates =
882             traits::supertraits(tcx, trait_ref.clone())
883             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
884
885         let candidate = self.one_bound_for_assoc_type(candidates,
886                                                       &trait_ref.to_string(),
887                                                       &binding.item_name.as_str(),
888                                                       binding.span)?;
889
890         Ok(candidate.map_bound(|trait_ref| {
891             ty::ProjectionPredicate {
892                 projection_ty: ty::ProjectionTy {
893                     trait_ref: trait_ref,
894                     item_name: binding.item_name,
895                 },
896                 ty: binding.ty,
897             }
898         }))
899     }
900
901     fn ast_path_to_ty(&self,
902         rscope: &RegionScope,
903         span: Span,
904         did: DefId,
905         item_segment: &hir::PathSegment)
906         -> Ty<'tcx>
907     {
908         let tcx = self.tcx();
909         let decl_ty = match self.get_item_type(span, did) {
910             Ok(ty) => ty,
911             Err(ErrorReported) => {
912                 return tcx.types.err;
913             }
914         };
915
916         let substs = self.ast_path_substs_for_ty(rscope,
917                                                  span,
918                                                  did,
919                                                  item_segment);
920
921         // FIXME(#12938): This is a hack until we have full support for DST.
922         if Some(did) == self.tcx().lang_items.owned_box() {
923             assert_eq!(substs.types().count(), 1);
924             return self.tcx().mk_box(substs.type_at(0));
925         }
926
927         decl_ty.subst(self.tcx(), substs)
928     }
929
930     /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
931     /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
932     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
933                                 -> ty::ExistentialTraitRef<'tcx> {
934         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
935         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
936     }
937
938     fn trait_path_to_object_type(&self,
939                                  rscope: &RegionScope,
940                                  path_span: Span,
941                                  trait_def_id: DefId,
942                                  trait_path_ref_id: ast::NodeId,
943                                  trait_segment: &hir::PathSegment,
944                                  span: Span,
945                                  partitioned_bounds: PartitionedBounds)
946                                  -> Ty<'tcx> {
947         let tcx = self.tcx();
948
949         let mut projection_bounds = vec![];
950         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
951         let principal = self.ast_path_to_poly_trait_ref(rscope,
952                                                         path_span,
953                                                         trait_def_id,
954                                                         dummy_self,
955                                                         trait_path_ref_id,
956                                                         trait_segment,
957                                                         &mut projection_bounds);
958
959         let PartitionedBounds { trait_bounds,
960                                 region_bounds } =
961             partitioned_bounds;
962
963         let (auto_traits, trait_bounds) = split_auto_traits(tcx, trait_bounds);
964
965         if !trait_bounds.is_empty() {
966             let b = &trait_bounds[0];
967             let span = b.trait_ref.path.span;
968             struct_span_err!(self.tcx().sess, span, E0225,
969                 "only Send/Sync traits can be used as additional traits in a trait object")
970                 .span_label(span, &format!("non-Send/Sync additional trait"))
971                 .emit();
972         }
973
974         // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
975         let existential_principal = principal.map_bound(|trait_ref| {
976             self.trait_ref_to_existential(trait_ref)
977         });
978         let existential_projections = projection_bounds.iter().map(|bound| {
979             bound.map_bound(|b| {
980                 let p = b.projection_ty;
981                 ty::ExistentialProjection {
982                     trait_ref: self.trait_ref_to_existential(p.trait_ref),
983                     item_name: p.item_name,
984                     ty: b.ty
985                 }
986             })
987         });
988
989         // ensure the super predicates and stop if we encountered an error
990         if self.ensure_super_predicates(span, principal.def_id()).is_err() {
991             return tcx.types.err;
992         }
993
994         // check that there are no gross object safety violations,
995         // most importantly, that the supertraits don't contain Self,
996         // to avoid ICE-s.
997         let object_safety_violations =
998             tcx.astconv_object_safety_violations(principal.def_id());
999         if !object_safety_violations.is_empty() {
1000             tcx.report_object_safety_error(
1001                 span, principal.def_id(), object_safety_violations)
1002                 .emit();
1003             return tcx.types.err;
1004         }
1005
1006         let mut associated_types = FxHashSet::default();
1007         for tr in traits::supertraits(tcx, principal) {
1008             associated_types.extend(tcx.associated_items(tr.def_id())
1009                 .filter(|item| item.kind == ty::AssociatedKind::Type)
1010                 .map(|item| (tr.def_id(), item.name)));
1011         }
1012
1013         for projection_bound in &projection_bounds {
1014             let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1015                         projection_bound.0.projection_ty.item_name);
1016             associated_types.remove(&pair);
1017         }
1018
1019         for (trait_def_id, name) in associated_types {
1020             struct_span_err!(tcx.sess, span, E0191,
1021                 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1022                         name,
1023                         tcx.item_path_str(trait_def_id))
1024                         .span_label(span, &format!(
1025                             "missing associated type `{}` value", name))
1026                         .emit();
1027         }
1028
1029         let mut v =
1030             iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
1031             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1032             .chain(existential_projections
1033                    .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1034             .collect::<AccumulateVec<[_; 8]>>();
1035         v.sort_by(|a, b| a.cmp(tcx, b));
1036         let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
1037
1038         let region_bound = self.compute_object_lifetime_bound(span,
1039                                                               &region_bounds,
1040                                                               existential_predicates);
1041
1042         let region_bound = match region_bound {
1043             Some(r) => r,
1044             None => {
1045                 tcx.mk_region(match rscope.object_lifetime_default(span) {
1046                     Some(r) => r,
1047                     None => {
1048                         span_err!(self.tcx().sess, span, E0228,
1049                                   "the lifetime bound for this object type cannot be deduced \
1050                                    from context; please supply an explicit bound");
1051                         ty::ReStatic
1052                     }
1053                 })
1054             }
1055         };
1056
1057         debug!("region_bound: {:?}", region_bound);
1058
1059         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1060         debug!("trait_object_type: {:?}", ty);
1061         ty
1062     }
1063
1064     fn report_ambiguous_associated_type(&self,
1065                                         span: Span,
1066                                         type_str: &str,
1067                                         trait_str: &str,
1068                                         name: &str) {
1069         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1070             .span_label(span, &format!("ambiguous associated type"))
1071             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1072                   type_str, trait_str, name))
1073             .emit();
1074
1075     }
1076
1077     // Search for a bound on a type parameter which includes the associated item
1078     // given by assoc_name. ty_param_node_id is the node id for the type parameter
1079     // (which might be `Self`, but only if it is the `Self` of a trait, not an
1080     // impl). This function will fail if there are no suitable bounds or there is
1081     // any ambiguity.
1082     fn find_bound_for_assoc_item(&self,
1083                                  ty_param_node_id: ast::NodeId,
1084                                  ty_param_name: ast::Name,
1085                                  assoc_name: ast::Name,
1086                                  span: Span)
1087                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1088     {
1089         let tcx = self.tcx();
1090
1091         let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1092             Ok(v) => v,
1093             Err(ErrorReported) => {
1094                 return Err(ErrorReported);
1095             }
1096         };
1097
1098         // Ensure the super predicates and stop if we encountered an error.
1099         if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1100             return Err(ErrorReported);
1101         }
1102
1103         // Check that there is exactly one way to find an associated type with the
1104         // correct name.
1105         let suitable_bounds =
1106             traits::transitive_bounds(tcx, &bounds)
1107             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1108
1109         self.one_bound_for_assoc_type(suitable_bounds,
1110                                       &ty_param_name.as_str(),
1111                                       &assoc_name.as_str(),
1112                                       span)
1113     }
1114
1115
1116     // Checks that bounds contains exactly one element and reports appropriate
1117     // errors otherwise.
1118     fn one_bound_for_assoc_type<I>(&self,
1119                                 mut bounds: I,
1120                                 ty_param_name: &str,
1121                                 assoc_name: &str,
1122                                 span: Span)
1123         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1124         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1125     {
1126         let bound = match bounds.next() {
1127             Some(bound) => bound,
1128             None => {
1129                 struct_span_err!(self.tcx().sess, span, E0220,
1130                           "associated type `{}` not found for `{}`",
1131                           assoc_name,
1132                           ty_param_name)
1133                   .span_label(span, &format!("associated type `{}` not found", assoc_name))
1134                   .emit();
1135                 return Err(ErrorReported);
1136             }
1137         };
1138
1139         if let Some(bound2) = bounds.next() {
1140             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1141             let mut err = struct_span_err!(
1142                 self.tcx().sess, span, E0221,
1143                 "ambiguous associated type `{}` in bounds of `{}`",
1144                 assoc_name,
1145                 ty_param_name);
1146             err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
1147
1148             for bound in bounds {
1149                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1150                     item.kind == ty::AssociatedKind::Type && item.name == assoc_name
1151                 })
1152                 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
1153
1154                 if let Some(span) = bound_span {
1155                     err.span_label(span, &format!("ambiguous `{}` from `{}`",
1156                                                   assoc_name,
1157                                                   bound));
1158                 } else {
1159                     span_note!(&mut err, span,
1160                                "associated type `{}` could derive from `{}`",
1161                                ty_param_name,
1162                                bound);
1163                 }
1164             }
1165             err.emit();
1166         }
1167
1168         return Ok(bound);
1169     }
1170
1171     // Create a type from a path to an associated type.
1172     // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1173     // and item_segment is the path segment for D. We return a type and a def for
1174     // the whole path.
1175     // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1176     // parameter or Self.
1177     pub fn associated_path_def_to_ty(&self,
1178                                      ref_id: ast::NodeId,
1179                                      span: Span,
1180                                      ty: Ty<'tcx>,
1181                                      ty_path_def: Def,
1182                                      item_segment: &hir::PathSegment)
1183                                      -> (Ty<'tcx>, Def)
1184     {
1185         let tcx = self.tcx();
1186         let assoc_name = item_segment.name;
1187
1188         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1189
1190         tcx.prohibit_type_params(slice::ref_slice(item_segment));
1191
1192         // Find the type of the associated item, and the trait where the associated
1193         // item is declared.
1194         let bound = match (&ty.sty, ty_path_def) {
1195             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1196                 // `Self` in an impl of a trait - we have a concrete self type and a
1197                 // trait reference.
1198                 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
1199                 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1200                     trait_ref.subst(tcx, free_substs)
1201                 } else {
1202                     trait_ref
1203                 };
1204
1205                 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
1206                     return (tcx.types.err, Def::Err);
1207                 }
1208
1209                 let candidates =
1210                     traits::supertraits(tcx, ty::Binder(trait_ref))
1211                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1212                                                                          assoc_name));
1213
1214                 match self.one_bound_for_assoc_type(candidates,
1215                                                     "Self",
1216                                                     &assoc_name.as_str(),
1217                                                     span) {
1218                     Ok(bound) => bound,
1219                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1220                 }
1221             }
1222             (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1223                 let trait_node_id = tcx.hir.as_local_node_id(trait_did).unwrap();
1224                 match self.find_bound_for_assoc_item(trait_node_id,
1225                                                      keywords::SelfType.name(),
1226                                                      assoc_name,
1227                                                      span) {
1228                     Ok(bound) => bound,
1229                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1230                 }
1231             }
1232             (&ty::TyParam(_), Def::TyParam(param_did)) => {
1233                 let param_node_id = tcx.hir.as_local_node_id(param_did).unwrap();
1234                 let param_name = tcx.type_parameter_def(param_node_id).name;
1235                 match self.find_bound_for_assoc_item(param_node_id,
1236                                                      param_name,
1237                                                      assoc_name,
1238                                                      span) {
1239                     Ok(bound) => bound,
1240                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1241                 }
1242             }
1243             _ => {
1244                 // Don't print TyErr to the user.
1245                 if !ty.references_error() {
1246                     self.report_ambiguous_associated_type(span,
1247                                                           &ty.to_string(),
1248                                                           "Trait",
1249                                                           &assoc_name.as_str());
1250                 }
1251                 return (tcx.types.err, Def::Err);
1252             }
1253         };
1254
1255         let trait_did = bound.0.def_id;
1256         let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1257
1258         let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
1259         let def_id = item.expect("missing associated type").def_id;
1260         tcx.check_stability(def_id, ref_id, span);
1261         (ty, Def::AssociatedTy(def_id))
1262     }
1263
1264     fn qpath_to_ty(&self,
1265                    rscope: &RegionScope,
1266                    span: Span,
1267                    opt_self_ty: Option<Ty<'tcx>>,
1268                    trait_def_id: DefId,
1269                    trait_segment: &hir::PathSegment,
1270                    item_segment: &hir::PathSegment)
1271                    -> Ty<'tcx>
1272     {
1273         let tcx = self.tcx();
1274
1275         tcx.prohibit_type_params(slice::ref_slice(item_segment));
1276
1277         let self_ty = if let Some(ty) = opt_self_ty {
1278             ty
1279         } else {
1280             let path_str = tcx.item_path_str(trait_def_id);
1281             self.report_ambiguous_associated_type(span,
1282                                                   "Type",
1283                                                   &path_str,
1284                                                   &item_segment.name.as_str());
1285             return tcx.types.err;
1286         };
1287
1288         debug!("qpath_to_ty: self_type={:?}", self_ty);
1289
1290         let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1291                                                         span,
1292                                                         trait_def_id,
1293                                                         self_ty,
1294                                                         trait_segment);
1295
1296         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1297
1298         self.projected_ty(span, trait_ref, item_segment.name)
1299     }
1300
1301     /// Convert a type supplied as value for a type argument from AST into our
1302     /// our internal representation. This is the same as `ast_ty_to_ty` but that
1303     /// it applies the object lifetime default.
1304     ///
1305     /// # Parameters
1306     ///
1307     /// * `this`, `rscope`: the surrounding context
1308     /// * `def`: the type parameter being instantiated (if available)
1309     /// * `region_substs`: a partial substitution consisting of
1310     ///   only the region type parameters being supplied to this type.
1311     /// * `ast_ty`: the ast representation of the type being supplied
1312     fn ast_ty_arg_to_ty(&self,
1313                         rscope: &RegionScope,
1314                         def: Option<&ty::TypeParameterDef<'tcx>>,
1315                         region_substs: &[Kind<'tcx>],
1316                         ast_ty: &hir::Ty)
1317                         -> Ty<'tcx>
1318     {
1319         let tcx = self.tcx();
1320
1321         if let Some(def) = def {
1322             let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1323             let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1324             self.ast_ty_to_ty(rscope1, ast_ty)
1325         } else {
1326             self.ast_ty_to_ty(rscope, ast_ty)
1327         }
1328     }
1329
1330     // Check a type Path and convert it to a Ty.
1331     pub fn def_to_ty(&self,
1332                      rscope: &RegionScope,
1333                      opt_self_ty: Option<Ty<'tcx>>,
1334                      path: &hir::Path,
1335                      path_id: ast::NodeId,
1336                      permit_variants: bool)
1337                      -> Ty<'tcx> {
1338         let tcx = self.tcx();
1339
1340         debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1341                path.def, opt_self_ty, path.segments);
1342
1343         let span = path.span;
1344         match path.def {
1345             Def::Trait(trait_def_id) => {
1346                 // N.B. this case overlaps somewhat with
1347                 // TyTraitObject, see that fn for details
1348
1349                 assert_eq!(opt_self_ty, None);
1350                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1351
1352                 self.trait_path_to_object_type(rscope,
1353                                                span,
1354                                                trait_def_id,
1355                                                path_id,
1356                                                path.segments.last().unwrap(),
1357                                                span,
1358                                                partition_bounds(&[]))
1359             }
1360             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1361                 assert_eq!(opt_self_ty, None);
1362                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1363                 self.ast_path_to_ty(rscope, span, did, path.segments.last().unwrap())
1364             }
1365             Def::Variant(did) if permit_variants => {
1366                 // Convert "variant type" as if it were a real type.
1367                 // The resulting `Ty` is type of the variant's enum for now.
1368                 assert_eq!(opt_self_ty, None);
1369                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1370                 self.ast_path_to_ty(rscope,
1371                                     span,
1372                                     tcx.parent_def_id(did).unwrap(),
1373                                     path.segments.last().unwrap())
1374             }
1375             Def::TyParam(did) => {
1376                 assert_eq!(opt_self_ty, None);
1377                 tcx.prohibit_type_params(&path.segments);
1378
1379                 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1380                 let param = tcx.ty_param_defs.borrow().get(&node_id)
1381                                .map(ty::ParamTy::for_def);
1382                 if let Some(p) = param {
1383                     p.to_ty(tcx)
1384                 } else {
1385                     // Only while computing defaults of earlier type
1386                     // parameters can a type parameter be missing its def.
1387                     struct_span_err!(tcx.sess, span, E0128,
1388                                      "type parameters with a default cannot use \
1389                                       forward declared identifiers")
1390                         .span_label(span, &format!("defaulted type parameters \
1391                                                     cannot be forward declared"))
1392                         .emit();
1393                     tcx.types.err
1394                 }
1395             }
1396             Def::SelfTy(_, Some(def_id)) => {
1397                 // Self in impl (we know the concrete type).
1398
1399                 assert_eq!(opt_self_ty, None);
1400                 tcx.prohibit_type_params(&path.segments);
1401
1402                 // FIXME: Self type is not always computed when we are here because type parameter
1403                 // bounds may affect Self type and have to be converted before it.
1404                 let ty = if def_id.is_local() {
1405                     tcx.item_types.borrow().get(&def_id).cloned()
1406                 } else {
1407                     Some(tcx.item_type(def_id))
1408                 };
1409                 if let Some(ty) = ty {
1410                     if let Some(free_substs) = self.get_free_substs() {
1411                         ty.subst(tcx, free_substs)
1412                     } else {
1413                         ty
1414                     }
1415                 } else {
1416                     tcx.sess.span_err(span, "`Self` type is used before it's determined");
1417                     tcx.types.err
1418                 }
1419             }
1420             Def::SelfTy(Some(_), None) => {
1421                 // Self in trait.
1422                 assert_eq!(opt_self_ty, None);
1423                 tcx.prohibit_type_params(&path.segments);
1424                 tcx.mk_self_type()
1425             }
1426             Def::AssociatedTy(def_id) => {
1427                 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1428                 let trait_did = tcx.parent_def_id(def_id).unwrap();
1429                 self.qpath_to_ty(rscope,
1430                                  span,
1431                                  opt_self_ty,
1432                                  trait_did,
1433                                  &path.segments[path.segments.len()-2],
1434                                  path.segments.last().unwrap())
1435             }
1436             Def::PrimTy(prim_ty) => {
1437                 assert_eq!(opt_self_ty, None);
1438                 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1439             }
1440             Def::Err => {
1441                 self.set_tainted_by_errors();
1442                 return self.tcx().types.err;
1443             }
1444             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1445         }
1446     }
1447
1448     /// Parses the programmer's textual representation of a type into our
1449     /// internal notion of a type.
1450     pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1451         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1452                ast_ty.id, ast_ty);
1453
1454         let tcx = self.tcx();
1455
1456         let cache = self.ast_ty_to_ty_cache();
1457         if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1458             return ty;
1459         }
1460
1461         let result_ty = match ast_ty.node {
1462             hir::TySlice(ref ty) => {
1463                 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1464             }
1465             hir::TyPtr(ref mt) => {
1466                 tcx.mk_ptr(ty::TypeAndMut {
1467                     ty: self.ast_ty_to_ty(rscope, &mt.ty),
1468                     mutbl: mt.mutbl
1469                 })
1470             }
1471             hir::TyRptr(ref region, ref mt) => {
1472                 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, Some(region), None);
1473                 debug!("TyRef r={:?}", r);
1474                 let rscope1 =
1475                     &ObjectLifetimeDefaultRscope::new(
1476                         rscope,
1477                         ty::ObjectLifetimeDefault::Specific(r));
1478                 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1479                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1480             }
1481             hir::TyNever => {
1482                 tcx.types.never
1483             },
1484             hir::TyTup(ref fields) => {
1485                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(rscope, &t)))
1486             }
1487             hir::TyBareFn(ref bf) => {
1488                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1489                 let anon_scope = rscope.anon_type_scope();
1490                 let bare_fn_ty = self.ty_of_method_or_bare_fn(bf.unsafety,
1491                                                               bf.abi,
1492                                                               None,
1493                                                               &bf.decl,
1494                                                               None,
1495                                                               anon_scope,
1496                                                               anon_scope);
1497
1498                 // Find any late-bound regions declared in return type that do
1499                 // not appear in the arguments. These are not wellformed.
1500                 //
1501                 // Example:
1502                 //
1503                 //     for<'a> fn() -> &'a str <-- 'a is bad
1504                 //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1505                 //
1506                 // Note that we do this check **here** and not in
1507                 // `ty_of_bare_fn` because the latter is also used to make
1508                 // the types for fn items, and we do not want to issue a
1509                 // warning then. (Once we fix #32330, the regions we are
1510                 // checking for here would be considered early bound
1511                 // anyway.)
1512                 let inputs = bare_fn_ty.sig.inputs();
1513                 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1514                     &inputs.map_bound(|i| i.to_owned()));
1515                 let output = bare_fn_ty.sig.output();
1516                 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1517                 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1518                     let br_name = match *br {
1519                         ty::BrNamed(_, name, _) => name,
1520                         _ => {
1521                             span_bug!(
1522                                 bf.decl.output.span(),
1523                                 "anonymous bound region {:?} in return but not args",
1524                                 br);
1525                         }
1526                     };
1527                     tcx.sess.add_lint(
1528                         lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1529                         ast_ty.id,
1530                         ast_ty.span,
1531                         format!("return type references lifetime `{}`, \
1532                                  which does not appear in the trait input types",
1533                                 br_name));
1534                 }
1535                 tcx.mk_fn_ptr(bare_fn_ty)
1536             }
1537             hir::TyTraitObject(ref bounds) => {
1538                 self.conv_object_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1539             }
1540             hir::TyImplTrait(ref bounds) => {
1541                 use collect::{compute_bounds, SizedByDefault};
1542
1543                 // Create the anonymized type.
1544                 let def_id = tcx.hir.local_def_id(ast_ty.id);
1545                 if let Some(anon_scope) = rscope.anon_type_scope() {
1546                     let substs = anon_scope.fresh_substs(self, ast_ty.span);
1547                     let ty = tcx.mk_anon(tcx.hir.local_def_id(ast_ty.id), substs);
1548
1549                     // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1550                     let bounds = compute_bounds(self, ty, bounds,
1551                                                 SizedByDefault::Yes,
1552                                                 Some(anon_scope),
1553                                                 ast_ty.span);
1554                     let predicates = bounds.predicates(tcx, ty);
1555                     let predicates = tcx.lift_to_global(&predicates).unwrap();
1556                     tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1557                         parent: None,
1558                         predicates: predicates
1559                     });
1560
1561                     ty
1562                 } else {
1563                     span_err!(tcx.sess, ast_ty.span, E0562,
1564                               "`impl Trait` not allowed outside of function \
1565                                and inherent method return types");
1566                     tcx.types.err
1567                 }
1568             }
1569             hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1570                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1571                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1572                     self.ast_ty_to_ty(rscope, qself)
1573                 });
1574                 self.def_to_ty(rscope, opt_self_ty, path, ast_ty.id, false)
1575             }
1576             hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1577                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1578                 let ty = self.ast_ty_to_ty(rscope, qself);
1579
1580                 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1581                     path.def
1582                 } else {
1583                     Def::Err
1584                 };
1585                 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1586             }
1587             hir::TyArray(ref ty, length) => {
1588                 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1589                     tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), length)
1590                 } else {
1591                     self.tcx().types.err
1592                 }
1593             }
1594             hir::TyTypeof(ref _e) => {
1595                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1596                                  "`typeof` is a reserved keyword but unimplemented")
1597                     .span_label(ast_ty.span, &format!("reserved keyword"))
1598                     .emit();
1599
1600                 tcx.types.err
1601             }
1602             hir::TyInfer => {
1603                 // TyInfer also appears as the type of arguments or return
1604                 // values in a ExprClosure, or as
1605                 // the type of local variables. Both of these cases are
1606                 // handled specially and will not descend into this routine.
1607                 self.ty_infer(ast_ty.span)
1608             }
1609         };
1610
1611         cache.borrow_mut().insert(ast_ty.id, result_ty);
1612
1613         result_ty
1614     }
1615
1616     pub fn ty_of_arg(&self,
1617                      rscope: &RegionScope,
1618                      ty: &hir::Ty,
1619                      expected_ty: Option<Ty<'tcx>>)
1620                      -> Ty<'tcx>
1621     {
1622         match ty.node {
1623             hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1624             hir::TyInfer => self.ty_infer(ty.span),
1625             _ => self.ast_ty_to_ty(rscope, ty),
1626         }
1627     }
1628
1629     pub fn ty_of_method(&self,
1630                         sig: &hir::MethodSig,
1631                         opt_self_value_ty: Option<Ty<'tcx>>,
1632                         body: Option<hir::BodyId>,
1633                         anon_scope: Option<AnonTypeScope>)
1634                         -> &'tcx ty::BareFnTy<'tcx> {
1635         self.ty_of_method_or_bare_fn(sig.unsafety,
1636                                      sig.abi,
1637                                      opt_self_value_ty,
1638                                      &sig.decl,
1639                                      body,
1640                                      None,
1641                                      anon_scope)
1642     }
1643
1644     pub fn ty_of_bare_fn(&self,
1645                          unsafety: hir::Unsafety,
1646                          abi: abi::Abi,
1647                          decl: &hir::FnDecl,
1648                          body: hir::BodyId,
1649                          anon_scope: Option<AnonTypeScope>)
1650                          -> &'tcx ty::BareFnTy<'tcx> {
1651         self.ty_of_method_or_bare_fn(unsafety, abi, None, decl, Some(body), None, anon_scope)
1652     }
1653
1654     fn ty_of_method_or_bare_fn(&self,
1655                                unsafety: hir::Unsafety,
1656                                abi: abi::Abi,
1657                                opt_self_value_ty: Option<Ty<'tcx>>,
1658                                decl: &hir::FnDecl,
1659                                body: Option<hir::BodyId>,
1660                                arg_anon_scope: Option<AnonTypeScope>,
1661                                ret_anon_scope: Option<AnonTypeScope>)
1662                                -> &'tcx ty::BareFnTy<'tcx>
1663     {
1664         debug!("ty_of_method_or_bare_fn");
1665
1666         // New region names that appear inside of the arguments of the function
1667         // declaration are bound to that function type.
1668         let rb = MaybeWithAnonTypes::new(BindingRscope::new(), arg_anon_scope);
1669
1670         let input_tys: Vec<Ty> =
1671             decl.inputs.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1672
1673         let has_self = opt_self_value_ty.is_some();
1674         let explicit_self = opt_self_value_ty.map(|self_value_ty| {
1675             ExplicitSelf::determine(self_value_ty, input_tys[0])
1676         });
1677
1678         let implied_output_region = match explicit_self {
1679             // `implied_output_region` is the region that will be assumed for any
1680             // region parameters in the return type. In accordance with the rules for
1681             // lifetime elision, we can determine it in two ways. First (determined
1682             // here), if self is by-reference, then the implied output region is the
1683             // region of the self parameter.
1684             Some(ExplicitSelf::ByReference(region, _)) => Ok(*region),
1685
1686             // Second, if there was exactly one lifetime (either a substitution or a
1687             // reference) in the arguments, then any anonymous regions in the output
1688             // have that lifetime.
1689             _ => {
1690                 let arg_tys = &input_tys[has_self as usize..];
1691                 let arg_params = has_self as usize..input_tys.len();
1692                 self.find_implied_output_region(arg_tys, body, arg_params)
1693
1694             }
1695         };
1696
1697         let output_ty = match decl.output {
1698             hir::Return(ref output) =>
1699                 self.convert_ty_with_lifetime_elision(implied_output_region,
1700                                                       &output,
1701                                                       ret_anon_scope),
1702             hir::DefaultReturn(..) => self.tcx().mk_nil(),
1703         };
1704
1705         debug!("ty_of_method_or_bare_fn: output_ty={:?}", output_ty);
1706
1707         self.tcx().mk_bare_fn(ty::BareFnTy {
1708             unsafety: unsafety,
1709             abi: abi,
1710             sig: ty::Binder(self.tcx().mk_fn_sig(
1711                 input_tys.into_iter(),
1712                 output_ty,
1713                 decl.variadic
1714             )),
1715         })
1716     }
1717
1718     pub fn ty_of_closure(&self,
1719         unsafety: hir::Unsafety,
1720         decl: &hir::FnDecl,
1721         abi: abi::Abi,
1722         expected_sig: Option<ty::FnSig<'tcx>>)
1723         -> ty::ClosureTy<'tcx>
1724     {
1725         debug!("ty_of_closure(expected_sig={:?})",
1726                expected_sig);
1727
1728         // new region names that appear inside of the fn decl are bound to
1729         // that function type
1730         let rb = rscope::BindingRscope::new();
1731
1732         let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1733             let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1734                 // no guarantee that the correct number of expected args
1735                 // were supplied
1736                 if i < e.inputs().len() {
1737                     Some(e.inputs()[i])
1738                 } else {
1739                     None
1740                 }
1741             });
1742             self.ty_of_arg(&rb, a, expected_arg_ty)
1743         });
1744
1745         let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1746
1747         let is_infer = match decl.output {
1748             hir::Return(ref output) if output.node == hir::TyInfer => true,
1749             hir::DefaultReturn(..) => true,
1750             _ => false
1751         };
1752
1753         let output_ty = match decl.output {
1754             _ if is_infer && expected_ret_ty.is_some() =>
1755                 expected_ret_ty.unwrap(),
1756             _ if is_infer => self.ty_infer(decl.output.span()),
1757             hir::Return(ref output) =>
1758                 self.ast_ty_to_ty(&rb, &output),
1759             hir::DefaultReturn(..) => bug!(),
1760         };
1761
1762         debug!("ty_of_closure: output_ty={:?}", output_ty);
1763
1764         ty::ClosureTy {
1765             unsafety: unsafety,
1766             abi: abi,
1767             sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1768         }
1769     }
1770
1771     fn conv_object_ty_poly_trait_ref(&self,
1772         rscope: &RegionScope,
1773         span: Span,
1774         ast_bounds: &[hir::TyParamBound])
1775         -> Ty<'tcx>
1776     {
1777         let mut partitioned_bounds = partition_bounds(ast_bounds);
1778
1779         let trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1780             partitioned_bounds.trait_bounds.remove(0)
1781         } else {
1782             span_err!(self.tcx().sess, span, E0224,
1783                       "at least one non-builtin trait is required for an object type");
1784             return self.tcx().types.err;
1785         };
1786
1787         let trait_ref = &trait_bound.trait_ref;
1788         let trait_def_id = self.trait_def_id(trait_ref);
1789         self.trait_path_to_object_type(rscope,
1790                                        trait_ref.path.span,
1791                                        trait_def_id,
1792                                        trait_ref.ref_id,
1793                                        trait_ref.path.segments.last().unwrap(),
1794                                        span,
1795                                        partitioned_bounds)
1796     }
1797
1798     /// Given the bounds on an object, determines what single region bound (if any) we can
1799     /// use to summarize this type. The basic idea is that we will use the bound the user
1800     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1801     /// for region bounds. It may be that we can derive no bound at all, in which case
1802     /// we return `None`.
1803     fn compute_object_lifetime_bound(&self,
1804         span: Span,
1805         explicit_region_bounds: &[&hir::Lifetime],
1806         existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1807         -> Option<&'tcx ty::Region> // if None, use the default
1808     {
1809         let tcx = self.tcx();
1810
1811         debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
1812                existential_predicates={:?})",
1813                explicit_region_bounds,
1814                existential_predicates);
1815
1816         if explicit_region_bounds.len() > 1 {
1817             span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
1818                 "only a single explicit lifetime bound is permitted");
1819         }
1820
1821         if let Some(&r) = explicit_region_bounds.get(0) {
1822             // Explicitly specified region bound. Use that.
1823             return Some(self.ast_region_to_region(r));
1824         }
1825
1826         if let Some(principal) = existential_predicates.principal() {
1827             if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1828                 return Some(tcx.mk_region(ty::ReStatic));
1829             }
1830         }
1831
1832         // No explicit region bound specified. Therefore, examine trait
1833         // bounds and see if we can derive region bounds from those.
1834         let derived_region_bounds =
1835             object_region_bounds(tcx, existential_predicates);
1836
1837         // If there are no derived region bounds, then report back that we
1838         // can find no region bound. The caller will use the default.
1839         if derived_region_bounds.is_empty() {
1840             return None;
1841         }
1842
1843         // If any of the derived region bounds are 'static, that is always
1844         // the best choice.
1845         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1846             return Some(tcx.mk_region(ty::ReStatic));
1847         }
1848
1849         // Determine whether there is exactly one unique region in the set
1850         // of derived region bounds. If so, use that. Otherwise, report an
1851         // error.
1852         let r = derived_region_bounds[0];
1853         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1854             span_err!(tcx.sess, span, E0227,
1855                       "ambiguous lifetime bound, explicit lifetime bound required");
1856         }
1857         return Some(r);
1858     }
1859 }
1860
1861 pub struct PartitionedBounds<'a> {
1862     pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
1863     pub region_bounds: Vec<&'a hir::Lifetime>,
1864 }
1865
1866 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1867 /// remaining general trait bounds.
1868 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1869                                          trait_bounds: Vec<&'b hir::PolyTraitRef>)
1870     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1871 {
1872     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.into_iter().partition(|bound| {
1873         match bound.trait_ref.path.def {
1874             Def::Trait(trait_did) => {
1875                 // Checks whether `trait_did` refers to one of the builtin
1876                 // traits, like `Send`, and adds it to `auto_traits` if so.
1877                 if Some(trait_did) == tcx.lang_items.send_trait() ||
1878                     Some(trait_did) == tcx.lang_items.sync_trait() {
1879                     let segments = &bound.trait_ref.path.segments;
1880                     let parameters = &segments[segments.len() - 1].parameters;
1881                     if !parameters.types().is_empty() {
1882                         check_type_argument_count(tcx, bound.trait_ref.path.span,
1883                                                   parameters.types().len(), &[]);
1884                     }
1885                     if !parameters.lifetimes().is_empty() {
1886                         report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1887                                                      parameters.lifetimes().len(), 0);
1888                     }
1889                     true
1890                 } else {
1891                     false
1892                 }
1893             }
1894             _ => false
1895         }
1896     });
1897
1898     let auto_traits = auto_traits.into_iter().map(|tr| {
1899         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1900             trait_did
1901         } else {
1902             unreachable!()
1903         }
1904     }).collect::<Vec<_>>();
1905
1906     (auto_traits, trait_bounds)
1907 }
1908
1909 /// Divides a list of bounds from the AST into two groups: general trait bounds and region bounds
1910 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(ast_bounds: &'b [hir::TyParamBound])
1911     -> PartitionedBounds<'b>
1912 {
1913     let mut region_bounds = Vec::new();
1914     let mut trait_bounds = Vec::new();
1915     for ast_bound in ast_bounds {
1916         match *ast_bound {
1917             hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
1918                 trait_bounds.push(b);
1919             }
1920             hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
1921             hir::RegionTyParamBound(ref l) => {
1922                 region_bounds.push(l);
1923             }
1924         }
1925     }
1926
1927     PartitionedBounds {
1928         trait_bounds: trait_bounds,
1929         region_bounds: region_bounds,
1930     }
1931 }
1932
1933 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1934                              ty_param_defs: &[ty::TypeParameterDef]) {
1935     let accepted = ty_param_defs.len();
1936     let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
1937     if supplied < required {
1938         let expected = if required < accepted {
1939             "expected at least"
1940         } else {
1941             "expected"
1942         };
1943         let arguments_plural = if required == 1 { "" } else { "s" };
1944
1945         struct_span_err!(tcx.sess, span, E0243,
1946                 "wrong number of type arguments: {} {}, found {}",
1947                 expected, required, supplied)
1948             .span_label(span,
1949                 &format!("{} {} type argument{}",
1950                     expected,
1951                     required,
1952                     arguments_plural))
1953             .emit();
1954     } else if supplied > accepted {
1955         let expected = if required < accepted {
1956             format!("expected at most {}", accepted)
1957         } else {
1958             format!("expected {}", accepted)
1959         };
1960         let arguments_plural = if accepted == 1 { "" } else { "s" };
1961
1962         struct_span_err!(tcx.sess, span, E0244,
1963                 "wrong number of type arguments: {}, found {}",
1964                 expected, supplied)
1965             .span_label(
1966                 span,
1967                 &format!("{} type argument{}",
1968                     if accepted == 0 { "expected no" } else { &expected },
1969                     arguments_plural)
1970             )
1971             .emit();
1972     }
1973 }
1974
1975 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1976     let label = if number < expected {
1977         if expected == 1 {
1978             format!("expected {} lifetime parameter", expected)
1979         } else {
1980             format!("expected {} lifetime parameters", expected)
1981         }
1982     } else {
1983         let additional = number - expected;
1984         if additional == 1 {
1985             "unexpected lifetime parameter".to_string()
1986         } else {
1987             format!("{} unexpected lifetime parameters", additional)
1988         }
1989     };
1990     struct_span_err!(tcx.sess, span, E0107,
1991                      "wrong number of lifetime parameters: expected {}, found {}",
1992                      expected, number)
1993         .span_label(span, &label)
1994         .emit();
1995 }
1996
1997 // A helper struct for conveniently grouping a set of bounds which we pass to
1998 // and return from functions in multiple places.
1999 #[derive(PartialEq, Eq, Clone, Debug)]
2000 pub struct Bounds<'tcx> {
2001     pub region_bounds: Vec<&'tcx ty::Region>,
2002     pub implicitly_sized: bool,
2003     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2004     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2005 }
2006
2007 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2008     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2009                       -> Vec<ty::Predicate<'tcx>>
2010     {
2011         let mut vec = Vec::new();
2012
2013         // If it could be sized, and is, add the sized predicate
2014         if self.implicitly_sized {
2015             if let Some(sized) = tcx.lang_items.sized_trait() {
2016                 let trait_ref = ty::TraitRef {
2017                     def_id: sized,
2018                     substs: tcx.mk_substs_trait(param_ty, &[])
2019                 };
2020                 vec.push(trait_ref.to_predicate());
2021             }
2022         }
2023
2024         for &region_bound in &self.region_bounds {
2025             // account for the binder being introduced below; no need to shift `param_ty`
2026             // because, at present at least, it can only refer to early-bound regions
2027             let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
2028             vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2029         }
2030
2031         for bound_trait_ref in &self.trait_bounds {
2032             vec.push(bound_trait_ref.to_predicate());
2033         }
2034
2035         for projection in &self.projection_bounds {
2036             vec.push(projection.to_predicate());
2037         }
2038
2039         vec
2040     }
2041 }
2042
2043 pub enum ExplicitSelf<'tcx> {
2044     ByValue,
2045     ByReference(&'tcx ty::Region, hir::Mutability),
2046     ByBox
2047 }
2048
2049 impl<'tcx> ExplicitSelf<'tcx> {
2050     /// We wish to (for now) categorize an explicit self
2051     /// declaration like `self: SomeType` into either `self`,
2052     /// `&self`, `&mut self`, or `Box<self>`. We do this here
2053     /// by some simple pattern matching. A more precise check
2054     /// is done later in `check_method_self_type()`.
2055     ///
2056     /// Examples:
2057     ///
2058     /// ```
2059     /// impl Foo for &T {
2060     ///     // Legal declarations:
2061     ///     fn method1(self: &&T); // ExplicitSelf::ByReference
2062     ///     fn method2(self: &T); // ExplicitSelf::ByValue
2063     ///     fn method3(self: Box<&T>); // ExplicitSelf::ByBox
2064     ///
2065     ///     // Invalid cases will be caught later by `check_method_self_type`:
2066     ///     fn method_err1(self: &mut T); // ExplicitSelf::ByReference
2067     /// }
2068     /// ```
2069     ///
2070     /// To do the check we just count the number of "modifiers"
2071     /// on each type and compare them. If they are the same or
2072     /// the impl has more, we call it "by value". Otherwise, we
2073     /// look at the outermost modifier on the method decl and
2074     /// call it by-ref, by-box as appropriate. For method1, for
2075     /// example, the impl type has one modifier, but the method
2076     /// type has two, so we end up with
2077     /// ExplicitSelf::ByReference.
2078     pub fn determine(untransformed_self_ty: Ty<'tcx>,
2079                      self_arg_ty: Ty<'tcx>)
2080                      -> ExplicitSelf<'tcx> {
2081         fn count_modifiers(ty: Ty) -> usize {
2082             match ty.sty {
2083                 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
2084                 ty::TyBox(t) => count_modifiers(t) + 1,
2085                 _ => 0,
2086             }
2087         }
2088
2089         let impl_modifiers = count_modifiers(untransformed_self_ty);
2090         let method_modifiers = count_modifiers(self_arg_ty);
2091
2092         if impl_modifiers >= method_modifiers {
2093             ExplicitSelf::ByValue
2094         } else {
2095             match self_arg_ty.sty {
2096                 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
2097                 ty::TyBox(_) => ExplicitSelf::ByBox,
2098                 _ => ExplicitSelf::ByValue,
2099             }
2100         }
2101     }
2102 }