]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Add test for MIR range matching.
[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_scheme()`
20 //! function triggers a recursive call to `type_scheme_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_scheme()` just looks up the item type in
24 //! `tcx.tcache` (using `ty::lookup_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 middle::astconv_util::{prim_ty_to_ty, prohibit_type_params, prohibit_projection};
52 use middle::const_eval::{self, ConstVal};
53 use middle::const_eval::EvalHint::UncheckedExprHint;
54 use middle::def;
55 use middle::def_id::DefId;
56 use middle::resolve_lifetime as rl;
57 use middle::privacy::{AllPublic, LastMod};
58 use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs, ParamSpace};
59 use middle::traits;
60 use middle::ty::{self, Ty, ToPredicate, HasTypeFlags};
61 use middle::ty::wf::object_region_bounds;
62 use require_c_abi_if_variadic;
63 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
64              ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
65              ElisionFailureInfo, ElidedLifetime};
66 use util::common::{ErrorReported, FN_OUTPUT_NAME};
67 use util::nodemap::FnvHashSet;
68
69 use syntax::{abi, ast};
70 use syntax::codemap::{Span, Pos};
71 use syntax::feature_gate::{GateIssue, emit_feature_err};
72 use syntax::parse::token;
73
74 use rustc_front::print::pprust;
75 use rustc_front::hir;
76 use rustc_back::slice;
77
78 pub trait AstConv<'tcx> {
79     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
80
81     /// Identify the type scheme for an item with a type, like a type
82     /// alias, fn, or struct. This allows you to figure out the set of
83     /// type parameters defined on the item.
84     fn get_item_type_scheme(&self, span: Span, id: DefId)
85                             -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
86
87     /// Returns the `TraitDef` for a given trait. This allows you to
88     /// figure out the set of type parameters defined on the trait.
89     fn get_trait_def(&self, span: Span, id: DefId)
90                      -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
91
92     /// Ensure that the super-predicates for the trait with the given
93     /// id are available and also for the transitive set of
94     /// super-predicates.
95     fn ensure_super_predicates(&self, span: Span, id: DefId)
96                                -> Result<(), ErrorReported>;
97
98     /// Returns the set of bounds in scope for the type parameter with
99     /// the given id.
100     fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
101                                  -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
102
103     /// Returns true if the trait with id `trait_def_id` defines an
104     /// associated type with the name `name`.
105     fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
106                                            -> bool;
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         None
114     }
115
116     /// What type should we use when a type is omitted?
117         fn ty_infer(&self,
118                     param_and_substs: Option<ty::TypeParameterDef<'tcx>>,
119                     substs: Option<&mut Substs<'tcx>>,
120                     space: Option<ParamSpace>,
121                     span: Span) -> Ty<'tcx>;
122
123     /// Projecting an associated type from a (potentially)
124     /// higher-ranked trait reference is more complicated, because of
125     /// the possibility of late-bound regions appearing in the
126     /// associated type binding. This is not legal in function
127     /// signatures for that reason. In a function body, we can always
128     /// handle it because we can use inference variables to remove the
129     /// late-bound regions.
130     fn projected_ty_from_poly_trait_ref(&self,
131                                         span: Span,
132                                         poly_trait_ref: ty::PolyTraitRef<'tcx>,
133                                         item_name: ast::Name)
134                                         -> Ty<'tcx>
135     {
136         if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
137             self.projected_ty(span, trait_ref, item_name)
138         } else {
139             // no late-bound regions, we can just ignore the binder
140             span_err!(self.tcx().sess, span, E0212,
141                 "cannot extract an associated type from a higher-ranked trait bound \
142                  in this context");
143             self.tcx().types.err
144         }
145     }
146
147     /// Project an associated type from a non-higher-ranked trait reference.
148     /// This is fairly straightforward and can be accommodated in any context.
149     fn projected_ty(&self,
150                     span: Span,
151                     _trait_ref: ty::TraitRef<'tcx>,
152                     _item_name: ast::Name)
153                     -> Ty<'tcx>;
154 }
155
156 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &hir::Lifetime)
157                             -> ty::Region {
158     let r = match tcx.named_region_map.get(&lifetime.id) {
159         None => {
160             // should have been recorded by the `resolve_lifetime` pass
161             tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
162         }
163
164         Some(&rl::DefStaticRegion) => {
165             ty::ReStatic
166         }
167
168         Some(&rl::DefLateBoundRegion(debruijn, id)) => {
169             ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id), lifetime.name))
170         }
171
172         Some(&rl::DefEarlyBoundRegion(space, index, _)) => {
173             ty::ReEarlyBound(ty::EarlyBoundRegion {
174                 space: space,
175                 index: index,
176                 name: lifetime.name
177             })
178         }
179
180         Some(&rl::DefFreeRegion(scope, id)) => {
181             ty::ReFree(ty::FreeRegion {
182                     scope: scope.to_code_extent(&tcx.region_maps),
183                     bound_region: ty::BrNamed(tcx.map.local_def_id(id),
184                                               lifetime.name)
185                 })
186         }
187     };
188
189     debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
190            lifetime,
191            lifetime.id,
192            r);
193
194     r
195 }
196
197 fn report_elision_failure(
198     tcx: &ty::ctxt,
199     default_span: Span,
200     params: Vec<ElisionFailureInfo>)
201 {
202     let mut m = String::new();
203     let len = params.len();
204     let mut any_lifetimes = false;
205
206     for (i, info) in params.into_iter().enumerate() {
207         let ElisionFailureInfo {
208             name, lifetime_count: n, have_bound_regions
209         } = info;
210
211         any_lifetimes = any_lifetimes || (n > 0);
212
213         let help_name = if name.is_empty() {
214             format!("argument {}", i + 1)
215         } else {
216             format!("`{}`", name)
217         };
218
219         m.push_str(&(if n == 1 {
220             help_name
221         } else {
222             format!("one of {}'s {} elided {}lifetimes", help_name, n,
223                     if have_bound_regions { "free " } else { "" } )
224         })[..]);
225
226         if len == 2 && i == 0 {
227             m.push_str(" or ");
228         } else if i + 2 == len {
229             m.push_str(", or ");
230         } else if i + 1 != len {
231             m.push_str(", ");
232         }
233     }
234
235     if len == 0 {
236         fileline_help!(tcx.sess, default_span,
237                        "this function's return type contains a borrowed value, but \
238                         there is no value for it to be borrowed from");
239         fileline_help!(tcx.sess, default_span,
240                        "consider giving it a 'static lifetime");
241     } else if !any_lifetimes {
242         fileline_help!(tcx.sess, default_span,
243                        "this function's return type contains a borrowed value with \
244                         an elided lifetime, but the lifetime cannot be derived from \
245                         the arguments");
246         fileline_help!(tcx.sess, default_span,
247                        "consider giving it an explicit bounded or 'static \
248                         lifetime");
249     } else if len == 1 {
250         fileline_help!(tcx.sess, default_span,
251                        "this function's return type contains a borrowed value, but \
252                         the signature does not say which {} it is borrowed from",
253                        m);
254     } else {
255         fileline_help!(tcx.sess, default_span,
256                        "this function's return type contains a borrowed value, but \
257                         the signature does not say whether it is borrowed from {}",
258                        m);
259     }
260 }
261
262 pub fn opt_ast_region_to_region<'tcx>(
263     this: &AstConv<'tcx>,
264     rscope: &RegionScope,
265     default_span: Span,
266     opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
267 {
268     let r = match *opt_lifetime {
269         Some(ref lifetime) => {
270             ast_region_to_region(this.tcx(), lifetime)
271         }
272
273         None => match rscope.anon_regions(default_span, 1) {
274             Ok(rs) => rs[0],
275             Err(params) => {
276                 span_err!(this.tcx().sess, default_span, E0106,
277                           "missing lifetime specifier");
278                 if let Some(params) = params {
279                     report_elision_failure(this.tcx(), default_span, params);
280                 }
281                 ty::ReStatic
282             }
283         }
284     };
285
286     debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
287             opt_lifetime,
288             r);
289
290     r
291 }
292
293 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
294 /// returns an appropriate set of substitutions for this particular reference to `I`.
295 pub fn ast_path_substs_for_ty<'tcx>(
296     this: &AstConv<'tcx>,
297     rscope: &RegionScope,
298     span: Span,
299     param_mode: PathParamMode,
300     decl_generics: &ty::Generics<'tcx>,
301     item_segment: &hir::PathSegment)
302     -> Substs<'tcx>
303 {
304     let tcx = this.tcx();
305
306     // ast_path_substs() is only called to convert paths that are
307     // known to refer to traits, types, or structs. In these cases,
308     // all type parameters defined for the item being referenced will
309     // be in the TypeSpace or SelfSpace.
310     //
311     // Note: in the case of traits, the self parameter is also
312     // defined, but we don't currently create a `type_param_def` for
313     // `Self` because it is implicit.
314     assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
315     assert!(decl_generics.types.all(|d| d.space != FnSpace));
316
317     let (regions, types, assoc_bindings) = match item_segment.parameters {
318         hir::AngleBracketedParameters(ref data) => {
319             convert_angle_bracketed_parameters(this, rscope, span, decl_generics, data)
320         }
321         hir::ParenthesizedParameters(..) => {
322             span_err!(tcx.sess, span, E0214,
323                       "parenthesized parameters may only be used with a trait");
324             let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
325             (Substs::empty(),
326              ty_param_defs.iter().map(|_| tcx.types.err).collect(),
327              vec![])
328         }
329     };
330
331     prohibit_projections(this.tcx(), &assoc_bindings);
332
333     create_substs_for_ast_path(this,
334                                span,
335                                param_mode,
336                                decl_generics,
337                                None,
338                                types,
339                                regions)
340 }
341
342 #[derive(PartialEq, Eq)]
343 pub enum PathParamMode {
344     // Any path in a type context.
345     Explicit,
346     // The `module::Type` in `module::Type::method` in an expression.
347     Optional
348 }
349
350 fn create_region_substs<'tcx>(
351     this: &AstConv<'tcx>,
352     rscope: &RegionScope,
353     span: Span,
354     decl_generics: &ty::Generics<'tcx>,
355     regions_provided: Vec<ty::Region>)
356     -> Substs<'tcx>
357 {
358     let tcx = this.tcx();
359
360     // If the type is parameterized by this region, then replace this
361     // region with the current anon region binding (in other words,
362     // whatever & would get replaced with).
363     let expected_num_region_params = decl_generics.regions.len(TypeSpace);
364     let supplied_num_region_params = regions_provided.len();
365     let regions = if expected_num_region_params == supplied_num_region_params {
366         regions_provided
367     } else {
368         let anon_regions =
369             rscope.anon_regions(span, expected_num_region_params);
370
371         if supplied_num_region_params != 0 || anon_regions.is_err() {
372             report_lifetime_number_error(tcx, span,
373                                          supplied_num_region_params,
374                                          expected_num_region_params);
375         }
376
377         match anon_regions {
378             Ok(anon_regions) => anon_regions,
379             Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
380         }
381     };
382     Substs::new_type(vec![], regions)
383 }
384
385 /// Given the type/region arguments provided to some path (along with
386 /// an implicit Self, if this is a trait reference) returns the complete
387 /// set of substitutions. This may involve applying defaulted type parameters.
388 ///
389 /// Note that the type listing given here is *exactly* what the user provided.
390 ///
391 /// The `region_substs` should be the result of `create_region_substs`
392 /// -- that is, a substitution with no types but the correct number of
393 /// regions.
394 fn create_substs_for_ast_path<'tcx>(
395     this: &AstConv<'tcx>,
396     span: Span,
397     param_mode: PathParamMode,
398     decl_generics: &ty::Generics<'tcx>,
399     self_ty: Option<Ty<'tcx>>,
400     types_provided: Vec<Ty<'tcx>>,
401     region_substs: Substs<'tcx>)
402     -> Substs<'tcx>
403 {
404     let tcx = this.tcx();
405
406     debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}, \
407            types_provided={:?}, region_substs={:?})",
408            decl_generics, self_ty, types_provided,
409            region_substs);
410
411     assert_eq!(region_substs.regions().len(TypeSpace), decl_generics.regions.len(TypeSpace));
412     assert!(region_substs.types.is_empty());
413
414     // Convert the type parameters supplied by the user.
415     let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
416     let formal_ty_param_count = ty_param_defs.len();
417     let required_ty_param_count = ty_param_defs.iter()
418                                                .take_while(|x| x.default.is_none())
419                                                .count();
420
421     let mut type_substs = get_type_substs_for_defs(this,
422                                                    span,
423                                                    types_provided,
424                                                    param_mode,
425                                                    ty_param_defs,
426                                                    region_substs.clone(),
427                                                    self_ty);
428
429     let supplied_ty_param_count = type_substs.len();
430     check_type_argument_count(this.tcx(), span, supplied_ty_param_count,
431                               required_ty_param_count, formal_ty_param_count);
432
433     if supplied_ty_param_count < required_ty_param_count {
434         while type_substs.len() < required_ty_param_count {
435             type_substs.push(tcx.types.err);
436         }
437     } else if supplied_ty_param_count > formal_ty_param_count {
438         type_substs.truncate(formal_ty_param_count);
439     }
440     assert!(type_substs.len() >= required_ty_param_count &&
441             type_substs.len() <= formal_ty_param_count);
442
443     let mut substs = region_substs;
444     substs.types.extend(TypeSpace, type_substs.into_iter());
445
446     match self_ty {
447         None => {
448             // If no self-type is provided, it's still possible that
449             // one was declared, because this could be an object type.
450         }
451         Some(ty) => {
452             // If a self-type is provided, one should have been
453             // "declared" (in other words, this should be a
454             // trait-ref).
455             assert!(decl_generics.types.get_self().is_some());
456             substs.types.push(SelfSpace, ty);
457         }
458     }
459
460     let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
461     for param in &ty_param_defs[actual_supplied_ty_param_count..] {
462         if let Some(default) = param.default {
463             // If we are converting an object type, then the
464             // `Self` parameter is unknown. However, some of the
465             // other type parameters may reference `Self` in their
466             // defaults. This will lead to an ICE if we are not
467             // careful!
468             if self_ty.is_none() && default.has_self_ty() {
469                 span_err!(tcx.sess, span, E0393,
470                           "the type parameter `{}` must be explicitly specified \
471                            in an object type because its default value `{}` references \
472                            the type `Self`",
473                           param.name,
474                           default);
475                 substs.types.push(TypeSpace, tcx.types.err);
476             } else {
477                 // This is a default type parameter.
478                 let default = default.subst_spanned(tcx,
479                                                     &substs,
480                                                     Some(span));
481                 substs.types.push(TypeSpace, default);
482             }
483         } else {
484             tcx.sess.span_bug(span, "extra parameter without default");
485         }
486     }
487
488     debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
489            decl_generics, self_ty, substs);
490
491     substs
492 }
493
494 /// Returns types_provided if it is not empty, otherwise populating the
495 /// type parameters with inference variables as appropriate.
496 fn get_type_substs_for_defs<'tcx>(this: &AstConv<'tcx>,
497                                   span: Span,
498                                   types_provided: Vec<Ty<'tcx>>,
499                                   param_mode: PathParamMode,
500                                   ty_param_defs: &[ty::TypeParameterDef<'tcx>],
501                                   mut substs: Substs<'tcx>,
502                                   self_ty: Option<Ty<'tcx>>)
503                                   -> Vec<Ty<'tcx>>
504 {
505     fn default_type_parameter<'tcx>(p: &ty::TypeParameterDef<'tcx>, self_ty: Option<Ty<'tcx>>)
506                                     -> Option<ty::TypeParameterDef<'tcx>>
507     {
508         if let Some(ref default) = p.default {
509             if self_ty.is_none() && default.has_self_ty() {
510                 // There is no suitable inference default for a type parameter
511                 // that references self with no self-type provided.
512                 return None;
513             }
514         }
515
516         Some(p.clone())
517     }
518
519     if param_mode == PathParamMode::Optional && types_provided.is_empty() {
520         ty_param_defs
521             .iter()
522             .map(|p| this.ty_infer(default_type_parameter(p, self_ty), Some(&mut substs),
523                                    Some(TypeSpace), span))
524             .collect()
525     } else {
526         types_provided
527     }
528 }
529
530 struct ConvertedBinding<'tcx> {
531     item_name: ast::Name,
532     ty: Ty<'tcx>,
533     span: Span,
534 }
535
536 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
537                                             rscope: &RegionScope,
538                                             span: Span,
539                                             decl_generics: &ty::Generics<'tcx>,
540                                             data: &hir::AngleBracketedParameterData)
541                                             -> (Substs<'tcx>,
542                                                 Vec<Ty<'tcx>>,
543                                                 Vec<ConvertedBinding<'tcx>>)
544 {
545     let regions: Vec<_> =
546         data.lifetimes.iter()
547                       .map(|l| ast_region_to_region(this.tcx(), l))
548                       .collect();
549
550     let region_substs =
551         create_region_substs(this, rscope, span, decl_generics, regions);
552
553     let types: Vec<_> =
554         data.types.iter()
555                   .enumerate()
556                   .map(|(i,t)| ast_ty_arg_to_ty(this, rscope, decl_generics,
557                                                 i, &region_substs, t))
558                   .collect();
559
560     let assoc_bindings: Vec<_> =
561         data.bindings.iter()
562                      .map(|b| ConvertedBinding { item_name: b.name,
563                                                  ty: ast_ty_to_ty(this, rscope, &*b.ty),
564                                                  span: b.span })
565                      .collect();
566
567     (region_substs, types, assoc_bindings)
568 }
569
570 /// Returns the appropriate lifetime to use for any output lifetimes
571 /// (if one exists) and a vector of the (pattern, number of lifetimes)
572 /// corresponding to each input type/pattern.
573 fn find_implied_output_region<'tcx>(tcx: &ty::ctxt<'tcx>,
574                                     input_tys: &[Ty<'tcx>],
575                                     input_pats: Vec<String>) -> ElidedLifetime
576 {
577     let mut lifetimes_for_params = Vec::new();
578     let mut possible_implied_output_region = None;
579
580     for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
581         let mut regions = FnvHashSet();
582         let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
583
584         debug!("find_implied_output_regions: collected {:?} from {:?} \
585                 have_bound_regions={:?}", &regions, input_type, have_bound_regions);
586
587         if regions.len() == 1 {
588             // there's a chance that the unique lifetime of this
589             // iteration will be the appropriate lifetime for output
590             // parameters, so lets store it.
591             possible_implied_output_region = regions.iter().cloned().next();
592         }
593
594         lifetimes_for_params.push(ElisionFailureInfo {
595             name: input_pat,
596             lifetime_count: regions.len(),
597             have_bound_regions: have_bound_regions
598         });
599     }
600
601     if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
602         Ok(possible_implied_output_region.unwrap())
603     } else {
604         Err(Some(lifetimes_for_params))
605     }
606 }
607
608 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
609                                           elided_lifetime: ElidedLifetime,
610                                           ty: &hir::Ty)
611                                           -> Ty<'tcx>
612 {
613     match elided_lifetime {
614         Ok(implied_output_region) => {
615             let rb = ElidableRscope::new(implied_output_region);
616             ast_ty_to_ty(this, &rb, ty)
617         }
618         Err(param_lifetimes) => {
619             // All regions must be explicitly specified in the output
620             // if the lifetime elision rules do not apply. This saves
621             // the user from potentially-confusing errors.
622             let rb = UnelidableRscope::new(param_lifetimes);
623             ast_ty_to_ty(this, &rb, ty)
624         }
625     }
626 }
627
628 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
629                                           rscope: &RegionScope,
630                                           span: Span,
631                                           decl_generics: &ty::Generics<'tcx>,
632                                           data: &hir::ParenthesizedParameterData)
633                                           -> (Substs<'tcx>,
634                                               Vec<Ty<'tcx>>,
635                                               Vec<ConvertedBinding<'tcx>>)
636 {
637     let region_substs =
638         create_region_substs(this, rscope, span, decl_generics, Vec::new());
639
640     let binding_rscope = BindingRscope::new();
641     let inputs =
642         data.inputs.iter()
643                    .map(|a_t| ast_ty_arg_to_ty(this, &binding_rscope, decl_generics,
644                                                0, &region_substs, a_t))
645                    .collect::<Vec<Ty<'tcx>>>();
646
647     let input_params = vec![String::new(); inputs.len()];
648     let implied_output_region = find_implied_output_region(this.tcx(), &inputs, input_params);
649
650     let input_ty = this.tcx().mk_tup(inputs);
651
652     let (output, output_span) = match data.output {
653         Some(ref output_ty) => {
654             (convert_ty_with_lifetime_elision(this,
655                                               implied_output_region,
656                                               &output_ty),
657              output_ty.span)
658         }
659         None => {
660             (this.tcx().mk_nil(), data.span)
661         }
662     };
663
664     let output_binding = ConvertedBinding {
665         item_name: token::intern(FN_OUTPUT_NAME),
666         ty: output,
667         span: output_span
668     };
669
670     (region_substs, vec![input_ty], vec![output_binding])
671 }
672
673 pub fn instantiate_poly_trait_ref<'tcx>(
674     this: &AstConv<'tcx>,
675     rscope: &RegionScope,
676     ast_trait_ref: &hir::PolyTraitRef,
677     self_ty: Option<Ty<'tcx>>,
678     poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
679     -> ty::PolyTraitRef<'tcx>
680 {
681     let trait_ref = &ast_trait_ref.trait_ref;
682     let trait_def_id = trait_def_id(this, trait_ref);
683     ast_path_to_poly_trait_ref(this,
684                                rscope,
685                                trait_ref.path.span,
686                                PathParamMode::Explicit,
687                                trait_def_id,
688                                self_ty,
689                                trait_ref.path.segments.last().unwrap(),
690                                poly_projections)
691 }
692
693 /// Instantiates the path for the given trait reference, assuming that it's
694 /// bound to a valid trait type. Returns the def_id for the defining trait.
695 /// Fails if the type is a type other than a trait type.
696 ///
697 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
698 /// are disallowed. Otherwise, they are pushed onto the vector given.
699 pub fn instantiate_mono_trait_ref<'tcx>(
700     this: &AstConv<'tcx>,
701     rscope: &RegionScope,
702     trait_ref: &hir::TraitRef,
703     self_ty: Option<Ty<'tcx>>)
704     -> ty::TraitRef<'tcx>
705 {
706     let trait_def_id = trait_def_id(this, trait_ref);
707     ast_path_to_mono_trait_ref(this,
708                                rscope,
709                                trait_ref.path.span,
710                                PathParamMode::Explicit,
711                                trait_def_id,
712                                self_ty,
713                                trait_ref.path.segments.last().unwrap())
714 }
715
716 fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &hir::TraitRef) -> DefId {
717     let path = &trait_ref.path;
718     match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
719         def::DefTrait(trait_def_id) => trait_def_id,
720         def::DefErr => {
721             this.tcx().sess.fatal("cannot continue compilation due to previous error");
722         }
723         _ => {
724             span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
725                         path);
726         }
727     }
728 }
729
730 fn object_path_to_poly_trait_ref<'a,'tcx>(
731     this: &AstConv<'tcx>,
732     rscope: &RegionScope,
733     span: Span,
734     param_mode: PathParamMode,
735     trait_def_id: DefId,
736     trait_segment: &hir::PathSegment,
737     mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
738     -> ty::PolyTraitRef<'tcx>
739 {
740     ast_path_to_poly_trait_ref(this,
741                                rscope,
742                                span,
743                                param_mode,
744                                trait_def_id,
745                                None,
746                                trait_segment,
747                                projections)
748 }
749
750 fn ast_path_to_poly_trait_ref<'a,'tcx>(
751     this: &AstConv<'tcx>,
752     rscope: &RegionScope,
753     span: Span,
754     param_mode: PathParamMode,
755     trait_def_id: DefId,
756     self_ty: Option<Ty<'tcx>>,
757     trait_segment: &hir::PathSegment,
758     poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
759     -> ty::PolyTraitRef<'tcx>
760 {
761     debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
762     // The trait reference introduces a binding level here, so
763     // we need to shift the `rscope`. It'd be nice if we could
764     // do away with this rscope stuff and work this knowledge
765     // into resolve_lifetimes, as we do with non-omitted
766     // lifetimes. Oh well, not there yet.
767     let shifted_rscope = &ShiftedRscope::new(rscope);
768
769     let (substs, assoc_bindings) =
770         create_substs_for_ast_trait_ref(this,
771                                         shifted_rscope,
772                                         span,
773                                         param_mode,
774                                         trait_def_id,
775                                         self_ty,
776                                         trait_segment);
777     let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
778
779     {
780         let converted_bindings =
781             assoc_bindings
782             .iter()
783             .filter_map(|binding| {
784                 // specify type to assert that error was already reported in Err case:
785                 let predicate: Result<_, ErrorReported> =
786                     ast_type_binding_to_poly_projection_predicate(this,
787                                                                   poly_trait_ref.clone(),
788                                                                   self_ty,
789                                                                   binding);
790                 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
791             });
792         poly_projections.extend(converted_bindings);
793     }
794
795     debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
796            trait_segment, poly_projections, poly_trait_ref);
797     poly_trait_ref
798 }
799
800 fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
801                                        rscope: &RegionScope,
802                                        span: Span,
803                                        param_mode: PathParamMode,
804                                        trait_def_id: DefId,
805                                        self_ty: Option<Ty<'tcx>>,
806                                        trait_segment: &hir::PathSegment)
807                                        -> ty::TraitRef<'tcx>
808 {
809     let (substs, assoc_bindings) =
810         create_substs_for_ast_trait_ref(this,
811                                         rscope,
812                                         span,
813                                         param_mode,
814                                         trait_def_id,
815                                         self_ty,
816                                         trait_segment);
817     prohibit_projections(this.tcx(), &assoc_bindings);
818     ty::TraitRef::new(trait_def_id, substs)
819 }
820
821 fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
822                                             rscope: &RegionScope,
823                                             span: Span,
824                                             param_mode: PathParamMode,
825                                             trait_def_id: DefId,
826                                             self_ty: Option<Ty<'tcx>>,
827                                             trait_segment: &hir::PathSegment)
828                                             -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
829 {
830     debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
831            trait_segment);
832
833     let trait_def = match this.get_trait_def(span, trait_def_id) {
834         Ok(trait_def) => trait_def,
835         Err(ErrorReported) => {
836             // No convenient way to recover from a cycle here. Just bail. Sorry!
837             this.tcx().sess.abort_if_errors();
838             this.tcx().sess.bug("ErrorReported returned, but no errors reports?")
839         }
840     };
841
842     let (regions, types, assoc_bindings) = match trait_segment.parameters {
843         hir::AngleBracketedParameters(ref data) => {
844             // For now, require that parenthetical notation be used
845             // only with `Fn()` etc.
846             if !this.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
847                 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
848                                  "unboxed_closures", span, GateIssue::Language,
849                                  "\
850                     the precise format of `Fn`-family traits' type parameters is \
851                     subject to change. Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
852             }
853
854             convert_angle_bracketed_parameters(this, rscope, span, &trait_def.generics, data)
855         }
856         hir::ParenthesizedParameters(ref data) => {
857             // For now, require that parenthetical notation be used
858             // only with `Fn()` etc.
859             if !this.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
860                 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
861                                  "unboxed_closures", span, GateIssue::Language,
862                                  "\
863                     parenthetical notation is only stable when used with `Fn`-family traits");
864             }
865
866             convert_parenthesized_parameters(this, rscope, span, &trait_def.generics, data)
867         }
868     };
869
870     let substs = create_substs_for_ast_path(this,
871                                             span,
872                                             param_mode,
873                                             &trait_def.generics,
874                                             self_ty,
875                                             types,
876                                             regions);
877
878     (this.tcx().mk_substs(substs), assoc_bindings)
879 }
880
881 fn ast_type_binding_to_poly_projection_predicate<'tcx>(
882     this: &AstConv<'tcx>,
883     mut trait_ref: ty::PolyTraitRef<'tcx>,
884     self_ty: Option<Ty<'tcx>>,
885     binding: &ConvertedBinding<'tcx>)
886     -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
887 {
888     let tcx = this.tcx();
889
890     // Given something like `U : SomeTrait<T=X>`, we want to produce a
891     // predicate like `<U as SomeTrait>::T = X`. This is somewhat
892     // subtle in the event that `T` is defined in a supertrait of
893     // `SomeTrait`, because in that case we need to upcast.
894     //
895     // That is, consider this case:
896     //
897     // ```
898     // trait SubTrait : SuperTrait<int> { }
899     // trait SuperTrait<A> { type T; }
900     //
901     // ... B : SubTrait<T=foo> ...
902     // ```
903     //
904     // We want to produce `<B as SuperTrait<int>>::T == foo`.
905
906     // Simple case: X is defined in the current trait.
907     if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
908         return Ok(ty::Binder(ty::ProjectionPredicate {      // <-------------------+
909             projection_ty: ty::ProjectionTy {               //                     |
910                 trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
911                 item_name: binding.item_name,
912             },
913             ty: binding.ty,
914         }));
915     }
916
917     // Otherwise, we have to walk through the supertraits to find
918     // those that do.  This is complicated by the fact that, for an
919     // object type, the `Self` type is not present in the
920     // substitutions (after all, it's being constructed right now),
921     // but the `supertraits` iterator really wants one. To handle
922     // this, we currently insert a dummy type and then remove it
923     // later. Yuck.
924
925     let dummy_self_ty = tcx.mk_infer(ty::FreshTy(0));
926     if self_ty.is_none() { // if converting for an object type
927         let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
928         assert!(dummy_substs.self_ty().is_none());                     //                    |
929         dummy_substs.types.push(SelfSpace, dummy_self_ty);             //                    |
930         trait_ref = ty::Binder(ty::TraitRef::new(trait_ref.def_id(),   // <------------+
931                                                  tcx.mk_substs(dummy_substs)));
932     }
933
934     try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
935
936     let mut candidates: Vec<ty::PolyTraitRef> =
937         traits::supertraits(tcx, trait_ref.clone())
938         .filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
939         .collect();
940
941     // If converting for an object type, then remove the dummy-ty from `Self` now.
942     // Yuckety yuck.
943     if self_ty.is_none() {
944         for candidate in &mut candidates {
945             let mut dummy_substs = candidate.0.substs.clone();
946             assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
947             dummy_substs.types.pop(SelfSpace);
948             *candidate = ty::Binder(ty::TraitRef::new(candidate.def_id(),
949                                                       tcx.mk_substs(dummy_substs)));
950         }
951     }
952
953     let candidate = try!(one_bound_for_assoc_type(tcx,
954                                                   candidates,
955                                                   &trait_ref.to_string(),
956                                                   &binding.item_name.as_str(),
957                                                   binding.span));
958
959     Ok(ty::Binder(ty::ProjectionPredicate {             // <-------------------------+
960         projection_ty: ty::ProjectionTy {               //                           |
961             trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
962             item_name: binding.item_name,
963         },
964         ty: binding.ty,
965     }))
966 }
967
968 fn ast_path_to_ty<'tcx>(
969     this: &AstConv<'tcx>,
970     rscope: &RegionScope,
971     span: Span,
972     param_mode: PathParamMode,
973     did: DefId,
974     item_segment: &hir::PathSegment)
975     -> Ty<'tcx>
976 {
977     let tcx = this.tcx();
978     let (generics, decl_ty) = match this.get_item_type_scheme(span, did) {
979         Ok(ty::TypeScheme { generics,  ty: decl_ty }) => {
980             (generics, decl_ty)
981         }
982         Err(ErrorReported) => {
983             return tcx.types.err;
984         }
985     };
986
987     let substs = ast_path_substs_for_ty(this,
988                                         rscope,
989                                         span,
990                                         param_mode,
991                                         &generics,
992                                         item_segment);
993
994     // FIXME(#12938): This is a hack until we have full support for DST.
995     if Some(did) == this.tcx().lang_items.owned_box() {
996         assert_eq!(substs.types.len(TypeSpace), 1);
997         return this.tcx().mk_box(*substs.types.get(TypeSpace, 0));
998     }
999
1000     decl_ty.subst(this.tcx(), &substs)
1001 }
1002
1003 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
1004
1005 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
1006                              rscope: &RegionScope,
1007                              ty: &hir::Ty,
1008                              bounds: &[hir::TyParamBound])
1009                              -> Result<TraitAndProjections<'tcx>, ErrorReported>
1010 {
1011     /*!
1012      * In a type like `Foo + Send`, we want to wait to collect the
1013      * full set of bounds before we make the object type, because we
1014      * need them to infer a region bound.  (For example, if we tried
1015      * made a type from just `Foo`, then it wouldn't be enough to
1016      * infer a 'static bound, and hence the user would get an error.)
1017      * So this function is used when we're dealing with a sum type to
1018      * convert the LHS. It only accepts a type that refers to a trait
1019      * name, and reports an error otherwise.
1020      */
1021
1022     match ty.node {
1023         hir::TyPath(None, ref path) => {
1024             let def = match this.tcx().def_map.borrow().get(&ty.id) {
1025                 Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
1026                 _ => None
1027             };
1028             match def {
1029                 Some(def::DefTrait(trait_def_id)) => {
1030                     let mut projection_bounds = Vec::new();
1031                     let trait_ref = object_path_to_poly_trait_ref(this,
1032                                                                   rscope,
1033                                                                   path.span,
1034                                                                   PathParamMode::Explicit,
1035                                                                   trait_def_id,
1036                                                                   path.segments.last().unwrap(),
1037                                                                   &mut projection_bounds);
1038                     Ok((trait_ref, projection_bounds))
1039                 }
1040                 _ => {
1041                     span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
1042                     Err(ErrorReported)
1043                 }
1044             }
1045         }
1046         _ => {
1047             span_err!(this.tcx().sess, ty.span, E0178,
1048                       "expected a path on the left-hand side of `+`, not `{}`",
1049                       pprust::ty_to_string(ty));
1050             let hi = bounds.iter().map(|x| match *x {
1051                 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
1052                 hir::RegionTyParamBound(ref r) => r.span.hi,
1053             }).max_by_key(|x| x.to_usize());
1054             let full_span = hi.map(|hi| Span {
1055                 lo: ty.span.lo,
1056                 hi: hi,
1057                 expn_id: ty.span.expn_id,
1058             });
1059             match (&ty.node, full_span) {
1060                 (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
1061                     let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1062                     this.tcx().sess
1063                         .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1064                                          format!("&{}({} +{})",
1065                                                  mutbl_str,
1066                                                  pprust::ty_to_string(&*mut_ty.ty),
1067                                                  pprust::bounds_to_string(bounds)));
1068                 }
1069                 (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1070                     let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1071                     this.tcx().sess
1072                         .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1073                                          format!("&{} {}({} +{})",
1074                                                  pprust::lifetime_to_string(lt),
1075                                                  mutbl_str,
1076                                                  pprust::ty_to_string(&*mut_ty.ty),
1077                                                  pprust::bounds_to_string(bounds)));
1078                 }
1079
1080                 _ => {
1081                     fileline_help!(this.tcx().sess, ty.span,
1082                                "perhaps you forgot parentheses? (per RFC 438)");
1083                 }
1084             }
1085             Err(ErrorReported)
1086         }
1087     }
1088 }
1089
1090 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
1091                                   rscope: &RegionScope,
1092                                   span: Span,
1093                                   trait_ref: ty::PolyTraitRef<'tcx>,
1094                                   projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1095                                   bounds: &[hir::TyParamBound])
1096                                   -> Ty<'tcx>
1097 {
1098     let existential_bounds = conv_existential_bounds(this,
1099                                                      rscope,
1100                                                      span,
1101                                                      trait_ref.clone(),
1102                                                      projection_bounds,
1103                                                      bounds);
1104
1105     let result = make_object_type(this, span, trait_ref, existential_bounds);
1106     debug!("trait_ref_to_object_type: result={:?}",
1107            result);
1108
1109     result
1110 }
1111
1112 fn make_object_type<'tcx>(this: &AstConv<'tcx>,
1113                           span: Span,
1114                           principal: ty::PolyTraitRef<'tcx>,
1115                           bounds: ty::ExistentialBounds<'tcx>)
1116                           -> Ty<'tcx> {
1117     let tcx = this.tcx();
1118     let object = ty::TraitTy {
1119         principal: principal,
1120         bounds: bounds
1121     };
1122     let object_trait_ref =
1123         object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
1124
1125     // ensure the super predicates and stop if we encountered an error
1126     if this.ensure_super_predicates(span, principal.def_id()).is_err() {
1127         return tcx.types.err;
1128     }
1129
1130     // check that there are no gross object safety violations,
1131     // most importantly, that the supertraits don't contain Self,
1132     // to avoid ICE-s.
1133     let object_safety_violations =
1134         traits::astconv_object_safety_violations(tcx, principal.def_id());
1135     if !object_safety_violations.is_empty() {
1136         traits::report_object_safety_error(
1137             tcx, span, principal.def_id(), object_safety_violations);
1138         return tcx.types.err;
1139     }
1140
1141     let mut associated_types: FnvHashSet<(DefId, ast::Name)> =
1142         traits::supertraits(tcx, object_trait_ref)
1143         .flat_map(|tr| {
1144             let trait_def = tcx.lookup_trait_def(tr.def_id());
1145             trait_def.associated_type_names
1146                 .clone()
1147                 .into_iter()
1148                 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1149         })
1150         .collect();
1151
1152     for projection_bound in &object.bounds.projection_bounds {
1153         let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1154                     projection_bound.0.projection_ty.item_name);
1155         associated_types.remove(&pair);
1156     }
1157
1158     for (trait_def_id, name) in associated_types {
1159         span_err!(tcx.sess, span, E0191,
1160             "the value of the associated type `{}` (from the trait `{}`) must be specified",
1161                     name,
1162                     tcx.item_path_str(trait_def_id));
1163     }
1164
1165     tcx.mk_trait(object.principal, object.bounds)
1166 }
1167
1168 fn report_ambiguous_associated_type(tcx: &ty::ctxt,
1169                                     span: Span,
1170                                     type_str: &str,
1171                                     trait_str: &str,
1172                                     name: &str) {
1173     span_err!(tcx.sess, span, E0223,
1174               "ambiguous associated type; specify the type using the syntax \
1175                `<{} as {}>::{}`",
1176               type_str, trait_str, name);
1177 }
1178
1179 // Search for a bound on a type parameter which includes the associated item
1180 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1181 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1182 // impl). This function will fail if there are no suitable bounds or there is
1183 // any ambiguity.
1184 fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>,
1185                                    ty_param_node_id: ast::NodeId,
1186                                    ty_param_name: ast::Name,
1187                                    assoc_name: ast::Name,
1188                                    span: Span)
1189                                    -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1190 {
1191     let tcx = this.tcx();
1192
1193     let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
1194         Ok(v) => v,
1195         Err(ErrorReported) => {
1196             return Err(ErrorReported);
1197         }
1198     };
1199
1200     // Ensure the super predicates and stop if we encountered an error.
1201     if bounds.iter().any(|b| this.ensure_super_predicates(span, b.def_id()).is_err()) {
1202         return Err(ErrorReported);
1203     }
1204
1205     // Check that there is exactly one way to find an associated type with the
1206     // correct name.
1207     let suitable_bounds: Vec<_> =
1208         traits::transitive_bounds(tcx, &bounds)
1209         .filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name))
1210         .collect();
1211
1212     one_bound_for_assoc_type(tcx,
1213                              suitable_bounds,
1214                              &ty_param_name.as_str(),
1215                              &assoc_name.as_str(),
1216                              span)
1217 }
1218
1219
1220 // Checks that bounds contains exactly one element and reports appropriate
1221 // errors otherwise.
1222 fn one_bound_for_assoc_type<'tcx>(tcx: &ty::ctxt<'tcx>,
1223                                   bounds: Vec<ty::PolyTraitRef<'tcx>>,
1224                                   ty_param_name: &str,
1225                                   assoc_name: &str,
1226                                   span: Span)
1227     -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1228 {
1229     if bounds.is_empty() {
1230         span_err!(tcx.sess, span, E0220,
1231                   "associated type `{}` not found for `{}`",
1232                   assoc_name,
1233                   ty_param_name);
1234         return Err(ErrorReported);
1235     }
1236
1237     if bounds.len() > 1 {
1238         span_err!(tcx.sess, span, E0221,
1239                   "ambiguous associated type `{}` in bounds of `{}`",
1240                   assoc_name,
1241                   ty_param_name);
1242
1243         for bound in &bounds {
1244             span_note!(tcx.sess, span,
1245                        "associated type `{}` could derive from `{}`",
1246                        ty_param_name,
1247                        bound);
1248         }
1249     }
1250
1251     Ok(bounds[0].clone())
1252 }
1253
1254 // Create a type from a path to an associated type.
1255 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1256 // and item_segment is the path segment for D. We return a type and a def for
1257 // the whole path.
1258 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1259 // parameter or Self.
1260 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1261                                    span: Span,
1262                                    ty: Ty<'tcx>,
1263                                    ty_path_def: def::Def,
1264                                    item_segment: &hir::PathSegment)
1265                                    -> (Ty<'tcx>, def::Def)
1266 {
1267     let tcx = this.tcx();
1268     let assoc_name = item_segment.identifier.name;
1269
1270     debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1271
1272     prohibit_type_params(tcx, slice::ref_slice(item_segment));
1273
1274     // Find the type of the associated item, and the trait where the associated
1275     // item is declared.
1276     let bound = match (&ty.sty, ty_path_def) {
1277         (_, def::DefSelfTy(Some(trait_did), Some((impl_id, _)))) => {
1278             // `Self` in an impl of a trait - we have a concrete self type and a
1279             // trait reference.
1280             let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1281             let trait_ref = if let Some(free_substs) = this.get_free_substs() {
1282                 trait_ref.subst(tcx, free_substs)
1283             } else {
1284                 trait_ref
1285             };
1286
1287             if this.ensure_super_predicates(span, trait_did).is_err() {
1288                 return (tcx.types.err, ty_path_def);
1289             }
1290
1291             let candidates: Vec<ty::PolyTraitRef> =
1292                 traits::supertraits(tcx, ty::Binder(trait_ref))
1293                 .filter(|r| this.trait_defines_associated_type_named(r.def_id(),
1294                                                                      assoc_name))
1295                 .collect();
1296
1297             match one_bound_for_assoc_type(tcx,
1298                                            candidates,
1299                                            "Self",
1300                                            &assoc_name.as_str(),
1301                                            span) {
1302                 Ok(bound) => bound,
1303                 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1304             }
1305         }
1306         (&ty::TyParam(_), def::DefSelfTy(Some(trait_did), None)) => {
1307             let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1308             match find_bound_for_assoc_item(this,
1309                                             trait_node_id,
1310                                             token::special_idents::type_self.name,
1311                                             assoc_name,
1312                                             span) {
1313                 Ok(bound) => bound,
1314                 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1315             }
1316         }
1317         (&ty::TyParam(_), def::DefTyParam(_, _, param_did, param_name)) => {
1318             let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1319             match find_bound_for_assoc_item(this,
1320                                             param_node_id,
1321                                             param_name,
1322                                             assoc_name,
1323                                             span) {
1324                 Ok(bound) => bound,
1325                 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1326             }
1327         }
1328         _ => {
1329             report_ambiguous_associated_type(tcx,
1330                                              span,
1331                                              &ty.to_string(),
1332                                              "Trait",
1333                                              &assoc_name.as_str());
1334             return (tcx.types.err, ty_path_def);
1335         }
1336     };
1337
1338     let trait_did = bound.0.def_id;
1339     let ty = this.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1340
1341     let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1342         // `ty::trait_items` used below requires information generated
1343         // by type collection, which may be in progress at this point.
1344         match tcx.map.expect_item(trait_id).node {
1345             hir::ItemTrait(_, _, _, ref trait_items) => {
1346                 let item = trait_items.iter()
1347                                       .find(|i| i.name == assoc_name)
1348                                       .expect("missing associated type");
1349                 tcx.map.local_def_id(item.id)
1350             }
1351             _ => unreachable!()
1352         }
1353     } else {
1354         let trait_items = tcx.trait_items(trait_did);
1355         let item = trait_items.iter().find(|i| i.name() == assoc_name);
1356         item.expect("missing associated type").def_id()
1357     };
1358
1359     (ty, def::DefAssociatedTy(trait_did, item_did))
1360 }
1361
1362 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
1363                      rscope: &RegionScope,
1364                      span: Span,
1365                      param_mode: PathParamMode,
1366                      opt_self_ty: Option<Ty<'tcx>>,
1367                      trait_def_id: DefId,
1368                      trait_segment: &hir::PathSegment,
1369                      item_segment: &hir::PathSegment)
1370                      -> Ty<'tcx>
1371 {
1372     let tcx = this.tcx();
1373
1374     prohibit_type_params(tcx, slice::ref_slice(item_segment));
1375
1376     let self_ty = if let Some(ty) = opt_self_ty {
1377         ty
1378     } else {
1379         let path_str = tcx.item_path_str(trait_def_id);
1380         report_ambiguous_associated_type(tcx,
1381                                          span,
1382                                          "Type",
1383                                          &path_str,
1384                                          &item_segment.identifier.name.as_str());
1385         return tcx.types.err;
1386     };
1387
1388     debug!("qpath_to_ty: self_type={:?}", self_ty);
1389
1390     let trait_ref = ast_path_to_mono_trait_ref(this,
1391                                                rscope,
1392                                                span,
1393                                                param_mode,
1394                                                trait_def_id,
1395                                                Some(self_ty),
1396                                                trait_segment);
1397
1398     debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1399
1400     this.projected_ty(span, trait_ref, item_segment.identifier.name)
1401 }
1402
1403 /// Convert a type supplied as value for a type argument from AST into our
1404 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1405 /// it applies the object lifetime default.
1406 ///
1407 /// # Parameters
1408 ///
1409 /// * `this`, `rscope`: the surrounding context
1410 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1411 ///   referenced
1412 /// * `index`: the index of the type parameter being instantiated from the list
1413 ///   (we assume it is in the `TypeSpace`)
1414 /// * `region_substs`: a partial substitution consisting of
1415 ///   only the region type parameters being supplied to this type.
1416 /// * `ast_ty`: the ast representation of the type being supplied
1417 pub fn ast_ty_arg_to_ty<'tcx>(this: &AstConv<'tcx>,
1418                               rscope: &RegionScope,
1419                               decl_generics: &ty::Generics<'tcx>,
1420                               index: usize,
1421                               region_substs: &Substs<'tcx>,
1422                               ast_ty: &hir::Ty)
1423                               -> Ty<'tcx>
1424 {
1425     let tcx = this.tcx();
1426
1427     if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1428         let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1429         let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1430         ast_ty_to_ty(this, rscope1, ast_ty)
1431     } else {
1432         ast_ty_to_ty(this, rscope, ast_ty)
1433     }
1434 }
1435
1436 // Check the base def in a PathResolution and convert it to a Ty. If there are
1437 // associated types in the PathResolution, these will need to be separately
1438 // resolved.
1439 fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1440                         rscope: &RegionScope,
1441                         span: Span,
1442                         param_mode: PathParamMode,
1443                         def: &def::Def,
1444                         opt_self_ty: Option<Ty<'tcx>>,
1445                         base_segments: &[hir::PathSegment])
1446                         -> Ty<'tcx> {
1447     let tcx = this.tcx();
1448
1449     match *def {
1450         def::DefTrait(trait_def_id) => {
1451             // N.B. this case overlaps somewhat with
1452             // TyObjectSum, see that fn for details
1453             let mut projection_bounds = Vec::new();
1454
1455             let trait_ref = object_path_to_poly_trait_ref(this,
1456                                                           rscope,
1457                                                           span,
1458                                                           param_mode,
1459                                                           trait_def_id,
1460                                                           base_segments.last().unwrap(),
1461                                                           &mut projection_bounds);
1462
1463             prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1464             trait_ref_to_object_type(this,
1465                                      rscope,
1466                                      span,
1467                                      trait_ref,
1468                                      projection_bounds,
1469                                      &[])
1470         }
1471         def::DefTy(did, _) | def::DefStruct(did) => {
1472             prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1473             ast_path_to_ty(this,
1474                            rscope,
1475                            span,
1476                            param_mode,
1477                            did,
1478                            base_segments.last().unwrap())
1479         }
1480         def::DefTyParam(space, index, _, name) => {
1481             prohibit_type_params(tcx, base_segments);
1482             tcx.mk_param(space, index, name)
1483         }
1484         def::DefSelfTy(_, Some((_, self_ty_id))) => {
1485             // Self in impl (we know the concrete type).
1486             prohibit_type_params(tcx, base_segments);
1487             if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&self_ty_id) {
1488                 if let Some(free_substs) = this.get_free_substs() {
1489                     ty.subst(tcx, free_substs)
1490                 } else {
1491                     ty
1492                 }
1493             } else {
1494                 tcx.sess.span_bug(span, "self type has not been fully resolved")
1495             }
1496         }
1497         def::DefSelfTy(Some(_), None) => {
1498             // Self in trait.
1499             prohibit_type_params(tcx, base_segments);
1500             tcx.mk_self_type()
1501         }
1502         def::DefAssociatedTy(trait_did, _) => {
1503             prohibit_type_params(tcx, &base_segments[..base_segments.len()-2]);
1504             qpath_to_ty(this,
1505                         rscope,
1506                         span,
1507                         param_mode,
1508                         opt_self_ty,
1509                         trait_did,
1510                         &base_segments[base_segments.len()-2],
1511                         base_segments.last().unwrap())
1512         }
1513         def::DefMod(id) => {
1514             // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1515             // FIXME(#22519) This part of the resolution logic should be
1516             // avoided entirely for that form, once we stop needed a Def
1517             // for `associated_path_def_to_ty`.
1518             // Fixing this will also let use resolve <Self>::Foo the same way we
1519             // resolve Self::Foo, at the moment we can't resolve the former because
1520             // we don't have the trait information around, which is just sad.
1521
1522             if !base_segments.is_empty() {
1523                 let id_node = tcx.map.as_local_node_id(id).unwrap();
1524                 span_err!(tcx.sess,
1525                           span,
1526                           E0247,
1527                           "found module name used as a type: {}",
1528                           tcx.map.node_to_user_string(id_node));
1529                 return this.tcx().types.err;
1530             }
1531
1532             opt_self_ty.expect("missing T in <T>::a::b::c")
1533         }
1534         def::DefPrimTy(prim_ty) => {
1535             prim_ty_to_ty(tcx, base_segments, prim_ty)
1536         }
1537         def::DefErr => {
1538             return this.tcx().types.err;
1539         }
1540         _ => {
1541             let id_node = tcx.map.as_local_node_id(def.def_id()).unwrap();
1542             span_err!(tcx.sess, span, E0248,
1543                       "found value `{}` used as a type",
1544                       tcx.map.path_to_string(id_node));
1545             return this.tcx().types.err;
1546         }
1547     }
1548 }
1549
1550 // Note that both base_segments and assoc_segments may be empty, although not at
1551 // the same time.
1552 pub fn finish_resolving_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1553                                         rscope: &RegionScope,
1554                                         span: Span,
1555                                         param_mode: PathParamMode,
1556                                         def: &def::Def,
1557                                         opt_self_ty: Option<Ty<'tcx>>,
1558                                         base_segments: &[hir::PathSegment],
1559                                         assoc_segments: &[hir::PathSegment])
1560                                         -> Ty<'tcx> {
1561     let mut ty = base_def_to_ty(this,
1562                                 rscope,
1563                                 span,
1564                                 param_mode,
1565                                 def,
1566                                 opt_self_ty,
1567                                 base_segments);
1568     let mut def = *def;
1569     // If any associated type segments remain, attempt to resolve them.
1570     for segment in assoc_segments {
1571         if ty.sty == ty::TyError {
1572             break;
1573         }
1574         // This is pretty bad (it will fail except for T::A and Self::A).
1575         let (a_ty, a_def) = associated_path_def_to_ty(this,
1576                                                       span,
1577                                                       ty,
1578                                                       def,
1579                                                       segment);
1580         ty = a_ty;
1581         def = a_def;
1582     }
1583     ty
1584 }
1585
1586 /// Parses the programmer's textual representation of a type into our
1587 /// internal notion of a type.
1588 pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
1589                           rscope: &RegionScope,
1590                           ast_ty: &hir::Ty)
1591                           -> Ty<'tcx>
1592 {
1593     debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1594            ast_ty.id, ast_ty);
1595
1596     let tcx = this.tcx();
1597
1598     if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&ast_ty.id) {
1599         debug!("ast_ty_to_ty: id={:?} ty={:?} (cached)", ast_ty.id, ty);
1600         return ty;
1601     }
1602
1603     let typ = match ast_ty.node {
1604         hir::TyVec(ref ty) => {
1605             tcx.mk_slice(ast_ty_to_ty(this, rscope, &**ty))
1606         }
1607         hir::TyObjectSum(ref ty, ref bounds) => {
1608             match ast_ty_to_trait_ref(this, rscope, &**ty, bounds) {
1609                 Ok((trait_ref, projection_bounds)) => {
1610                     trait_ref_to_object_type(this,
1611                                              rscope,
1612                                              ast_ty.span,
1613                                              trait_ref,
1614                                              projection_bounds,
1615                                              bounds)
1616                 }
1617                 Err(ErrorReported) => {
1618                     this.tcx().types.err
1619                 }
1620             }
1621         }
1622         hir::TyPtr(ref mt) => {
1623             tcx.mk_ptr(ty::TypeAndMut {
1624                 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
1625                 mutbl: mt.mutbl
1626             })
1627         }
1628         hir::TyRptr(ref region, ref mt) => {
1629             let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1630             debug!("TyRef r={:?}", r);
1631             let rscope1 =
1632                 &ObjectLifetimeDefaultRscope::new(
1633                     rscope,
1634                     ty::ObjectLifetimeDefault::Specific(r));
1635             let t = ast_ty_to_ty(this, rscope1, &*mt.ty);
1636             tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1637         }
1638         hir::TyTup(ref fields) => {
1639             let flds = fields.iter()
1640                              .map(|t| ast_ty_to_ty(this, rscope, &**t))
1641                              .collect();
1642             tcx.mk_tup(flds)
1643         }
1644         hir::TyBareFn(ref bf) => {
1645             require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1646             let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
1647             tcx.mk_fn(None, tcx.mk_bare_fn(bare_fn))
1648         }
1649         hir::TyPolyTraitRef(ref bounds) => {
1650             conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds)
1651         }
1652         hir::TyPath(ref maybe_qself, ref path) => {
1653             let path_res = if let Some(&d) = tcx.def_map.borrow().get(&ast_ty.id) {
1654                 d
1655             } else if let Some(hir::QSelf { position: 0, .. }) = *maybe_qself {
1656                 // Create some fake resolution that can't possibly be a type.
1657                 def::PathResolution {
1658                     base_def: def::DefMod(tcx.map.local_def_id(ast::CRATE_NODE_ID)),
1659                     last_private: LastMod(AllPublic),
1660                     depth: path.segments.len()
1661                 }
1662             } else {
1663                 tcx.sess.span_bug(ast_ty.span, &format!("unbound path {:?}", ast_ty))
1664             };
1665             let def = path_res.base_def;
1666             let base_ty_end = path.segments.len() - path_res.depth;
1667             let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1668                 ast_ty_to_ty(this, rscope, &qself.ty)
1669             });
1670             let ty = finish_resolving_def_to_ty(this,
1671                                                 rscope,
1672                                                 ast_ty.span,
1673                                                 PathParamMode::Explicit,
1674                                                 &def,
1675                                                 opt_self_ty,
1676                                                 &path.segments[..base_ty_end],
1677                                                 &path.segments[base_ty_end..]);
1678
1679             if path_res.depth != 0 && ty.sty != ty::TyError {
1680                 // Write back the new resolution.
1681                 tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
1682                     base_def: def,
1683                     last_private: path_res.last_private,
1684                     depth: 0
1685                 });
1686             }
1687
1688             ty
1689         }
1690         hir::TyFixedLengthVec(ref ty, ref e) => {
1691             let hint = UncheckedExprHint(tcx.types.usize);
1692             match const_eval::eval_const_expr_partial(tcx, &e, hint, None) {
1693                 Ok(r) => {
1694                     match r {
1695                         ConstVal::Int(i) =>
1696                             tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1697                                          i as usize),
1698                         ConstVal::Uint(i) =>
1699                             tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1700                                          i as usize),
1701                         _ => {
1702                             span_err!(tcx.sess, ast_ty.span, E0249,
1703                                       "expected constant integer expression \
1704                                        for array length");
1705                             this.tcx().types.err
1706                         }
1707                     }
1708                 }
1709                 Err(ref r) => {
1710                     span_err!(tcx.sess, r.span, E0250,
1711                               "array length constant evaluation error: {}",
1712                               r.description());
1713                     if !ast_ty.span.contains(r.span) {
1714                         span_note!(tcx.sess, ast_ty.span, "for array length here")
1715                     }
1716                     this.tcx().types.err
1717                 }
1718             }
1719         }
1720         hir::TyTypeof(ref _e) => {
1721             span_err!(tcx.sess, ast_ty.span, E0516,
1722                   "`typeof` is a reserved keyword but unimplemented");
1723             tcx.types.err
1724         }
1725         hir::TyInfer => {
1726             // TyInfer also appears as the type of arguments or return
1727             // values in a ExprClosure, or as
1728             // the type of local variables. Both of these cases are
1729             // handled specially and will not descend into this routine.
1730             this.ty_infer(None, None, None, ast_ty.span)
1731         }
1732     };
1733
1734     debug!("ast_ty_to_ty: id={:?} ty={:?}", ast_ty.id, typ);
1735     tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, typ);
1736     return typ;
1737 }
1738
1739 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1740                        rscope: &RegionScope,
1741                        a: &hir::Arg,
1742                        expected_ty: Option<Ty<'tcx>>)
1743                        -> Ty<'tcx>
1744 {
1745     match a.ty.node {
1746         hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1747         hir::TyInfer => this.ty_infer(None, None, None, a.ty.span),
1748         _ => ast_ty_to_ty(this, rscope, &*a.ty),
1749     }
1750 }
1751
1752 struct SelfInfo<'a, 'tcx> {
1753     untransformed_self_ty: Ty<'tcx>,
1754     explicit_self: &'a hir::ExplicitSelf,
1755 }
1756
1757 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1758                           sig: &hir::MethodSig,
1759                           untransformed_self_ty: Ty<'tcx>)
1760                           -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1761     let self_info = Some(SelfInfo {
1762         untransformed_self_ty: untransformed_self_ty,
1763         explicit_self: &sig.explicit_self,
1764     });
1765     let (bare_fn_ty, optional_explicit_self_category) =
1766         ty_of_method_or_bare_fn(this,
1767                                 sig.unsafety,
1768                                 sig.abi,
1769                                 self_info,
1770                                 &sig.decl);
1771     (bare_fn_ty, optional_explicit_self_category.unwrap())
1772 }
1773
1774 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: hir::Unsafety, abi: abi::Abi,
1775                                               decl: &hir::FnDecl) -> ty::BareFnTy<'tcx> {
1776     let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1777     bare_fn_ty
1778 }
1779
1780 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1781                                      unsafety: hir::Unsafety,
1782                                      abi: abi::Abi,
1783                                      opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1784                                      decl: &hir::FnDecl)
1785                                      -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1786 {
1787     debug!("ty_of_method_or_bare_fn");
1788
1789     // New region names that appear inside of the arguments of the function
1790     // declaration are bound to that function type.
1791     let rb = rscope::BindingRscope::new();
1792
1793     // `implied_output_region` is the region that will be assumed for any
1794     // region parameters in the return type. In accordance with the rules for
1795     // lifetime elision, we can determine it in two ways. First (determined
1796     // here), if self is by-reference, then the implied output region is the
1797     // region of the self parameter.
1798     let (self_ty, explicit_self_category) = match opt_self_info {
1799         None => (None, None),
1800         Some(self_info) => determine_self_type(this, &rb, self_info)
1801     };
1802
1803     // HACK(eddyb) replace the fake self type in the AST with the actual type.
1804     let arg_params = if self_ty.is_some() {
1805         &decl.inputs[1..]
1806     } else {
1807         &decl.inputs[..]
1808     };
1809     let arg_tys: Vec<Ty> =
1810         arg_params.iter().map(|a| ty_of_arg(this, &rb, a, None)).collect();
1811     let arg_pats: Vec<String> =
1812         arg_params.iter().map(|a| pprust::pat_to_string(&*a.pat)).collect();
1813
1814     // Second, if there was exactly one lifetime (either a substitution or a
1815     // reference) in the arguments, then any anonymous regions in the output
1816     // have that lifetime.
1817     let implied_output_region = match explicit_self_category {
1818         Some(ty::ByReferenceExplicitSelfCategory(region, _)) => Ok(region),
1819         _ => find_implied_output_region(this.tcx(), &arg_tys, arg_pats)
1820     };
1821
1822     let output_ty = match decl.output {
1823         hir::Return(ref output) =>
1824             ty::FnConverging(convert_ty_with_lifetime_elision(this,
1825                                                               implied_output_region,
1826                                                               &output)),
1827         hir::DefaultReturn(..) => ty::FnConverging(this.tcx().mk_nil()),
1828         hir::NoReturn(..) => ty::FnDiverging
1829     };
1830
1831     (ty::BareFnTy {
1832         unsafety: unsafety,
1833         abi: abi,
1834         sig: ty::Binder(ty::FnSig {
1835             inputs: self_ty.into_iter().chain(arg_tys).collect(),
1836             output: output_ty,
1837             variadic: decl.variadic
1838         }),
1839     }, explicit_self_category)
1840 }
1841
1842 fn determine_self_type<'a, 'tcx>(this: &AstConv<'tcx>,
1843                                  rscope: &RegionScope,
1844                                  self_info: SelfInfo<'a, 'tcx>)
1845                                  -> (Option<Ty<'tcx>>, Option<ty::ExplicitSelfCategory>)
1846 {
1847     let self_ty = self_info.untransformed_self_ty;
1848     return match self_info.explicit_self.node {
1849         hir::SelfStatic => (None, Some(ty::StaticExplicitSelfCategory)),
1850         hir::SelfValue(_) => {
1851             (Some(self_ty), Some(ty::ByValueExplicitSelfCategory))
1852         }
1853         hir::SelfRegion(ref lifetime, mutability, _) => {
1854             let region =
1855                 opt_ast_region_to_region(this,
1856                                          rscope,
1857                                          self_info.explicit_self.span,
1858                                          lifetime);
1859             (Some(this.tcx().mk_ref(
1860                 this.tcx().mk_region(region),
1861                 ty::TypeAndMut {
1862                     ty: self_ty,
1863                     mutbl: mutability
1864                 })),
1865              Some(ty::ByReferenceExplicitSelfCategory(region, mutability)))
1866         }
1867         hir::SelfExplicit(ref ast_type, _) => {
1868             let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1869
1870             // We wish to (for now) categorize an explicit self
1871             // declaration like `self: SomeType` into either `self`,
1872             // `&self`, `&mut self`, or `Box<self>`. We do this here
1873             // by some simple pattern matching. A more precise check
1874             // is done later in `check_method_self_type()`.
1875             //
1876             // Examples:
1877             //
1878             // ```
1879             // impl Foo for &T {
1880             //     // Legal declarations:
1881             //     fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1882             //     fn method2(self: &T); // ByValueExplicitSelfCategory
1883             //     fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1884             //
1885             //     // Invalid cases will be caught later by `check_method_self_type`:
1886             //     fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1887             // }
1888             // ```
1889             //
1890             // To do the check we just count the number of "modifiers"
1891             // on each type and compare them. If they are the same or
1892             // the impl has more, we call it "by value". Otherwise, we
1893             // look at the outermost modifier on the method decl and
1894             // call it by-ref, by-box as appropriate. For method1, for
1895             // example, the impl type has one modifier, but the method
1896             // type has two, so we end up with
1897             // ByReferenceExplicitSelfCategory.
1898
1899             let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1900             let method_modifiers = count_modifiers(explicit_type);
1901
1902             debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1903                    explicit_type={:?} \
1904                    modifiers=({},{})",
1905                    self_info.untransformed_self_ty,
1906                    explicit_type,
1907                    impl_modifiers,
1908                    method_modifiers);
1909
1910             let category = if impl_modifiers >= method_modifiers {
1911                 ty::ByValueExplicitSelfCategory
1912             } else {
1913                 match explicit_type.sty {
1914                     ty::TyRef(r, mt) => ty::ByReferenceExplicitSelfCategory(*r, mt.mutbl),
1915                     ty::TyBox(_) => ty::ByBoxExplicitSelfCategory,
1916                     _ => ty::ByValueExplicitSelfCategory,
1917                 }
1918             };
1919
1920             (Some(explicit_type), Some(category))
1921         }
1922     };
1923
1924     fn count_modifiers(ty: Ty) -> usize {
1925         match ty.sty {
1926             ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1927             ty::TyBox(t) => count_modifiers(t) + 1,
1928             _ => 0,
1929         }
1930     }
1931 }
1932
1933 pub fn ty_of_closure<'tcx>(
1934     this: &AstConv<'tcx>,
1935     unsafety: hir::Unsafety,
1936     decl: &hir::FnDecl,
1937     abi: abi::Abi,
1938     expected_sig: Option<ty::FnSig<'tcx>>)
1939     -> ty::ClosureTy<'tcx>
1940 {
1941     debug!("ty_of_closure(expected_sig={:?})",
1942            expected_sig);
1943
1944     // new region names that appear inside of the fn decl are bound to
1945     // that function type
1946     let rb = rscope::BindingRscope::new();
1947
1948     let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1949         let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1950             // no guarantee that the correct number of expected args
1951             // were supplied
1952             if i < e.inputs.len() {
1953                 Some(e.inputs[i])
1954             } else {
1955                 None
1956             }
1957         });
1958         ty_of_arg(this, &rb, a, expected_arg_ty)
1959     }).collect();
1960
1961     let expected_ret_ty = expected_sig.map(|e| e.output);
1962
1963     let is_infer = match decl.output {
1964         hir::Return(ref output) if output.node == hir::TyInfer => true,
1965         hir::DefaultReturn(..) => true,
1966         _ => false
1967     };
1968
1969     let output_ty = match decl.output {
1970         _ if is_infer && expected_ret_ty.is_some() =>
1971             expected_ret_ty.unwrap(),
1972         _ if is_infer =>
1973             ty::FnConverging(this.ty_infer(None, None, None, decl.output.span())),
1974         hir::Return(ref output) =>
1975             ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1976         hir::DefaultReturn(..) => unreachable!(),
1977         hir::NoReturn(..) => ty::FnDiverging
1978     };
1979
1980     debug!("ty_of_closure: input_tys={:?}", input_tys);
1981     debug!("ty_of_closure: output_ty={:?}", output_ty);
1982
1983     ty::ClosureTy {
1984         unsafety: unsafety,
1985         abi: abi,
1986         sig: ty::Binder(ty::FnSig {inputs: input_tys,
1987                                    output: output_ty,
1988                                    variadic: decl.variadic}),
1989     }
1990 }
1991
1992 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1993 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1994 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1995 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1996 fn conv_existential_bounds<'tcx>(
1997     this: &AstConv<'tcx>,
1998     rscope: &RegionScope,
1999     span: Span,
2000     principal_trait_ref: ty::PolyTraitRef<'tcx>,
2001     projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2002     ast_bounds: &[hir::TyParamBound])
2003     -> ty::ExistentialBounds<'tcx>
2004 {
2005     let partitioned_bounds =
2006         partition_bounds(this.tcx(), span, ast_bounds);
2007
2008     conv_existential_bounds_from_partitioned_bounds(
2009         this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2010 }
2011
2012 fn conv_ty_poly_trait_ref<'tcx>(
2013     this: &AstConv<'tcx>,
2014     rscope: &RegionScope,
2015     span: Span,
2016     ast_bounds: &[hir::TyParamBound])
2017     -> Ty<'tcx>
2018 {
2019     let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[..]);
2020
2021     let mut projection_bounds = Vec::new();
2022     let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2023         let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2024         instantiate_poly_trait_ref(this,
2025                                    rscope,
2026                                    trait_bound,
2027                                    None,
2028                                    &mut projection_bounds)
2029     } else {
2030         span_err!(this.tcx().sess, span, E0224,
2031                   "at least one non-builtin trait is required for an object type");
2032         return this.tcx().types.err;
2033     };
2034
2035     let bounds =
2036         conv_existential_bounds_from_partitioned_bounds(this,
2037                                                         rscope,
2038                                                         span,
2039                                                         main_trait_bound.clone(),
2040                                                         projection_bounds,
2041                                                         partitioned_bounds);
2042
2043     make_object_type(this, span, main_trait_bound, bounds)
2044 }
2045
2046 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
2047     this: &AstConv<'tcx>,
2048     rscope: &RegionScope,
2049     span: Span,
2050     principal_trait_ref: ty::PolyTraitRef<'tcx>,
2051     projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2052     partitioned_bounds: PartitionedBounds)
2053     -> ty::ExistentialBounds<'tcx>
2054 {
2055     let PartitionedBounds { builtin_bounds,
2056                             trait_bounds,
2057                             region_bounds } =
2058         partitioned_bounds;
2059
2060     if !trait_bounds.is_empty() {
2061         let b = &trait_bounds[0];
2062         span_err!(this.tcx().sess, b.trait_ref.path.span, E0225,
2063                   "only the builtin traits can be used as closure or object bounds");
2064     }
2065
2066     let region_bound =
2067         compute_object_lifetime_bound(this,
2068                                       span,
2069                                       &region_bounds,
2070                                       principal_trait_ref,
2071                                       builtin_bounds);
2072
2073     let region_bound = match region_bound {
2074         Some(r) => r,
2075         None => {
2076             match rscope.object_lifetime_default(span) {
2077                 Some(r) => r,
2078                 None => {
2079                     span_err!(this.tcx().sess, span, E0228,
2080                               "the lifetime bound for this object type cannot be deduced \
2081                                from context; please supply an explicit bound");
2082                     ty::ReStatic
2083                 }
2084             }
2085         }
2086     };
2087
2088     debug!("region_bound: {:?}", region_bound);
2089
2090     ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2091 }
2092
2093 /// Given the bounds on an object, determines what single region bound
2094 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
2095 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
2096 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
2097 fn compute_object_lifetime_bound<'tcx>(
2098     this: &AstConv<'tcx>,
2099     span: Span,
2100     explicit_region_bounds: &[&hir::Lifetime],
2101     principal_trait_ref: ty::PolyTraitRef<'tcx>,
2102     builtin_bounds: ty::BuiltinBounds)
2103     -> Option<ty::Region> // if None, use the default
2104 {
2105     let tcx = this.tcx();
2106
2107     debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2108            principal_trait_ref={:?}, builtin_bounds={:?})",
2109            explicit_region_bounds,
2110            principal_trait_ref,
2111            builtin_bounds);
2112
2113     if explicit_region_bounds.len() > 1 {
2114         span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2115             "only a single explicit lifetime bound is permitted");
2116     }
2117
2118     if !explicit_region_bounds.is_empty() {
2119         // Explicitly specified region bound. Use that.
2120         let r = explicit_region_bounds[0];
2121         return Some(ast_region_to_region(tcx, r));
2122     }
2123
2124     if let Err(ErrorReported) = this.ensure_super_predicates(span,principal_trait_ref.def_id()) {
2125         return Some(ty::ReStatic);
2126     }
2127
2128     // No explicit region bound specified. Therefore, examine trait
2129     // bounds and see if we can derive region bounds from those.
2130     let derived_region_bounds =
2131         object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2132
2133     // If there are no derived region bounds, then report back that we
2134     // can find no region bound. The caller will use the default.
2135     if derived_region_bounds.is_empty() {
2136         return None;
2137     }
2138
2139     // If any of the derived region bounds are 'static, that is always
2140     // the best choice.
2141     if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2142         return Some(ty::ReStatic);
2143     }
2144
2145     // Determine whether there is exactly one unique region in the set
2146     // of derived region bounds. If so, use that. Otherwise, report an
2147     // error.
2148     let r = derived_region_bounds[0];
2149     if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2150         span_err!(tcx.sess, span, E0227,
2151                   "ambiguous lifetime bound, explicit lifetime bound required");
2152     }
2153     return Some(r);
2154 }
2155
2156 pub struct PartitionedBounds<'a> {
2157     pub builtin_bounds: ty::BuiltinBounds,
2158     pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2159     pub region_bounds: Vec<&'a hir::Lifetime>,
2160 }
2161
2162 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2163 /// general trait bounds, and region bounds.
2164 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
2165                             _span: Span,
2166                             ast_bounds: &'a [hir::TyParamBound])
2167                             -> PartitionedBounds<'a>
2168 {
2169     let mut builtin_bounds = ty::BuiltinBounds::empty();
2170     let mut region_bounds = Vec::new();
2171     let mut trait_bounds = Vec::new();
2172     for ast_bound in ast_bounds {
2173         match *ast_bound {
2174             hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2175                 match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
2176                     def::DefTrait(trait_did) => {
2177                         if tcx.try_add_builtin_trait(trait_did,
2178                                                      &mut builtin_bounds) {
2179                             let segments = &b.trait_ref.path.segments;
2180                             let parameters = &segments[segments.len() - 1].parameters;
2181                             if !parameters.types().is_empty() {
2182                                 check_type_argument_count(tcx, b.trait_ref.path.span,
2183                                                           parameters.types().len(), 0, 0);
2184                             }
2185                             if !parameters.lifetimes().is_empty() {
2186                                 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2187                                                              parameters.lifetimes().len(), 0);
2188                             }
2189                             continue; // success
2190                         }
2191                     }
2192                     _ => {
2193                         // Not a trait? that's an error, but it'll get
2194                         // reported later.
2195                     }
2196                 }
2197                 trait_bounds.push(b);
2198             }
2199             hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2200             hir::RegionTyParamBound(ref l) => {
2201                 region_bounds.push(l);
2202             }
2203         }
2204     }
2205
2206     PartitionedBounds {
2207         builtin_bounds: builtin_bounds,
2208         trait_bounds: trait_bounds,
2209         region_bounds: region_bounds,
2210     }
2211 }
2212
2213 fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
2214                               bindings: &[ConvertedBinding<'tcx>])
2215 {
2216     for binding in bindings.iter().take(1) {
2217         prohibit_projection(tcx, binding.span);
2218     }
2219 }
2220
2221 fn check_type_argument_count(tcx: &ty::ctxt, span: Span, supplied: usize,
2222                              required: usize, accepted: usize) {
2223     if supplied < required {
2224         let expected = if required < accepted {
2225             "expected at least"
2226         } else {
2227             "expected"
2228         };
2229         span_err!(tcx.sess, span, E0243,
2230                   "wrong number of type arguments: {} {}, found {}",
2231                   expected, required, supplied);
2232     } else if supplied > accepted {
2233         let expected = if required < accepted {
2234             "expected at most"
2235         } else {
2236             "expected"
2237         };
2238         span_err!(tcx.sess, span, E0244,
2239                   "wrong number of type arguments: {} {}, found {}",
2240                   expected,
2241                   accepted,
2242                   supplied);
2243     }
2244 }
2245
2246 fn report_lifetime_number_error(tcx: &ty::ctxt, span: Span, number: usize, expected: usize) {
2247     span_err!(tcx.sess, span, E0107,
2248               "wrong number of lifetime parameters: expected {}, found {}",
2249               expected, number);
2250 }
2251
2252 // A helper struct for conveniently grouping a set of bounds which we pass to
2253 // and return from functions in multiple places.
2254 #[derive(PartialEq, Eq, Clone, Debug)]
2255 pub struct Bounds<'tcx> {
2256     pub region_bounds: Vec<ty::Region>,
2257     pub builtin_bounds: ty::BuiltinBounds,
2258     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2259     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2260 }
2261
2262 impl<'tcx> Bounds<'tcx> {
2263     pub fn predicates(&self,
2264         tcx: &ty::ctxt<'tcx>,
2265         param_ty: Ty<'tcx>)
2266         -> Vec<ty::Predicate<'tcx>>
2267     {
2268         let mut vec = Vec::new();
2269
2270         for builtin_bound in &self.builtin_bounds {
2271             match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
2272                 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2273                 Err(ErrorReported) => { }
2274             }
2275         }
2276
2277         for &region_bound in &self.region_bounds {
2278             // account for the binder being introduced below; no need to shift `param_ty`
2279             // because, at present at least, it can only refer to early-bound regions
2280             let region_bound = ty::fold::shift_region(region_bound, 1);
2281             vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2282         }
2283
2284         for bound_trait_ref in &self.trait_bounds {
2285             vec.push(bound_trait_ref.to_predicate());
2286         }
2287
2288         for projection in &self.projection_bounds {
2289             vec.push(projection.to_predicate());
2290         }
2291
2292         vec
2293     }
2294 }