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