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