]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Auto merge of #38925 - petrochenkov:varass, 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, Pos};
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     fn ast_ty_to_object_trait_ref(&self,
934                                   rscope: &RegionScope,
935                                   span: Span,
936                                   ty: &hir::Ty,
937                                   bounds: &[hir::TyParamBound])
938                                   -> Ty<'tcx>
939     {
940         /*!
941          * In a type like `Foo + Send`, we want to wait to collect the
942          * full set of bounds before we make the object type, because we
943          * need them to infer a region bound.  (For example, if we tried
944          * made a type from just `Foo`, then it wouldn't be enough to
945          * infer a 'static bound, and hence the user would get an error.)
946          * So this function is used when we're dealing with a sum type to
947          * convert the LHS. It only accepts a type that refers to a trait
948          * name, and reports an error otherwise.
949          */
950
951         let tcx = self.tcx();
952         match ty.node {
953             hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
954                 if let Def::Trait(trait_def_id) = path.def {
955                     self.trait_path_to_object_type(rscope,
956                                                    path.span,
957                                                    trait_def_id,
958                                                    ty.id,
959                                                    path.segments.last().unwrap(),
960                                                    span,
961                                                    partition_bounds(bounds))
962                 } else {
963                     struct_span_err!(tcx.sess, ty.span, E0172,
964                                      "expected a reference to a trait")
965                         .span_label(ty.span, &format!("expected a trait"))
966                         .emit();
967                     tcx.types.err
968                 }
969             }
970             _ => {
971                 let mut err = struct_span_err!(tcx.sess, ty.span, E0178,
972                                                "expected a path on the left-hand side \
973                                                 of `+`, not `{}`",
974                                                tcx.map.node_to_pretty_string(ty.id));
975                 err.span_label(ty.span, &format!("expected a path"));
976                 let hi = bounds.iter().map(|x| match *x {
977                     hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
978                     hir::RegionTyParamBound(ref r) => r.span.hi,
979                 }).max_by_key(|x| x.to_usize());
980                 let full_span = hi.map(|hi| Span {
981                     lo: ty.span.lo,
982                     hi: hi,
983                     expn_id: ty.span.expn_id,
984                 });
985                 match (&ty.node, full_span) {
986                     (&hir::TyRptr(ref lifetime, ref mut_ty), Some(full_span)) => {
987                         let ty_str = hir::print::to_string(&tcx.map, |s| {
988                             use syntax::print::pp::word;
989                             use syntax::print::pprust::PrintState;
990
991                             word(&mut s.s, "&")?;
992                             s.print_opt_lifetime(lifetime)?;
993                             s.print_mutability(mut_ty.mutbl)?;
994                             s.popen()?;
995                             s.print_type(&mut_ty.ty)?;
996                             s.print_bounds(" +", bounds)?;
997                             s.pclose()
998                         });
999                         err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1000                                             ty_str);
1001                     }
1002
1003                     _ => {
1004                         help!(&mut err,
1005                                    "perhaps you forgot parentheses? (per RFC 438)");
1006                     }
1007                 }
1008                 err.emit();
1009                 tcx.types.err
1010             }
1011         }
1012     }
1013
1014     /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
1015     /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
1016     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
1017                                 -> ty::ExistentialTraitRef<'tcx> {
1018         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
1019         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
1020     }
1021
1022     fn trait_path_to_object_type(&self,
1023                                  rscope: &RegionScope,
1024                                  path_span: Span,
1025                                  trait_def_id: DefId,
1026                                  trait_path_ref_id: ast::NodeId,
1027                                  trait_segment: &hir::PathSegment,
1028                                  span: Span,
1029                                  partitioned_bounds: PartitionedBounds)
1030                                  -> Ty<'tcx> {
1031         let tcx = self.tcx();
1032
1033         let mut projection_bounds = vec![];
1034         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
1035         let principal = self.ast_path_to_poly_trait_ref(rscope,
1036                                                         path_span,
1037                                                         trait_def_id,
1038                                                         dummy_self,
1039                                                         trait_path_ref_id,
1040                                                         trait_segment,
1041                                                         &mut projection_bounds);
1042
1043         let PartitionedBounds { trait_bounds,
1044                                 region_bounds } =
1045             partitioned_bounds;
1046
1047         let (auto_traits, trait_bounds) = split_auto_traits(tcx, trait_bounds);
1048
1049         if !trait_bounds.is_empty() {
1050             let b = &trait_bounds[0];
1051             let span = b.trait_ref.path.span;
1052             struct_span_err!(self.tcx().sess, span, E0225,
1053                 "only Send/Sync traits can be used as additional traits in a trait object")
1054                 .span_label(span, &format!("non-Send/Sync additional trait"))
1055                 .emit();
1056         }
1057
1058         // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
1059         let existential_principal = principal.map_bound(|trait_ref| {
1060             self.trait_ref_to_existential(trait_ref)
1061         });
1062         let existential_projections = projection_bounds.iter().map(|bound| {
1063             bound.map_bound(|b| {
1064                 let p = b.projection_ty;
1065                 ty::ExistentialProjection {
1066                     trait_ref: self.trait_ref_to_existential(p.trait_ref),
1067                     item_name: p.item_name,
1068                     ty: b.ty
1069                 }
1070             })
1071         });
1072
1073         // ensure the super predicates and stop if we encountered an error
1074         if self.ensure_super_predicates(span, principal.def_id()).is_err() {
1075             return tcx.types.err;
1076         }
1077
1078         // check that there are no gross object safety violations,
1079         // most importantly, that the supertraits don't contain Self,
1080         // to avoid ICE-s.
1081         let object_safety_violations =
1082             tcx.astconv_object_safety_violations(principal.def_id());
1083         if !object_safety_violations.is_empty() {
1084             tcx.report_object_safety_error(
1085                 span, principal.def_id(), object_safety_violations)
1086                 .emit();
1087             return tcx.types.err;
1088         }
1089
1090         let mut associated_types = FxHashSet::default();
1091         for tr in traits::supertraits(tcx, principal) {
1092             associated_types.extend(tcx.associated_items(tr.def_id())
1093                 .filter(|item| item.kind == ty::AssociatedKind::Type)
1094                 .map(|item| (tr.def_id(), item.name)));
1095         }
1096
1097         for projection_bound in &projection_bounds {
1098             let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1099                         projection_bound.0.projection_ty.item_name);
1100             associated_types.remove(&pair);
1101         }
1102
1103         for (trait_def_id, name) in associated_types {
1104             struct_span_err!(tcx.sess, span, E0191,
1105                 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1106                         name,
1107                         tcx.item_path_str(trait_def_id))
1108                         .span_label(span, &format!(
1109                             "missing associated type `{}` value", name))
1110                         .emit();
1111         }
1112
1113         let mut v =
1114             iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
1115             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1116             .chain(existential_projections
1117                    .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1118             .collect::<AccumulateVec<[_; 8]>>();
1119         v.sort_by(|a, b| a.cmp(tcx, b));
1120         let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
1121
1122         let region_bound = self.compute_object_lifetime_bound(span,
1123                                                               &region_bounds,
1124                                                               existential_predicates);
1125
1126         let region_bound = match region_bound {
1127             Some(r) => r,
1128             None => {
1129                 tcx.mk_region(match rscope.object_lifetime_default(span) {
1130                     Some(r) => r,
1131                     None => {
1132                         span_err!(self.tcx().sess, span, E0228,
1133                                   "the lifetime bound for this object type cannot be deduced \
1134                                    from context; please supply an explicit bound");
1135                         ty::ReStatic
1136                     }
1137                 })
1138             }
1139         };
1140
1141         debug!("region_bound: {:?}", region_bound);
1142
1143         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1144         debug!("trait_object_type: {:?}", ty);
1145         ty
1146     }
1147
1148     fn report_ambiguous_associated_type(&self,
1149                                         span: Span,
1150                                         type_str: &str,
1151                                         trait_str: &str,
1152                                         name: &str) {
1153         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1154             .span_label(span, &format!("ambiguous associated type"))
1155             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1156                   type_str, trait_str, name))
1157             .emit();
1158
1159     }
1160
1161     // Search for a bound on a type parameter which includes the associated item
1162     // given by assoc_name. ty_param_node_id is the node id for the type parameter
1163     // (which might be `Self`, but only if it is the `Self` of a trait, not an
1164     // impl). This function will fail if there are no suitable bounds or there is
1165     // any ambiguity.
1166     fn find_bound_for_assoc_item(&self,
1167                                  ty_param_node_id: ast::NodeId,
1168                                  ty_param_name: ast::Name,
1169                                  assoc_name: ast::Name,
1170                                  span: Span)
1171                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1172     {
1173         let tcx = self.tcx();
1174
1175         let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1176             Ok(v) => v,
1177             Err(ErrorReported) => {
1178                 return Err(ErrorReported);
1179             }
1180         };
1181
1182         // Ensure the super predicates and stop if we encountered an error.
1183         if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1184             return Err(ErrorReported);
1185         }
1186
1187         // Check that there is exactly one way to find an associated type with the
1188         // correct name.
1189         let suitable_bounds =
1190             traits::transitive_bounds(tcx, &bounds)
1191             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1192
1193         self.one_bound_for_assoc_type(suitable_bounds,
1194                                       &ty_param_name.as_str(),
1195                                       &assoc_name.as_str(),
1196                                       span)
1197     }
1198
1199
1200     // Checks that bounds contains exactly one element and reports appropriate
1201     // errors otherwise.
1202     fn one_bound_for_assoc_type<I>(&self,
1203                                 mut bounds: I,
1204                                 ty_param_name: &str,
1205                                 assoc_name: &str,
1206                                 span: Span)
1207         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1208         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1209     {
1210         let bound = match bounds.next() {
1211             Some(bound) => bound,
1212             None => {
1213                 struct_span_err!(self.tcx().sess, span, E0220,
1214                           "associated type `{}` not found for `{}`",
1215                           assoc_name,
1216                           ty_param_name)
1217                   .span_label(span, &format!("associated type `{}` not found", assoc_name))
1218                   .emit();
1219                 return Err(ErrorReported);
1220             }
1221         };
1222
1223         if let Some(bound2) = bounds.next() {
1224             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1225             let mut err = struct_span_err!(
1226                 self.tcx().sess, span, E0221,
1227                 "ambiguous associated type `{}` in bounds of `{}`",
1228                 assoc_name,
1229                 ty_param_name);
1230             err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
1231
1232             for bound in bounds {
1233                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1234                     item.kind == ty::AssociatedKind::Type && item.name == assoc_name
1235                 })
1236                 .and_then(|item| self.tcx().map.span_if_local(item.def_id));
1237
1238                 if let Some(span) = bound_span {
1239                     err.span_label(span, &format!("ambiguous `{}` from `{}`",
1240                                                   assoc_name,
1241                                                   bound));
1242                 } else {
1243                     span_note!(&mut err, span,
1244                                "associated type `{}` could derive from `{}`",
1245                                ty_param_name,
1246                                bound);
1247                 }
1248             }
1249             err.emit();
1250         }
1251
1252         return Ok(bound);
1253     }
1254
1255     // Create a type from a path to an associated type.
1256     // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1257     // and item_segment is the path segment for D. We return a type and a def for
1258     // the whole path.
1259     // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1260     // parameter or Self.
1261     pub fn associated_path_def_to_ty(&self,
1262                                      ref_id: ast::NodeId,
1263                                      span: Span,
1264                                      ty: Ty<'tcx>,
1265                                      ty_path_def: Def,
1266                                      item_segment: &hir::PathSegment)
1267                                      -> (Ty<'tcx>, Def)
1268     {
1269         let tcx = self.tcx();
1270         let assoc_name = item_segment.name;
1271
1272         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1273
1274         tcx.prohibit_type_params(slice::ref_slice(item_segment));
1275
1276         // Find the type of the associated item, and the trait where the associated
1277         // item is declared.
1278         let bound = match (&ty.sty, ty_path_def) {
1279             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1280                 // `Self` in an impl of a trait - we have a concrete self type and a
1281                 // trait reference.
1282                 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
1283                 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1284                     trait_ref.subst(tcx, free_substs)
1285                 } else {
1286                     trait_ref
1287                 };
1288
1289                 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
1290                     return (tcx.types.err, Def::Err);
1291                 }
1292
1293                 let candidates =
1294                     traits::supertraits(tcx, ty::Binder(trait_ref))
1295                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1296                                                                          assoc_name));
1297
1298                 match self.one_bound_for_assoc_type(candidates,
1299                                                     "Self",
1300                                                     &assoc_name.as_str(),
1301                                                     span) {
1302                     Ok(bound) => bound,
1303                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1304                 }
1305             }
1306             (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1307                 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1308                 match self.find_bound_for_assoc_item(trait_node_id,
1309                                                      keywords::SelfType.name(),
1310                                                      assoc_name,
1311                                                      span) {
1312                     Ok(bound) => bound,
1313                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1314                 }
1315             }
1316             (&ty::TyParam(_), Def::TyParam(param_did)) => {
1317                 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1318                 let param_name = tcx.type_parameter_def(param_node_id).name;
1319                 match self.find_bound_for_assoc_item(param_node_id,
1320                                                      param_name,
1321                                                      assoc_name,
1322                                                      span) {
1323                     Ok(bound) => bound,
1324                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1325                 }
1326             }
1327             _ => {
1328                 // Don't print TyErr to the user.
1329                 if !ty.references_error() {
1330                     self.report_ambiguous_associated_type(span,
1331                                                           &ty.to_string(),
1332                                                           "Trait",
1333                                                           &assoc_name.as_str());
1334                 }
1335                 return (tcx.types.err, Def::Err);
1336             }
1337         };
1338
1339         let trait_did = bound.0.def_id;
1340         let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1341
1342         let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
1343         let def_id = item.expect("missing associated type").def_id;
1344         tcx.check_stability(def_id, ref_id, span);
1345         (ty, Def::AssociatedTy(def_id))
1346     }
1347
1348     fn qpath_to_ty(&self,
1349                    rscope: &RegionScope,
1350                    span: Span,
1351                    opt_self_ty: Option<Ty<'tcx>>,
1352                    trait_def_id: DefId,
1353                    trait_segment: &hir::PathSegment,
1354                    item_segment: &hir::PathSegment)
1355                    -> Ty<'tcx>
1356     {
1357         let tcx = self.tcx();
1358
1359         tcx.prohibit_type_params(slice::ref_slice(item_segment));
1360
1361         let self_ty = if let Some(ty) = opt_self_ty {
1362             ty
1363         } else {
1364             let path_str = tcx.item_path_str(trait_def_id);
1365             self.report_ambiguous_associated_type(span,
1366                                                   "Type",
1367                                                   &path_str,
1368                                                   &item_segment.name.as_str());
1369             return tcx.types.err;
1370         };
1371
1372         debug!("qpath_to_ty: self_type={:?}", self_ty);
1373
1374         let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1375                                                         span,
1376                                                         trait_def_id,
1377                                                         self_ty,
1378                                                         trait_segment);
1379
1380         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1381
1382         self.projected_ty(span, trait_ref, item_segment.name)
1383     }
1384
1385     /// Convert a type supplied as value for a type argument from AST into our
1386     /// our internal representation. This is the same as `ast_ty_to_ty` but that
1387     /// it applies the object lifetime default.
1388     ///
1389     /// # Parameters
1390     ///
1391     /// * `this`, `rscope`: the surrounding context
1392     /// * `def`: the type parameter being instantiated (if available)
1393     /// * `region_substs`: a partial substitution consisting of
1394     ///   only the region type parameters being supplied to this type.
1395     /// * `ast_ty`: the ast representation of the type being supplied
1396     fn ast_ty_arg_to_ty(&self,
1397                         rscope: &RegionScope,
1398                         def: Option<&ty::TypeParameterDef<'tcx>>,
1399                         region_substs: &[Kind<'tcx>],
1400                         ast_ty: &hir::Ty)
1401                         -> Ty<'tcx>
1402     {
1403         let tcx = self.tcx();
1404
1405         if let Some(def) = def {
1406             let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1407             let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1408             self.ast_ty_to_ty(rscope1, ast_ty)
1409         } else {
1410             self.ast_ty_to_ty(rscope, ast_ty)
1411         }
1412     }
1413
1414     // Check a type Path and convert it to a Ty.
1415     pub fn def_to_ty(&self,
1416                      rscope: &RegionScope,
1417                      opt_self_ty: Option<Ty<'tcx>>,
1418                      path: &hir::Path,
1419                      path_id: ast::NodeId,
1420                      permit_variants: bool)
1421                      -> Ty<'tcx> {
1422         let tcx = self.tcx();
1423
1424         debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1425                path.def, opt_self_ty, path.segments);
1426
1427         let span = path.span;
1428         match path.def {
1429             Def::Trait(trait_def_id) => {
1430                 // N.B. this case overlaps somewhat with
1431                 // TyObjectSum, see that fn for details
1432
1433                 assert_eq!(opt_self_ty, None);
1434                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1435
1436                 self.trait_path_to_object_type(rscope,
1437                                                span,
1438                                                trait_def_id,
1439                                                path_id,
1440                                                path.segments.last().unwrap(),
1441                                                span,
1442                                                partition_bounds(&[]))
1443             }
1444             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1445                 assert_eq!(opt_self_ty, None);
1446                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1447                 self.ast_path_to_ty(rscope, span, did, path.segments.last().unwrap())
1448             }
1449             Def::Variant(did) if permit_variants => {
1450                 // Convert "variant type" as if it were a real type.
1451                 // The resulting `Ty` is type of the variant's enum for now.
1452                 assert_eq!(opt_self_ty, None);
1453                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1454                 self.ast_path_to_ty(rscope,
1455                                     span,
1456                                     tcx.parent_def_id(did).unwrap(),
1457                                     path.segments.last().unwrap())
1458             }
1459             Def::TyParam(did) => {
1460                 assert_eq!(opt_self_ty, None);
1461                 tcx.prohibit_type_params(&path.segments);
1462
1463                 let node_id = tcx.map.as_local_node_id(did).unwrap();
1464                 let param = tcx.ty_param_defs.borrow().get(&node_id)
1465                                .map(ty::ParamTy::for_def);
1466                 if let Some(p) = param {
1467                     p.to_ty(tcx)
1468                 } else {
1469                     // Only while computing defaults of earlier type
1470                     // parameters can a type parameter be missing its def.
1471                     struct_span_err!(tcx.sess, span, E0128,
1472                                      "type parameters with a default cannot use \
1473                                       forward declared identifiers")
1474                         .span_label(span, &format!("defaulted type parameters \
1475                                                     cannot be forward declared"))
1476                         .emit();
1477                     tcx.types.err
1478                 }
1479             }
1480             Def::SelfTy(_, Some(def_id)) => {
1481                 // Self in impl (we know the concrete type).
1482
1483                 assert_eq!(opt_self_ty, None);
1484                 tcx.prohibit_type_params(&path.segments);
1485                 let ty = tcx.item_type(def_id);
1486                 if let Some(free_substs) = self.get_free_substs() {
1487                     ty.subst(tcx, free_substs)
1488                 } else {
1489                     ty
1490                 }
1491             }
1492             Def::SelfTy(Some(_), None) => {
1493                 // Self in trait.
1494                 assert_eq!(opt_self_ty, None);
1495                 tcx.prohibit_type_params(&path.segments);
1496                 tcx.mk_self_type()
1497             }
1498             Def::AssociatedTy(def_id) => {
1499                 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1500                 let trait_did = tcx.parent_def_id(def_id).unwrap();
1501                 self.qpath_to_ty(rscope,
1502                                  span,
1503                                  opt_self_ty,
1504                                  trait_did,
1505                                  &path.segments[path.segments.len()-2],
1506                                  path.segments.last().unwrap())
1507             }
1508             Def::PrimTy(prim_ty) => {
1509                 assert_eq!(opt_self_ty, None);
1510                 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1511             }
1512             Def::Err => {
1513                 self.set_tainted_by_errors();
1514                 return self.tcx().types.err;
1515             }
1516             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1517         }
1518     }
1519
1520     /// Parses the programmer's textual representation of a type into our
1521     /// internal notion of a type.
1522     pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1523         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1524                ast_ty.id, ast_ty);
1525
1526         let tcx = self.tcx();
1527
1528         let cache = self.ast_ty_to_ty_cache();
1529         if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1530             return ty;
1531         }
1532
1533         let result_ty = match ast_ty.node {
1534             hir::TySlice(ref ty) => {
1535                 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1536             }
1537             hir::TyObjectSum(ref ty, ref bounds) => {
1538                 self.ast_ty_to_object_trait_ref(rscope, ast_ty.span, ty, bounds)
1539             }
1540             hir::TyPtr(ref mt) => {
1541                 tcx.mk_ptr(ty::TypeAndMut {
1542                     ty: self.ast_ty_to_ty(rscope, &mt.ty),
1543                     mutbl: mt.mutbl
1544                 })
1545             }
1546             hir::TyRptr(ref region, ref mt) => {
1547                 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, region);
1548                 debug!("TyRef r={:?}", r);
1549                 let rscope1 =
1550                     &ObjectLifetimeDefaultRscope::new(
1551                         rscope,
1552                         ty::ObjectLifetimeDefault::Specific(r));
1553                 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1554                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1555             }
1556             hir::TyNever => {
1557                 tcx.types.never
1558             },
1559             hir::TyTup(ref fields) => {
1560                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(rscope, &t)))
1561             }
1562             hir::TyBareFn(ref bf) => {
1563                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1564                 let anon_scope = rscope.anon_type_scope();
1565                 let bare_fn_ty = self.ty_of_method_or_bare_fn(bf.unsafety,
1566                                                               bf.abi,
1567                                                               None,
1568                                                               &bf.decl,
1569                                                               None,
1570                                                               anon_scope,
1571                                                               anon_scope);
1572
1573                 // Find any late-bound regions declared in return type that do
1574                 // not appear in the arguments. These are not wellformed.
1575                 //
1576                 // Example:
1577                 //
1578                 //     for<'a> fn() -> &'a str <-- 'a is bad
1579                 //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1580                 //
1581                 // Note that we do this check **here** and not in
1582                 // `ty_of_bare_fn` because the latter is also used to make
1583                 // the types for fn items, and we do not want to issue a
1584                 // warning then. (Once we fix #32330, the regions we are
1585                 // checking for here would be considered early bound
1586                 // anyway.)
1587                 let inputs = bare_fn_ty.sig.inputs();
1588                 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1589                     &inputs.map_bound(|i| i.to_owned()));
1590                 let output = bare_fn_ty.sig.output();
1591                 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1592                 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1593                     let br_name = match *br {
1594                         ty::BrNamed(_, name, _) => name,
1595                         _ => {
1596                             span_bug!(
1597                                 bf.decl.output.span(),
1598                                 "anonymous bound region {:?} in return but not args",
1599                                 br);
1600                         }
1601                     };
1602                     tcx.sess.add_lint(
1603                         lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1604                         ast_ty.id,
1605                         ast_ty.span,
1606                         format!("return type references lifetime `{}`, \
1607                                  which does not appear in the trait input types",
1608                                 br_name));
1609                 }
1610                 tcx.mk_fn_ptr(bare_fn_ty)
1611             }
1612             hir::TyPolyTraitRef(ref bounds) => {
1613                 self.conv_object_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1614             }
1615             hir::TyImplTrait(ref bounds) => {
1616                 use collect::{compute_bounds, SizedByDefault};
1617
1618                 // Create the anonymized type.
1619                 let def_id = tcx.map.local_def_id(ast_ty.id);
1620                 if let Some(anon_scope) = rscope.anon_type_scope() {
1621                     let substs = anon_scope.fresh_substs(self, ast_ty.span);
1622                     let ty = tcx.mk_anon(tcx.map.local_def_id(ast_ty.id), substs);
1623
1624                     // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1625                     let bounds = compute_bounds(self, ty, bounds,
1626                                                 SizedByDefault::Yes,
1627                                                 Some(anon_scope),
1628                                                 ast_ty.span);
1629                     let predicates = bounds.predicates(tcx, ty);
1630                     let predicates = tcx.lift_to_global(&predicates).unwrap();
1631                     tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1632                         parent: None,
1633                         predicates: predicates
1634                     });
1635
1636                     ty
1637                 } else {
1638                     span_err!(tcx.sess, ast_ty.span, E0562,
1639                               "`impl Trait` not allowed outside of function \
1640                                and inherent method return types");
1641                     tcx.types.err
1642                 }
1643             }
1644             hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1645                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1646                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1647                     self.ast_ty_to_ty(rscope, qself)
1648                 });
1649                 self.def_to_ty(rscope, opt_self_ty, path, ast_ty.id, false)
1650             }
1651             hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1652                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1653                 let ty = self.ast_ty_to_ty(rscope, qself);
1654
1655                 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1656                     path.def
1657                 } else {
1658                     Def::Err
1659                 };
1660                 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1661             }
1662             hir::TyArray(ref ty, length) => {
1663                 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1664                     tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), length)
1665                 } else {
1666                     self.tcx().types.err
1667                 }
1668             }
1669             hir::TyTypeof(ref _e) => {
1670                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1671                                  "`typeof` is a reserved keyword but unimplemented")
1672                     .span_label(ast_ty.span, &format!("reserved keyword"))
1673                     .emit();
1674
1675                 tcx.types.err
1676             }
1677             hir::TyInfer => {
1678                 // TyInfer also appears as the type of arguments or return
1679                 // values in a ExprClosure, or as
1680                 // the type of local variables. Both of these cases are
1681                 // handled specially and will not descend into this routine.
1682                 self.ty_infer(ast_ty.span)
1683             }
1684         };
1685
1686         cache.borrow_mut().insert(ast_ty.id, result_ty);
1687
1688         result_ty
1689     }
1690
1691     pub fn ty_of_arg(&self,
1692                      rscope: &RegionScope,
1693                      ty: &hir::Ty,
1694                      expected_ty: Option<Ty<'tcx>>)
1695                      -> Ty<'tcx>
1696     {
1697         match ty.node {
1698             hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1699             hir::TyInfer => self.ty_infer(ty.span),
1700             _ => self.ast_ty_to_ty(rscope, ty),
1701         }
1702     }
1703
1704     pub fn ty_of_method(&self,
1705                         sig: &hir::MethodSig,
1706                         opt_self_value_ty: Option<Ty<'tcx>>,
1707                         body: Option<hir::BodyId>,
1708                         anon_scope: Option<AnonTypeScope>)
1709                         -> &'tcx ty::BareFnTy<'tcx> {
1710         self.ty_of_method_or_bare_fn(sig.unsafety,
1711                                      sig.abi,
1712                                      opt_self_value_ty,
1713                                      &sig.decl,
1714                                      body,
1715                                      None,
1716                                      anon_scope)
1717     }
1718
1719     pub fn ty_of_bare_fn(&self,
1720                          unsafety: hir::Unsafety,
1721                          abi: abi::Abi,
1722                          decl: &hir::FnDecl,
1723                          body: hir::BodyId,
1724                          anon_scope: Option<AnonTypeScope>)
1725                          -> &'tcx ty::BareFnTy<'tcx> {
1726         self.ty_of_method_or_bare_fn(unsafety, abi, None, decl, Some(body), None, anon_scope)
1727     }
1728
1729     fn ty_of_method_or_bare_fn(&self,
1730                                unsafety: hir::Unsafety,
1731                                abi: abi::Abi,
1732                                opt_self_value_ty: Option<Ty<'tcx>>,
1733                                decl: &hir::FnDecl,
1734                                body: Option<hir::BodyId>,
1735                                arg_anon_scope: Option<AnonTypeScope>,
1736                                ret_anon_scope: Option<AnonTypeScope>)
1737                                -> &'tcx ty::BareFnTy<'tcx>
1738     {
1739         debug!("ty_of_method_or_bare_fn");
1740
1741         // New region names that appear inside of the arguments of the function
1742         // declaration are bound to that function type.
1743         let rb = MaybeWithAnonTypes::new(BindingRscope::new(), arg_anon_scope);
1744
1745         let input_tys: Vec<Ty> =
1746             decl.inputs.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1747
1748         let has_self = opt_self_value_ty.is_some();
1749         let explicit_self = opt_self_value_ty.map(|self_value_ty| {
1750             ExplicitSelf::determine(self_value_ty, input_tys[0])
1751         });
1752
1753         let implied_output_region = match explicit_self {
1754             // `implied_output_region` is the region that will be assumed for any
1755             // region parameters in the return type. In accordance with the rules for
1756             // lifetime elision, we can determine it in two ways. First (determined
1757             // here), if self is by-reference, then the implied output region is the
1758             // region of the self parameter.
1759             Some(ExplicitSelf::ByReference(region, _)) => Ok(*region),
1760
1761             // Second, if there was exactly one lifetime (either a substitution or a
1762             // reference) in the arguments, then any anonymous regions in the output
1763             // have that lifetime.
1764             _ => {
1765                 let arg_tys = &input_tys[has_self as usize..];
1766                 let arg_params = has_self as usize..input_tys.len();
1767                 self.find_implied_output_region(arg_tys, body, arg_params)
1768
1769             }
1770         };
1771
1772         let output_ty = match decl.output {
1773             hir::Return(ref output) =>
1774                 self.convert_ty_with_lifetime_elision(implied_output_region,
1775                                                       &output,
1776                                                       ret_anon_scope),
1777             hir::DefaultReturn(..) => self.tcx().mk_nil(),
1778         };
1779
1780         debug!("ty_of_method_or_bare_fn: output_ty={:?}", output_ty);
1781
1782         self.tcx().mk_bare_fn(ty::BareFnTy {
1783             unsafety: unsafety,
1784             abi: abi,
1785             sig: ty::Binder(self.tcx().mk_fn_sig(
1786                 input_tys.into_iter(),
1787                 output_ty,
1788                 decl.variadic
1789             )),
1790         })
1791     }
1792
1793     pub fn ty_of_closure(&self,
1794         unsafety: hir::Unsafety,
1795         decl: &hir::FnDecl,
1796         abi: abi::Abi,
1797         expected_sig: Option<ty::FnSig<'tcx>>)
1798         -> ty::ClosureTy<'tcx>
1799     {
1800         debug!("ty_of_closure(expected_sig={:?})",
1801                expected_sig);
1802
1803         // new region names that appear inside of the fn decl are bound to
1804         // that function type
1805         let rb = rscope::BindingRscope::new();
1806
1807         let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1808             let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1809                 // no guarantee that the correct number of expected args
1810                 // were supplied
1811                 if i < e.inputs().len() {
1812                     Some(e.inputs()[i])
1813                 } else {
1814                     None
1815                 }
1816             });
1817             self.ty_of_arg(&rb, a, expected_arg_ty)
1818         });
1819
1820         let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1821
1822         let is_infer = match decl.output {
1823             hir::Return(ref output) if output.node == hir::TyInfer => true,
1824             hir::DefaultReturn(..) => true,
1825             _ => false
1826         };
1827
1828         let output_ty = match decl.output {
1829             _ if is_infer && expected_ret_ty.is_some() =>
1830                 expected_ret_ty.unwrap(),
1831             _ if is_infer => self.ty_infer(decl.output.span()),
1832             hir::Return(ref output) =>
1833                 self.ast_ty_to_ty(&rb, &output),
1834             hir::DefaultReturn(..) => bug!(),
1835         };
1836
1837         debug!("ty_of_closure: output_ty={:?}", output_ty);
1838
1839         ty::ClosureTy {
1840             unsafety: unsafety,
1841             abi: abi,
1842             sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1843         }
1844     }
1845
1846     fn conv_object_ty_poly_trait_ref(&self,
1847         rscope: &RegionScope,
1848         span: Span,
1849         ast_bounds: &[hir::TyParamBound])
1850         -> Ty<'tcx>
1851     {
1852         let mut partitioned_bounds = partition_bounds(ast_bounds);
1853
1854         let trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1855             partitioned_bounds.trait_bounds.remove(0)
1856         } else {
1857             span_err!(self.tcx().sess, span, E0224,
1858                       "at least one non-builtin trait is required for an object type");
1859             return self.tcx().types.err;
1860         };
1861
1862         let trait_ref = &trait_bound.trait_ref;
1863         let trait_def_id = self.trait_def_id(trait_ref);
1864         self.trait_path_to_object_type(rscope,
1865                                        trait_ref.path.span,
1866                                        trait_def_id,
1867                                        trait_ref.ref_id,
1868                                        trait_ref.path.segments.last().unwrap(),
1869                                        span,
1870                                        partitioned_bounds)
1871     }
1872
1873     /// Given the bounds on an object, determines what single region bound (if any) we can
1874     /// use to summarize this type. The basic idea is that we will use the bound the user
1875     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1876     /// for region bounds. It may be that we can derive no bound at all, in which case
1877     /// we return `None`.
1878     fn compute_object_lifetime_bound(&self,
1879         span: Span,
1880         explicit_region_bounds: &[&hir::Lifetime],
1881         existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1882         -> Option<&'tcx ty::Region> // if None, use the default
1883     {
1884         let tcx = self.tcx();
1885
1886         debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
1887                existential_predicates={:?})",
1888                explicit_region_bounds,
1889                existential_predicates);
1890
1891         if explicit_region_bounds.len() > 1 {
1892             span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
1893                 "only a single explicit lifetime bound is permitted");
1894         }
1895
1896         if let Some(&r) = explicit_region_bounds.get(0) {
1897             // Explicitly specified region bound. Use that.
1898             return Some(ast_region_to_region(tcx, r));
1899         }
1900
1901         if let Some(principal) = existential_predicates.principal() {
1902             if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1903                 return Some(tcx.mk_region(ty::ReStatic));
1904             }
1905         }
1906
1907         // No explicit region bound specified. Therefore, examine trait
1908         // bounds and see if we can derive region bounds from those.
1909         let derived_region_bounds =
1910             object_region_bounds(tcx, existential_predicates);
1911
1912         // If there are no derived region bounds, then report back that we
1913         // can find no region bound. The caller will use the default.
1914         if derived_region_bounds.is_empty() {
1915             return None;
1916         }
1917
1918         // If any of the derived region bounds are 'static, that is always
1919         // the best choice.
1920         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1921             return Some(tcx.mk_region(ty::ReStatic));
1922         }
1923
1924         // Determine whether there is exactly one unique region in the set
1925         // of derived region bounds. If so, use that. Otherwise, report an
1926         // error.
1927         let r = derived_region_bounds[0];
1928         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1929             span_err!(tcx.sess, span, E0227,
1930                       "ambiguous lifetime bound, explicit lifetime bound required");
1931         }
1932         return Some(r);
1933     }
1934 }
1935
1936 pub struct PartitionedBounds<'a> {
1937     pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
1938     pub region_bounds: Vec<&'a hir::Lifetime>,
1939 }
1940
1941 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1942 /// remaining general trait bounds.
1943 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1944                                          trait_bounds: Vec<&'b hir::PolyTraitRef>)
1945     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1946 {
1947     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.into_iter().partition(|bound| {
1948         match bound.trait_ref.path.def {
1949             Def::Trait(trait_did) => {
1950                 // Checks whether `trait_did` refers to one of the builtin
1951                 // traits, like `Send`, and adds it to `auto_traits` if so.
1952                 if Some(trait_did) == tcx.lang_items.send_trait() ||
1953                     Some(trait_did) == tcx.lang_items.sync_trait() {
1954                     let segments = &bound.trait_ref.path.segments;
1955                     let parameters = &segments[segments.len() - 1].parameters;
1956                     if !parameters.types().is_empty() {
1957                         check_type_argument_count(tcx, bound.trait_ref.path.span,
1958                                                   parameters.types().len(), &[]);
1959                     }
1960                     if !parameters.lifetimes().is_empty() {
1961                         report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1962                                                      parameters.lifetimes().len(), 0);
1963                     }
1964                     true
1965                 } else {
1966                     false
1967                 }
1968             }
1969             _ => false
1970         }
1971     });
1972
1973     let auto_traits = auto_traits.into_iter().map(|tr| {
1974         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1975             trait_did
1976         } else {
1977             unreachable!()
1978         }
1979     }).collect::<Vec<_>>();
1980
1981     (auto_traits, trait_bounds)
1982 }
1983
1984 /// Divides a list of bounds from the AST into two groups: general trait bounds and region bounds
1985 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(ast_bounds: &'b [hir::TyParamBound])
1986     -> PartitionedBounds<'b>
1987 {
1988     let mut region_bounds = Vec::new();
1989     let mut trait_bounds = Vec::new();
1990     for ast_bound in ast_bounds {
1991         match *ast_bound {
1992             hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
1993                 trait_bounds.push(b);
1994             }
1995             hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
1996             hir::RegionTyParamBound(ref l) => {
1997                 region_bounds.push(l);
1998             }
1999         }
2000     }
2001
2002     PartitionedBounds {
2003         trait_bounds: trait_bounds,
2004         region_bounds: region_bounds,
2005     }
2006 }
2007
2008 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
2009                              ty_param_defs: &[ty::TypeParameterDef]) {
2010     let accepted = ty_param_defs.len();
2011     let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
2012     if supplied < required {
2013         let expected = if required < accepted {
2014             "expected at least"
2015         } else {
2016             "expected"
2017         };
2018         let arguments_plural = if required == 1 { "" } else { "s" };
2019
2020         struct_span_err!(tcx.sess, span, E0243,
2021                 "wrong number of type arguments: {} {}, found {}",
2022                 expected, required, supplied)
2023             .span_label(span,
2024                 &format!("{} {} type argument{}",
2025                     expected,
2026                     required,
2027                     arguments_plural))
2028             .emit();
2029     } else if supplied > accepted {
2030         let expected = if required < accepted {
2031             format!("expected at most {}", accepted)
2032         } else {
2033             format!("expected {}", accepted)
2034         };
2035         let arguments_plural = if accepted == 1 { "" } else { "s" };
2036
2037         struct_span_err!(tcx.sess, span, E0244,
2038                 "wrong number of type arguments: {}, found {}",
2039                 expected, supplied)
2040             .span_label(
2041                 span,
2042                 &format!("{} type argument{}",
2043                     if accepted == 0 { "expected no" } else { &expected },
2044                     arguments_plural)
2045             )
2046             .emit();
2047     }
2048 }
2049
2050 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
2051     let label = if number < expected {
2052         if expected == 1 {
2053             format!("expected {} lifetime parameter", expected)
2054         } else {
2055             format!("expected {} lifetime parameters", expected)
2056         }
2057     } else {
2058         let additional = number - expected;
2059         if additional == 1 {
2060             "unexpected lifetime parameter".to_string()
2061         } else {
2062             format!("{} unexpected lifetime parameters", additional)
2063         }
2064     };
2065     struct_span_err!(tcx.sess, span, E0107,
2066                      "wrong number of lifetime parameters: expected {}, found {}",
2067                      expected, number)
2068         .span_label(span, &label)
2069         .emit();
2070 }
2071
2072 // A helper struct for conveniently grouping a set of bounds which we pass to
2073 // and return from functions in multiple places.
2074 #[derive(PartialEq, Eq, Clone, Debug)]
2075 pub struct Bounds<'tcx> {
2076     pub region_bounds: Vec<&'tcx ty::Region>,
2077     pub implicitly_sized: bool,
2078     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2079     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2080 }
2081
2082 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2083     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2084                       -> Vec<ty::Predicate<'tcx>>
2085     {
2086         let mut vec = Vec::new();
2087
2088         // If it could be sized, and is, add the sized predicate
2089         if self.implicitly_sized {
2090             if let Some(sized) = tcx.lang_items.sized_trait() {
2091                 let trait_ref = ty::TraitRef {
2092                     def_id: sized,
2093                     substs: tcx.mk_substs_trait(param_ty, &[])
2094                 };
2095                 vec.push(trait_ref.to_predicate());
2096             }
2097         }
2098
2099         for &region_bound in &self.region_bounds {
2100             // account for the binder being introduced below; no need to shift `param_ty`
2101             // because, at present at least, it can only refer to early-bound regions
2102             let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
2103             vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2104         }
2105
2106         for bound_trait_ref in &self.trait_bounds {
2107             vec.push(bound_trait_ref.to_predicate());
2108         }
2109
2110         for projection in &self.projection_bounds {
2111             vec.push(projection.to_predicate());
2112         }
2113
2114         vec
2115     }
2116 }
2117
2118 pub enum ExplicitSelf<'tcx> {
2119     ByValue,
2120     ByReference(&'tcx ty::Region, hir::Mutability),
2121     ByBox
2122 }
2123
2124 impl<'tcx> ExplicitSelf<'tcx> {
2125     /// We wish to (for now) categorize an explicit self
2126     /// declaration like `self: SomeType` into either `self`,
2127     /// `&self`, `&mut self`, or `Box<self>`. We do this here
2128     /// by some simple pattern matching. A more precise check
2129     /// is done later in `check_method_self_type()`.
2130     ///
2131     /// Examples:
2132     ///
2133     /// ```
2134     /// impl Foo for &T {
2135     ///     // Legal declarations:
2136     ///     fn method1(self: &&T); // ExplicitSelf::ByReference
2137     ///     fn method2(self: &T); // ExplicitSelf::ByValue
2138     ///     fn method3(self: Box<&T>); // ExplicitSelf::ByBox
2139     ///
2140     ///     // Invalid cases will be caught later by `check_method_self_type`:
2141     ///     fn method_err1(self: &mut T); // ExplicitSelf::ByReference
2142     /// }
2143     /// ```
2144     ///
2145     /// To do the check we just count the number of "modifiers"
2146     /// on each type and compare them. If they are the same or
2147     /// the impl has more, we call it "by value". Otherwise, we
2148     /// look at the outermost modifier on the method decl and
2149     /// call it by-ref, by-box as appropriate. For method1, for
2150     /// example, the impl type has one modifier, but the method
2151     /// type has two, so we end up with
2152     /// ExplicitSelf::ByReference.
2153     pub fn determine(untransformed_self_ty: Ty<'tcx>,
2154                      self_arg_ty: Ty<'tcx>)
2155                      -> ExplicitSelf<'tcx> {
2156         fn count_modifiers(ty: Ty) -> usize {
2157             match ty.sty {
2158                 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
2159                 ty::TyBox(t) => count_modifiers(t) + 1,
2160                 _ => 0,
2161             }
2162         }
2163
2164         let impl_modifiers = count_modifiers(untransformed_self_ty);
2165         let method_modifiers = count_modifiers(self_arg_ty);
2166
2167         if impl_modifiers >= method_modifiers {
2168             ExplicitSelf::ByValue
2169         } else {
2170             match self_arg_ty.sty {
2171                 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
2172                 ty::TyBox(_) => ExplicitSelf::ByBox,
2173                 _ => ExplicitSelf::ByValue,
2174             }
2175         }
2176     }
2177 }