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