]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Update E0253.rs
[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 rustc_const_eval::eval_length;
52 use hir::{self, SelfKind};
53 use hir::def::{Def, PathResolution};
54 use hir::def_id::DefId;
55 use hir::print as pprust;
56 use middle::resolve_lifetime as rl;
57 use rustc::lint;
58 use rustc::ty::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs, ParamSpace};
59 use rustc::traits;
60 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
61 use rustc::ty::wf::object_region_bounds;
62 use rustc_back::slice;
63 use require_c_abi_if_variadic;
64 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
65              ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
66              ElisionFailureInfo, ElidedLifetime};
67 use util::common::{ErrorReported, FN_OUTPUT_NAME};
68 use util::nodemap::{NodeMap, FnvHashSet};
69
70 use std::cell::RefCell;
71 use syntax::{abi, ast};
72 use syntax::feature_gate::{GateIssue, emit_feature_err};
73 use syntax::parse::token::{self, keywords};
74 use syntax_pos::{Span, Pos};
75 use errors::DiagnosticBuilder;
76
77 pub trait AstConv<'gcx, 'tcx> {
78     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
79
80     /// A cache used for the result of `ast_ty_to_ty_cache`
81     fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
82
83     /// Identify the type scheme for an item with a type, like a type
84     /// alias, fn, or struct. This allows you to figure out the set of
85     /// type parameters defined on the item.
86     fn get_item_type_scheme(&self, span: Span, id: DefId)
87                             -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
88
89     /// Returns the `TraitDef` for a given trait. This allows you to
90     /// figure out the set of type parameters defined on the trait.
91     fn get_trait_def(&self, span: Span, id: DefId)
92                      -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
93
94     /// Ensure that the super-predicates for the trait with the given
95     /// id are available and also for the transitive set of
96     /// super-predicates.
97     fn ensure_super_predicates(&self, span: Span, id: DefId)
98                                -> Result<(), ErrorReported>;
99
100     /// Returns the set of bounds in scope for the type parameter with
101     /// the given id.
102     fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
103                                  -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
104
105     /// Returns true if the trait with id `trait_def_id` defines an
106     /// associated type with the name `name`.
107     fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
108                                            -> bool;
109
110     /// Return an (optional) substitution to convert bound type parameters that
111     /// are in scope into free ones. This function should only return Some
112     /// within a fn body.
113     /// See ParameterEnvironment::free_substs for more information.
114     fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
115
116     /// What type should we use when a type is omitted?
117     fn ty_infer(&self,
118                 param_and_substs: Option<ty::TypeParameterDef<'tcx>>,
119                 substs: Option<&mut Substs<'tcx>>,
120                 space: Option<ParamSpace>,
121                 span: Span) -> Ty<'tcx>;
122
123     /// Projecting an associated type from a (potentially)
124     /// higher-ranked trait reference is more complicated, because of
125     /// the possibility of late-bound regions appearing in the
126     /// associated type binding. This is not legal in function
127     /// signatures for that reason. In a function body, we can always
128     /// handle it because we can use inference variables to remove the
129     /// late-bound regions.
130     fn projected_ty_from_poly_trait_ref(&self,
131                                         span: Span,
132                                         poly_trait_ref: ty::PolyTraitRef<'tcx>,
133                                         item_name: ast::Name)
134                                         -> Ty<'tcx>;
135
136     /// Project an associated type from a non-higher-ranked trait reference.
137     /// This is fairly straightforward and can be accommodated in any context.
138     fn projected_ty(&self,
139                     span: Span,
140                     _trait_ref: ty::TraitRef<'tcx>,
141                     _item_name: ast::Name)
142                     -> Ty<'tcx>;
143
144     /// Invoked when we encounter an error from some prior pass
145     /// (e.g. resolve) that is translated into a ty-error. This is
146     /// used to help suppress derived errors typeck might otherwise
147     /// report.
148     fn set_tainted_by_errors(&self);
149 }
150
151 #[derive(PartialEq, Eq)]
152 pub enum PathParamMode {
153     // Any path in a type context.
154     Explicit,
155     // The `module::Type` in `module::Type::method` in an expression.
156     Optional
157 }
158
159 struct ConvertedBinding<'tcx> {
160     item_name: ast::Name,
161     ty: Ty<'tcx>,
162     span: Span,
163 }
164
165 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
166
167 pub fn ast_region_to_region(tcx: TyCtxt, lifetime: &hir::Lifetime)
168                             -> ty::Region {
169     let r = match tcx.named_region_map.defs.get(&lifetime.id) {
170         None => {
171             // should have been recorded by the `resolve_lifetime` pass
172             span_bug!(lifetime.span, "unresolved lifetime");
173         }
174
175         Some(&rl::DefStaticRegion) => {
176             ty::ReStatic
177         }
178
179         Some(&rl::DefLateBoundRegion(debruijn, id)) => {
180             // If this region is declared on a function, it will have
181             // an entry in `late_bound`, but if it comes from
182             // `for<'a>` in some type or something, it won't
183             // necessarily have one. In that case though, we won't be
184             // changed from late to early bound, so we can just
185             // substitute false.
186             let issue_32330 = tcx.named_region_map
187                                  .late_bound
188                                  .get(&id)
189                                  .cloned()
190                                  .unwrap_or(ty::Issue32330::WontChange);
191             ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id),
192                                                   lifetime.name,
193                                                   issue_32330))
194         }
195
196         Some(&rl::DefEarlyBoundRegion(space, index, _)) => {
197             ty::ReEarlyBound(ty::EarlyBoundRegion {
198                 space: space,
199                 index: index,
200                 name: lifetime.name
201             })
202         }
203
204         Some(&rl::DefFreeRegion(scope, id)) => {
205             // As in DefLateBoundRegion above, could be missing for some late-bound
206             // regions, but also for early-bound regions.
207             let issue_32330 = tcx.named_region_map
208                                  .late_bound
209                                  .get(&id)
210                                  .cloned()
211                                  .unwrap_or(ty::Issue32330::WontChange);
212             ty::ReFree(ty::FreeRegion {
213                     scope: scope.to_code_extent(&tcx.region_maps),
214                     bound_region: ty::BrNamed(tcx.map.local_def_id(id),
215                                               lifetime.name,
216                                               issue_32330)
217             })
218
219                 // (*) -- not late-bound, won't change
220         }
221     };
222
223     debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
224            lifetime,
225            lifetime.id,
226            r);
227
228     r
229 }
230
231 fn report_elision_failure(
232     db: &mut DiagnosticBuilder,
233     params: Vec<ElisionFailureInfo>)
234 {
235     let mut m = String::new();
236     let len = params.len();
237
238     let elided_params: Vec<_> = params.into_iter()
239                                        .filter(|info| info.lifetime_count > 0)
240                                        .collect();
241
242     let elided_len = elided_params.len();
243
244     for (i, info) in elided_params.into_iter().enumerate() {
245         let ElisionFailureInfo {
246             name, lifetime_count: n, have_bound_regions
247         } = info;
248
249         let help_name = if name.is_empty() {
250             format!("argument {}", i + 1)
251         } else {
252             format!("`{}`", name)
253         };
254
255         m.push_str(&(if n == 1 {
256             help_name
257         } else {
258             format!("one of {}'s {} elided {}lifetimes", help_name, n,
259                     if have_bound_regions { "free " } else { "" } )
260         })[..]);
261
262         if elided_len == 2 && i == 0 {
263             m.push_str(" or ");
264         } else if i + 2 == elided_len {
265             m.push_str(", or ");
266         } else if i != elided_len - 1 {
267             m.push_str(", ");
268         }
269
270     }
271
272     if len == 0 {
273         help!(db,
274                    "this function's return type contains a borrowed value, but \
275                     there is no value for it to be borrowed from");
276         help!(db,
277                    "consider giving it a 'static lifetime");
278     } else if elided_len == 0 {
279         help!(db,
280                    "this function's return type contains a borrowed value with \
281                     an elided lifetime, but the lifetime cannot be derived from \
282                     the arguments");
283         help!(db,
284                    "consider giving it an explicit bounded or 'static \
285                     lifetime");
286     } else if elided_len == 1 {
287         help!(db,
288                    "this function's return type contains a borrowed value, but \
289                     the signature does not say which {} it is borrowed from",
290                    m);
291     } else {
292         help!(db,
293                    "this function's return type contains a borrowed value, but \
294                     the signature does not say whether it is borrowed from {}",
295                    m);
296     }
297 }
298
299 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
300     pub fn opt_ast_region_to_region(&self,
301         rscope: &RegionScope,
302         default_span: Span,
303         opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
304     {
305         let r = match *opt_lifetime {
306             Some(ref lifetime) => {
307                 ast_region_to_region(self.tcx(), lifetime)
308             }
309
310             None => match rscope.anon_regions(default_span, 1) {
311                 Ok(rs) => rs[0],
312                 Err(params) => {
313                     let ampersand_span = Span { hi: default_span.lo, ..default_span};
314
315                     let mut err = struct_span_err!(self.tcx().sess, ampersand_span, E0106,
316                                                  "missing lifetime specifier");
317                     err.span_label(ampersand_span, &format!("expected lifetime parameter"));
318
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 self.tcx().expect_def(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 resolution = self.tcx().expect_resolution(ty.id);
1068                 match resolution.base_def {
1069                     Def::Trait(trait_def_id) if resolution.depth == 0 => {
1070                         let mut projection_bounds = Vec::new();
1071                         let trait_ref =
1072                             self.object_path_to_poly_trait_ref(rscope,
1073                                                                path.span,
1074                                                                PathParamMode::Explicit,
1075                                                                trait_def_id,
1076                                                                ty.id,
1077                                                                path.segments.last().unwrap(),
1078                                                                &mut projection_bounds);
1079                         Ok((trait_ref, projection_bounds))
1080                     }
1081                     _ => {
1082                         struct_span_err!(self.tcx().sess, ty.span, E0172,
1083                                   "expected a reference to a trait")
1084                             .span_label(ty.span, &format!("expected a trait"))
1085                             .emit();
1086                         Err(ErrorReported)
1087                     }
1088                 }
1089             }
1090             _ => {
1091                 let mut err = struct_span_err!(self.tcx().sess, ty.span, E0178,
1092                                                "expected a path on the left-hand side \
1093                                                 of `+`, not `{}`",
1094                                                pprust::ty_to_string(ty));
1095                 err.span_label(ty.span, &format!("expected a path"));
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         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1219             .span_label(span, &format!("ambiguous associated type"))
1220             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1221                   type_str, trait_str, name))
1222             .emit();
1223
1224     }
1225
1226     // Search for a bound on a type parameter which includes the associated item
1227     // given by assoc_name. ty_param_node_id is the node id for the type parameter
1228     // (which might be `Self`, but only if it is the `Self` of a trait, not an
1229     // impl). This function will fail if there are no suitable bounds or there is
1230     // any ambiguity.
1231     fn find_bound_for_assoc_item(&self,
1232                                  ty_param_node_id: ast::NodeId,
1233                                  ty_param_name: ast::Name,
1234                                  assoc_name: ast::Name,
1235                                  span: Span)
1236                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1237     {
1238         let tcx = self.tcx();
1239
1240         let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1241             Ok(v) => v,
1242             Err(ErrorReported) => {
1243                 return Err(ErrorReported);
1244             }
1245         };
1246
1247         // Ensure the super predicates and stop if we encountered an error.
1248         if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1249             return Err(ErrorReported);
1250         }
1251
1252         // Check that there is exactly one way to find an associated type with the
1253         // correct name.
1254         let suitable_bounds: Vec<_> =
1255             traits::transitive_bounds(tcx, &bounds)
1256             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name))
1257             .collect();
1258
1259         self.one_bound_for_assoc_type(suitable_bounds,
1260                                       &ty_param_name.as_str(),
1261                                       &assoc_name.as_str(),
1262                                       span)
1263     }
1264
1265
1266     // Checks that bounds contains exactly one element and reports appropriate
1267     // errors otherwise.
1268     fn one_bound_for_assoc_type(&self,
1269                                 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1270                                 ty_param_name: &str,
1271                                 assoc_name: &str,
1272                                 span: Span)
1273         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1274     {
1275         if bounds.is_empty() {
1276             span_err!(self.tcx().sess, span, E0220,
1277                       "associated type `{}` not found for `{}`",
1278                       assoc_name,
1279                       ty_param_name);
1280             return Err(ErrorReported);
1281         }
1282
1283         if bounds.len() > 1 {
1284             let mut err = struct_span_err!(self.tcx().sess, span, E0221,
1285                                            "ambiguous associated type `{}` in bounds of `{}`",
1286                                            assoc_name,
1287                                            ty_param_name);
1288
1289             for bound in &bounds {
1290                 span_note!(&mut err, span,
1291                            "associated type `{}` could derive from `{}`",
1292                            ty_param_name,
1293                            bound);
1294             }
1295             err.emit();
1296         }
1297
1298         Ok(bounds[0].clone())
1299     }
1300
1301     // Create a type from a path to an associated type.
1302     // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1303     // and item_segment is the path segment for D. We return a type and a def for
1304     // the whole path.
1305     // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1306     // parameter or Self.
1307     fn associated_path_def_to_ty(&self,
1308                                  span: Span,
1309                                  ty: Ty<'tcx>,
1310                                  ty_path_def: Def,
1311                                  item_segment: &hir::PathSegment)
1312                                  -> (Ty<'tcx>, Def)
1313     {
1314         let tcx = self.tcx();
1315         let assoc_name = item_segment.name;
1316
1317         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1318
1319         tcx.prohibit_type_params(slice::ref_slice(item_segment));
1320
1321         // Find the type of the associated item, and the trait where the associated
1322         // item is declared.
1323         let bound = match (&ty.sty, ty_path_def) {
1324             (_, Def::SelfTy(Some(trait_did), Some(impl_id))) => {
1325                 // For Def::SelfTy() values inlined from another crate, the
1326                 // impl_id will be DUMMY_NODE_ID, which would cause problems
1327                 // here. But we should never run into an impl from another crate
1328                 // in this pass.
1329                 assert!(impl_id != ast::DUMMY_NODE_ID);
1330
1331                 // `Self` in an impl of a trait - we have a concrete self type and a
1332                 // trait reference.
1333                 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1334                 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1335                     trait_ref.subst(tcx, free_substs)
1336                 } else {
1337                     trait_ref
1338                 };
1339
1340                 if self.ensure_super_predicates(span, trait_did).is_err() {
1341                     return (tcx.types.err, Def::Err);
1342                 }
1343
1344                 let candidates: Vec<ty::PolyTraitRef> =
1345                     traits::supertraits(tcx, ty::Binder(trait_ref))
1346                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1347                                                                          assoc_name))
1348                     .collect();
1349
1350                 match self.one_bound_for_assoc_type(candidates,
1351                                                     "Self",
1352                                                     &assoc_name.as_str(),
1353                                                     span) {
1354                     Ok(bound) => bound,
1355                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1356                 }
1357             }
1358             (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1359                 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1360                 match self.find_bound_for_assoc_item(trait_node_id,
1361                                                      keywords::SelfType.name(),
1362                                                      assoc_name,
1363                                                      span) {
1364                     Ok(bound) => bound,
1365                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1366                 }
1367             }
1368             (&ty::TyParam(_), Def::TyParam(_, _, param_did, param_name)) => {
1369                 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1370                 match self.find_bound_for_assoc_item(param_node_id,
1371                                                      param_name,
1372                                                      assoc_name,
1373                                                      span) {
1374                     Ok(bound) => bound,
1375                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1376                 }
1377             }
1378             _ => {
1379                 self.report_ambiguous_associated_type(span,
1380                                                       &ty.to_string(),
1381                                                       "Trait",
1382                                                       &assoc_name.as_str());
1383                 return (tcx.types.err, Def::Err);
1384             }
1385         };
1386
1387         let trait_did = bound.0.def_id;
1388         let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1389
1390         let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1391             // `ty::trait_items` used below requires information generated
1392             // by type collection, which may be in progress at this point.
1393             match tcx.map.expect_item(trait_id).node {
1394                 hir::ItemTrait(_, _, _, ref trait_items) => {
1395                     let item = trait_items.iter()
1396                                           .find(|i| i.name == assoc_name)
1397                                           .expect("missing associated type");
1398                     tcx.map.local_def_id(item.id)
1399                 }
1400                 _ => bug!()
1401             }
1402         } else {
1403             let trait_items = tcx.trait_items(trait_did);
1404             let item = trait_items.iter().find(|i| i.name() == assoc_name);
1405             item.expect("missing associated type").def_id()
1406         };
1407
1408         (ty, Def::AssociatedTy(trait_did, item_did))
1409     }
1410
1411     fn qpath_to_ty(&self,
1412                    rscope: &RegionScope,
1413                    span: Span,
1414                    param_mode: PathParamMode,
1415                    opt_self_ty: Option<Ty<'tcx>>,
1416                    trait_def_id: DefId,
1417                    trait_segment: &hir::PathSegment,
1418                    item_segment: &hir::PathSegment)
1419                    -> Ty<'tcx>
1420     {
1421         let tcx = self.tcx();
1422
1423         tcx.prohibit_type_params(slice::ref_slice(item_segment));
1424
1425         let self_ty = if let Some(ty) = opt_self_ty {
1426             ty
1427         } else {
1428             let path_str = tcx.item_path_str(trait_def_id);
1429             self.report_ambiguous_associated_type(span,
1430                                                   "Type",
1431                                                   &path_str,
1432                                                   &item_segment.name.as_str());
1433             return tcx.types.err;
1434         };
1435
1436         debug!("qpath_to_ty: self_type={:?}", self_ty);
1437
1438         let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1439                                                         span,
1440                                                         param_mode,
1441                                                         trait_def_id,
1442                                                         Some(self_ty),
1443                                                         trait_segment);
1444
1445         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1446
1447         self.projected_ty(span, trait_ref, item_segment.name)
1448     }
1449
1450     /// Convert a type supplied as value for a type argument from AST into our
1451     /// our internal representation. This is the same as `ast_ty_to_ty` but that
1452     /// it applies the object lifetime default.
1453     ///
1454     /// # Parameters
1455     ///
1456     /// * `this`, `rscope`: the surrounding context
1457     /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1458     ///   referenced
1459     /// * `index`: the index of the type parameter being instantiated from the list
1460     ///   (we assume it is in the `TypeSpace`)
1461     /// * `region_substs`: a partial substitution consisting of
1462     ///   only the region type parameters being supplied to this type.
1463     /// * `ast_ty`: the ast representation of the type being supplied
1464     pub fn ast_ty_arg_to_ty(&self,
1465                             rscope: &RegionScope,
1466                             decl_generics: &ty::Generics<'tcx>,
1467                             index: usize,
1468                             region_substs: &Substs<'tcx>,
1469                             ast_ty: &hir::Ty)
1470                             -> Ty<'tcx>
1471     {
1472         let tcx = self.tcx();
1473
1474         if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1475             let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1476             let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1477             self.ast_ty_to_ty(rscope1, ast_ty)
1478         } else {
1479             self.ast_ty_to_ty(rscope, ast_ty)
1480         }
1481     }
1482
1483     // Check the base def in a PathResolution and convert it to a Ty. If there are
1484     // associated types in the PathResolution, these will need to be separately
1485     // resolved.
1486     fn base_def_to_ty(&self,
1487                       rscope: &RegionScope,
1488                       span: Span,
1489                       param_mode: PathParamMode,
1490                       def: Def,
1491                       opt_self_ty: Option<Ty<'tcx>>,
1492                       base_path_ref_id: ast::NodeId,
1493                       base_segments: &[hir::PathSegment])
1494                       -> Ty<'tcx> {
1495         let tcx = self.tcx();
1496
1497         debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, base_segments={:?})",
1498                def, opt_self_ty, base_segments);
1499
1500         match def {
1501             Def::Trait(trait_def_id) => {
1502                 // N.B. this case overlaps somewhat with
1503                 // TyObjectSum, see that fn for details
1504                 let mut projection_bounds = Vec::new();
1505
1506                 let trait_ref =
1507                     self.object_path_to_poly_trait_ref(rscope,
1508                                                        span,
1509                                                        param_mode,
1510                                                        trait_def_id,
1511                                                        base_path_ref_id,
1512                                                        base_segments.last().unwrap(),
1513                                                        &mut projection_bounds);
1514
1515                 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1516                 self.trait_ref_to_object_type(rscope,
1517                                               span,
1518                                               trait_ref,
1519                                               projection_bounds,
1520                                               &[])
1521             }
1522             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) => {
1523                 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1524                 self.ast_path_to_ty(rscope,
1525                                     span,
1526                                     param_mode,
1527                                     did,
1528                                     base_segments.last().unwrap())
1529             }
1530             Def::TyParam(space, index, _, name) => {
1531                 tcx.prohibit_type_params(base_segments);
1532                 tcx.mk_param(space, index, name)
1533             }
1534             Def::SelfTy(_, Some(impl_id)) => {
1535                 // Self in impl (we know the concrete type).
1536
1537                 // For Def::SelfTy() values inlined from another crate, the
1538                 // impl_id will be DUMMY_NODE_ID, which would cause problems
1539                 // here. But we should never run into an impl from another crate
1540                 // in this pass.
1541                 assert!(impl_id != ast::DUMMY_NODE_ID);
1542
1543                 tcx.prohibit_type_params(base_segments);
1544                 let ty = tcx.node_id_to_type(impl_id);
1545                 if let Some(free_substs) = self.get_free_substs() {
1546                     ty.subst(tcx, free_substs)
1547                 } else {
1548                     ty
1549                 }
1550             }
1551             Def::SelfTy(Some(_), None) => {
1552                 // Self in trait.
1553                 tcx.prohibit_type_params(base_segments);
1554                 tcx.mk_self_type()
1555             }
1556             Def::AssociatedTy(trait_did, _) => {
1557                 tcx.prohibit_type_params(&base_segments[..base_segments.len()-2]);
1558                 self.qpath_to_ty(rscope,
1559                                  span,
1560                                  param_mode,
1561                                  opt_self_ty,
1562                                  trait_did,
1563                                  &base_segments[base_segments.len()-2],
1564                                  base_segments.last().unwrap())
1565             }
1566             Def::Mod(..) => {
1567                 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1568                 // FIXME(#22519) This part of the resolution logic should be
1569                 // avoided entirely for that form, once we stop needed a Def
1570                 // for `associated_path_def_to_ty`.
1571                 // Fixing this will also let use resolve <Self>::Foo the same way we
1572                 // resolve Self::Foo, at the moment we can't resolve the former because
1573                 // we don't have the trait information around, which is just sad.
1574
1575                 assert!(base_segments.is_empty());
1576
1577                 opt_self_ty.expect("missing T in <T>::a::b::c")
1578             }
1579             Def::PrimTy(prim_ty) => {
1580                 tcx.prim_ty_to_ty(base_segments, prim_ty)
1581             }
1582             Def::Err => {
1583                 self.set_tainted_by_errors();
1584                 return self.tcx().types.err;
1585             }
1586             _ => {
1587                 span_err!(tcx.sess, span, E0248,
1588                           "found value `{}` used as a type",
1589                           tcx.item_path_str(def.def_id()));
1590                 return self.tcx().types.err;
1591             }
1592         }
1593     }
1594
1595     // Resolve possibly associated type path into a type and final definition.
1596     // Note that both base_segments and assoc_segments may be empty, although not at same time.
1597     pub fn finish_resolving_def_to_ty(&self,
1598                                       rscope: &RegionScope,
1599                                       span: Span,
1600                                       param_mode: PathParamMode,
1601                                       base_def: Def,
1602                                       opt_self_ty: Option<Ty<'tcx>>,
1603                                       base_path_ref_id: ast::NodeId,
1604                                       base_segments: &[hir::PathSegment],
1605                                       assoc_segments: &[hir::PathSegment])
1606                                       -> (Ty<'tcx>, Def) {
1607         // Convert the base type.
1608         debug!("finish_resolving_def_to_ty(base_def={:?}, \
1609                 base_segments={:?}, \
1610                 assoc_segments={:?})",
1611                base_def,
1612                base_segments,
1613                assoc_segments);
1614         let base_ty = self.base_def_to_ty(rscope,
1615                                           span,
1616                                           param_mode,
1617                                           base_def,
1618                                           opt_self_ty,
1619                                           base_path_ref_id,
1620                                           base_segments);
1621         debug!("finish_resolving_def_to_ty: base_def_to_ty returned {:?}", base_ty);
1622
1623         // If any associated type segments remain, attempt to resolve them.
1624         let (mut ty, mut def) = (base_ty, base_def);
1625         for segment in assoc_segments {
1626             debug!("finish_resolving_def_to_ty: segment={:?}", segment);
1627             // This is pretty bad (it will fail except for T::A and Self::A).
1628             let (new_ty, new_def) = self.associated_path_def_to_ty(span, ty, def, segment);
1629             ty = new_ty;
1630             def = new_def;
1631
1632             if def == Def::Err {
1633                 break;
1634             }
1635         }
1636         (ty, def)
1637     }
1638
1639     /// Parses the programmer's textual representation of a type into our
1640     /// internal notion of a type.
1641     pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1642         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1643                ast_ty.id, ast_ty);
1644
1645         let tcx = self.tcx();
1646
1647         let cache = self.ast_ty_to_ty_cache();
1648         match cache.borrow().get(&ast_ty.id) {
1649             Some(ty) => { return ty; }
1650             None => { }
1651         }
1652
1653         let result_ty = match ast_ty.node {
1654             hir::TyVec(ref ty) => {
1655                 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1656             }
1657             hir::TyObjectSum(ref ty, ref bounds) => {
1658                 match self.ast_ty_to_trait_ref(rscope, &ty, bounds) {
1659                     Ok((trait_ref, projection_bounds)) => {
1660                         self.trait_ref_to_object_type(rscope,
1661                                                       ast_ty.span,
1662                                                       trait_ref,
1663                                                       projection_bounds,
1664                                                       bounds)
1665                     }
1666                     Err(ErrorReported) => {
1667                         self.tcx().types.err
1668                     }
1669                 }
1670             }
1671             hir::TyPtr(ref mt) => {
1672                 tcx.mk_ptr(ty::TypeAndMut {
1673                     ty: self.ast_ty_to_ty(rscope, &mt.ty),
1674                     mutbl: mt.mutbl
1675                 })
1676             }
1677             hir::TyRptr(ref region, ref mt) => {
1678                 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, region);
1679                 debug!("TyRef r={:?}", r);
1680                 let rscope1 =
1681                     &ObjectLifetimeDefaultRscope::new(
1682                         rscope,
1683                         ty::ObjectLifetimeDefault::Specific(r));
1684                 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1685                 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1686             }
1687             hir::TyTup(ref fields) => {
1688                 let flds = fields.iter()
1689                                  .map(|t| self.ast_ty_to_ty(rscope, &t))
1690                                  .collect();
1691                 tcx.mk_tup(flds)
1692             }
1693             hir::TyBareFn(ref bf) => {
1694                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1695                 let bare_fn_ty = self.ty_of_bare_fn(bf.unsafety, bf.abi, &bf.decl);
1696
1697                 // Find any late-bound regions declared in return type that do
1698                 // not appear in the arguments. These are not wellformed.
1699                 //
1700                 // Example:
1701                 //
1702                 //     for<'a> fn() -> &'a str <-- 'a is bad
1703                 //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1704                 //
1705                 // Note that we do this check **here** and not in
1706                 // `ty_of_bare_fn` because the latter is also used to make
1707                 // the types for fn items, and we do not want to issue a
1708                 // warning then. (Once we fix #32330, the regions we are
1709                 // checking for here would be considered early bound
1710                 // anyway.)
1711                 let inputs = bare_fn_ty.sig.inputs();
1712                 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(&inputs);
1713                 let output = bare_fn_ty.sig.output();
1714                 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1715                 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1716                     let br_name = match *br {
1717                         ty::BrNamed(_, name, _) => name,
1718                         _ => {
1719                             span_bug!(
1720                                 bf.decl.output.span(),
1721                                 "anonymous bound region {:?} in return but not args",
1722                                 br);
1723                         }
1724                     };
1725                     tcx.sess.add_lint(
1726                         lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1727                         ast_ty.id,
1728                         ast_ty.span,
1729                         format!("return type references lifetime `{}`, \
1730                                  which does not appear in the trait input types",
1731                                 br_name));
1732                 }
1733                 tcx.mk_fn_ptr(bare_fn_ty)
1734             }
1735             hir::TyPolyTraitRef(ref bounds) => {
1736                 self.conv_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1737             }
1738             hir::TyPath(ref maybe_qself, ref path) => {
1739                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1740                 let path_res = tcx.expect_resolution(ast_ty.id);
1741                 let base_ty_end = path.segments.len() - path_res.depth;
1742                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1743                     self.ast_ty_to_ty(rscope, &qself.ty)
1744                 });
1745                 let (ty, def) = self.finish_resolving_def_to_ty(rscope,
1746                                                                 ast_ty.span,
1747                                                                 PathParamMode::Explicit,
1748                                                                 path_res.base_def,
1749                                                                 opt_self_ty,
1750                                                                 ast_ty.id,
1751                                                                 &path.segments[..base_ty_end],
1752                                                                 &path.segments[base_ty_end..]);
1753
1754                 // Write back the new resolution.
1755                 if path_res.depth != 0 {
1756                     tcx.def_map.borrow_mut().insert(ast_ty.id, PathResolution::new(def));
1757                 }
1758
1759                 ty
1760             }
1761             hir::TyFixedLengthVec(ref ty, ref e) => {
1762                 if let Ok(length) = eval_length(tcx.global_tcx(), &e, "array length") {
1763                     tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), length)
1764                 } else {
1765                     self.tcx().types.err
1766                 }
1767             }
1768             hir::TyTypeof(ref _e) => {
1769                 span_err!(tcx.sess, ast_ty.span, E0516,
1770                       "`typeof` is a reserved keyword but unimplemented");
1771                 tcx.types.err
1772             }
1773             hir::TyInfer => {
1774                 // TyInfer also appears as the type of arguments or return
1775                 // values in a ExprClosure, or as
1776                 // the type of local variables. Both of these cases are
1777                 // handled specially and will not descend into this routine.
1778                 self.ty_infer(None, None, None, ast_ty.span)
1779             }
1780         };
1781
1782         cache.borrow_mut().insert(ast_ty.id, result_ty);
1783
1784         result_ty
1785     }
1786
1787     pub fn ty_of_arg(&self,
1788                      rscope: &RegionScope,
1789                      a: &hir::Arg,
1790                      expected_ty: Option<Ty<'tcx>>)
1791                      -> Ty<'tcx>
1792     {
1793         match a.ty.node {
1794             hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1795             hir::TyInfer => self.ty_infer(None, None, None, a.ty.span),
1796             _ => self.ast_ty_to_ty(rscope, &a.ty),
1797         }
1798     }
1799
1800     pub fn ty_of_method(&self,
1801                         sig: &hir::MethodSig,
1802                         untransformed_self_ty: Ty<'tcx>)
1803                         -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1804         let (bare_fn_ty, optional_explicit_self_category) =
1805             self.ty_of_method_or_bare_fn(sig.unsafety,
1806                                          sig.abi,
1807                                          Some(untransformed_self_ty),
1808                                          &sig.decl);
1809         (bare_fn_ty, optional_explicit_self_category)
1810     }
1811
1812     pub fn ty_of_bare_fn(&self,
1813                          unsafety: hir::Unsafety,
1814                          abi: abi::Abi,
1815                          decl: &hir::FnDecl)
1816                          -> &'tcx ty::BareFnTy<'tcx> {
1817         self.ty_of_method_or_bare_fn(unsafety, abi, None, decl).0
1818     }
1819
1820     fn ty_of_method_or_bare_fn<'a>(&self,
1821                                    unsafety: hir::Unsafety,
1822                                    abi: abi::Abi,
1823                                    opt_untransformed_self_ty: Option<Ty<'tcx>>,
1824                                    decl: &hir::FnDecl)
1825                                    -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory)
1826     {
1827         debug!("ty_of_method_or_bare_fn");
1828
1829         // New region names that appear inside of the arguments of the function
1830         // declaration are bound to that function type.
1831         let rb = rscope::BindingRscope::new();
1832
1833         // `implied_output_region` is the region that will be assumed for any
1834         // region parameters in the return type. In accordance with the rules for
1835         // lifetime elision, we can determine it in two ways. First (determined
1836         // here), if self is by-reference, then the implied output region is the
1837         // region of the self parameter.
1838         let (self_ty, explicit_self_category) = match (opt_untransformed_self_ty, decl.get_self()) {
1839             (Some(untransformed_self_ty), Some(explicit_self)) => {
1840                 let self_type = self.determine_self_type(&rb, untransformed_self_ty,
1841                                                          &explicit_self);
1842                 (Some(self_type.0), self_type.1)
1843             }
1844             _ => (None, ty::ExplicitSelfCategory::Static),
1845         };
1846
1847         // HACK(eddyb) replace the fake self type in the AST with the actual type.
1848         let arg_params = if self_ty.is_some() {
1849             &decl.inputs[1..]
1850         } else {
1851             &decl.inputs[..]
1852         };
1853         let arg_tys: Vec<Ty> =
1854             arg_params.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1855         let arg_pats: Vec<String> =
1856             arg_params.iter().map(|a| pprust::pat_to_string(&a.pat)).collect();
1857
1858         // Second, if there was exactly one lifetime (either a substitution or a
1859         // reference) in the arguments, then any anonymous regions in the output
1860         // have that lifetime.
1861         let implied_output_region = match explicit_self_category {
1862             ty::ExplicitSelfCategory::ByReference(region, _) => Ok(region),
1863             _ => self.find_implied_output_region(&arg_tys, arg_pats)
1864         };
1865
1866         let output_ty = match decl.output {
1867             hir::Return(ref output) =>
1868                 ty::FnConverging(self.convert_ty_with_lifetime_elision(implied_output_region,
1869                                                                        &output)),
1870             hir::DefaultReturn(..) => ty::FnConverging(self.tcx().mk_nil()),
1871             hir::NoReturn(..) => ty::FnDiverging
1872         };
1873
1874         (self.tcx().mk_bare_fn(ty::BareFnTy {
1875             unsafety: unsafety,
1876             abi: abi,
1877             sig: ty::Binder(ty::FnSig {
1878                 inputs: self_ty.into_iter().chain(arg_tys).collect(),
1879                 output: output_ty,
1880                 variadic: decl.variadic
1881             }),
1882         }), explicit_self_category)
1883     }
1884
1885     fn determine_self_type<'a>(&self,
1886                                rscope: &RegionScope,
1887                                untransformed_self_ty: Ty<'tcx>,
1888                                explicit_self: &hir::ExplicitSelf)
1889                                -> (Ty<'tcx>, ty::ExplicitSelfCategory)
1890     {
1891         return match explicit_self.node {
1892             SelfKind::Value(..) => {
1893                 (untransformed_self_ty, ty::ExplicitSelfCategory::ByValue)
1894             }
1895             SelfKind::Region(ref lifetime, mutability) => {
1896                 let region =
1897                     self.opt_ast_region_to_region(
1898                                              rscope,
1899                                              explicit_self.span,
1900                                              lifetime);
1901                 (self.tcx().mk_ref(
1902                     self.tcx().mk_region(region),
1903                     ty::TypeAndMut {
1904                         ty: untransformed_self_ty,
1905                         mutbl: mutability
1906                     }),
1907                  ty::ExplicitSelfCategory::ByReference(region, mutability))
1908             }
1909             SelfKind::Explicit(ref ast_type, _) => {
1910                 let explicit_type = self.ast_ty_to_ty(rscope, &ast_type);
1911
1912                 // We wish to (for now) categorize an explicit self
1913                 // declaration like `self: SomeType` into either `self`,
1914                 // `&self`, `&mut self`, or `Box<self>`. We do this here
1915                 // by some simple pattern matching. A more precise check
1916                 // is done later in `check_method_self_type()`.
1917                 //
1918                 // Examples:
1919                 //
1920                 // ```
1921                 // impl Foo for &T {
1922                 //     // Legal declarations:
1923                 //     fn method1(self: &&T); // ExplicitSelfCategory::ByReference
1924                 //     fn method2(self: &T); // ExplicitSelfCategory::ByValue
1925                 //     fn method3(self: Box<&T>); // ExplicitSelfCategory::ByBox
1926                 //
1927                 //     // Invalid cases will be caught later by `check_method_self_type`:
1928                 //     fn method_err1(self: &mut T); // ExplicitSelfCategory::ByReference
1929                 // }
1930                 // ```
1931                 //
1932                 // To do the check we just count the number of "modifiers"
1933                 // on each type and compare them. If they are the same or
1934                 // the impl has more, we call it "by value". Otherwise, we
1935                 // look at the outermost modifier on the method decl and
1936                 // call it by-ref, by-box as appropriate. For method1, for
1937                 // example, the impl type has one modifier, but the method
1938                 // type has two, so we end up with
1939                 // ExplicitSelfCategory::ByReference.
1940
1941                 let impl_modifiers = count_modifiers(untransformed_self_ty);
1942                 let method_modifiers = count_modifiers(explicit_type);
1943
1944                 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1945                        explicit_type={:?} \
1946                        modifiers=({},{})",
1947                        untransformed_self_ty,
1948                        explicit_type,
1949                        impl_modifiers,
1950                        method_modifiers);
1951
1952                 let category = if impl_modifiers >= method_modifiers {
1953                     ty::ExplicitSelfCategory::ByValue
1954                 } else {
1955                     match explicit_type.sty {
1956                         ty::TyRef(r, mt) => ty::ExplicitSelfCategory::ByReference(*r, mt.mutbl),
1957                         ty::TyBox(_) => ty::ExplicitSelfCategory::ByBox,
1958                         _ => ty::ExplicitSelfCategory::ByValue,
1959                     }
1960                 };
1961
1962                 (explicit_type, category)
1963             }
1964         };
1965
1966         fn count_modifiers(ty: Ty) -> usize {
1967             match ty.sty {
1968                 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1969                 ty::TyBox(t) => count_modifiers(t) + 1,
1970                 _ => 0,
1971             }
1972         }
1973     }
1974
1975     pub fn ty_of_closure(&self,
1976         unsafety: hir::Unsafety,
1977         decl: &hir::FnDecl,
1978         abi: abi::Abi,
1979         expected_sig: Option<ty::FnSig<'tcx>>)
1980         -> ty::ClosureTy<'tcx>
1981     {
1982         debug!("ty_of_closure(expected_sig={:?})",
1983                expected_sig);
1984
1985         // new region names that appear inside of the fn decl are bound to
1986         // that function type
1987         let rb = rscope::BindingRscope::new();
1988
1989         let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1990             let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1991                 // no guarantee that the correct number of expected args
1992                 // were supplied
1993                 if i < e.inputs.len() {
1994                     Some(e.inputs[i])
1995                 } else {
1996                     None
1997                 }
1998             });
1999             self.ty_of_arg(&rb, a, expected_arg_ty)
2000         }).collect();
2001
2002         let expected_ret_ty = expected_sig.map(|e| e.output);
2003
2004         let is_infer = match decl.output {
2005             hir::Return(ref output) if output.node == hir::TyInfer => true,
2006             hir::DefaultReturn(..) => true,
2007             _ => false
2008         };
2009
2010         let output_ty = match decl.output {
2011             _ if is_infer && expected_ret_ty.is_some() =>
2012                 expected_ret_ty.unwrap(),
2013             _ if is_infer =>
2014                 ty::FnConverging(self.ty_infer(None, None, None, decl.output.span())),
2015             hir::Return(ref output) =>
2016                 ty::FnConverging(self.ast_ty_to_ty(&rb, &output)),
2017             hir::DefaultReturn(..) => bug!(),
2018             hir::NoReturn(..) => ty::FnDiverging
2019         };
2020
2021         debug!("ty_of_closure: input_tys={:?}", input_tys);
2022         debug!("ty_of_closure: output_ty={:?}", output_ty);
2023
2024         ty::ClosureTy {
2025             unsafety: unsafety,
2026             abi: abi,
2027             sig: ty::Binder(ty::FnSig {inputs: input_tys,
2028                                        output: output_ty,
2029                                        variadic: decl.variadic}),
2030         }
2031     }
2032
2033     /// Given an existential type like `Foo+'a+Bar`, this routine converts
2034     /// the `'a` and `Bar` intos an `ExistentialBounds` struct.
2035     /// The `main_trait_refs` argument specifies the `Foo` -- it is absent
2036     /// for closures. Eventually this should all be normalized, I think,
2037     /// so that there is no "main trait ref" and instead we just have a flat
2038     /// list of bounds as the existential type.
2039     fn conv_existential_bounds(&self,
2040         rscope: &RegionScope,
2041         span: Span,
2042         principal_trait_ref: ty::PolyTraitRef<'tcx>,
2043         projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2044         ast_bounds: &[hir::TyParamBound])
2045         -> ty::ExistentialBounds<'tcx>
2046     {
2047         let partitioned_bounds =
2048             partition_bounds(self.tcx(), span, ast_bounds);
2049
2050         self.conv_existential_bounds_from_partitioned_bounds(
2051             rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2052     }
2053
2054     fn conv_ty_poly_trait_ref(&self,
2055         rscope: &RegionScope,
2056         span: Span,
2057         ast_bounds: &[hir::TyParamBound])
2058         -> Ty<'tcx>
2059     {
2060         let mut partitioned_bounds = partition_bounds(self.tcx(), span, &ast_bounds[..]);
2061
2062         let mut projection_bounds = Vec::new();
2063         let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2064             let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2065             self.instantiate_poly_trait_ref(rscope,
2066                                             trait_bound,
2067                                             None,
2068                                             &mut projection_bounds)
2069         } else {
2070             span_err!(self.tcx().sess, span, E0224,
2071                       "at least one non-builtin trait is required for an object type");
2072             return self.tcx().types.err;
2073         };
2074
2075         let bounds =
2076             self.conv_existential_bounds_from_partitioned_bounds(rscope,
2077                                                                  span,
2078                                                                  main_trait_bound.clone(),
2079                                                                  projection_bounds,
2080                                                                  partitioned_bounds);
2081
2082         self.make_object_type(span, main_trait_bound, bounds)
2083     }
2084
2085     pub fn conv_existential_bounds_from_partitioned_bounds(&self,
2086         rscope: &RegionScope,
2087         span: Span,
2088         principal_trait_ref: ty::PolyTraitRef<'tcx>,
2089         projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2090         partitioned_bounds: PartitionedBounds)
2091         -> ty::ExistentialBounds<'tcx>
2092     {
2093         let PartitionedBounds { builtin_bounds,
2094                                 trait_bounds,
2095                                 region_bounds } =
2096             partitioned_bounds;
2097
2098         if !trait_bounds.is_empty() {
2099             let b = &trait_bounds[0];
2100             let span = b.trait_ref.path.span;
2101             struct_span_err!(self.tcx().sess, span, E0225,
2102                              "only the builtin traits can be used as closure or object bounds")
2103                 .span_label(span, &format!("non-builtin trait used as bounds"))
2104                 .emit();
2105         }
2106
2107         let region_bound =
2108             self.compute_object_lifetime_bound(span,
2109                                                &region_bounds,
2110                                                principal_trait_ref,
2111                                                builtin_bounds);
2112
2113         let region_bound = match region_bound {
2114             Some(r) => r,
2115             None => {
2116                 match rscope.object_lifetime_default(span) {
2117                     Some(r) => r,
2118                     None => {
2119                         span_err!(self.tcx().sess, span, E0228,
2120                                   "the lifetime bound for this object type cannot be deduced \
2121                                    from context; please supply an explicit bound");
2122                         ty::ReStatic
2123                     }
2124                 }
2125             }
2126         };
2127
2128         debug!("region_bound: {:?}", region_bound);
2129
2130         ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2131     }
2132
2133     /// Given the bounds on an object, determines what single region bound (if any) we can
2134     /// use to summarize this type. The basic idea is that we will use the bound the user
2135     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2136     /// for region bounds. It may be that we can derive no bound at all, in which case
2137     /// we return `None`.
2138     fn compute_object_lifetime_bound(&self,
2139         span: Span,
2140         explicit_region_bounds: &[&hir::Lifetime],
2141         principal_trait_ref: ty::PolyTraitRef<'tcx>,
2142         builtin_bounds: ty::BuiltinBounds)
2143         -> Option<ty::Region> // if None, use the default
2144     {
2145         let tcx = self.tcx();
2146
2147         debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2148                principal_trait_ref={:?}, builtin_bounds={:?})",
2149                explicit_region_bounds,
2150                principal_trait_ref,
2151                builtin_bounds);
2152
2153         if explicit_region_bounds.len() > 1 {
2154             span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2155                 "only a single explicit lifetime bound is permitted");
2156         }
2157
2158         if !explicit_region_bounds.is_empty() {
2159             // Explicitly specified region bound. Use that.
2160             let r = explicit_region_bounds[0];
2161             return Some(ast_region_to_region(tcx, r));
2162         }
2163
2164         if let Err(ErrorReported) =
2165                 self.ensure_super_predicates(span, principal_trait_ref.def_id()) {
2166             return Some(ty::ReStatic);
2167         }
2168
2169         // No explicit region bound specified. Therefore, examine trait
2170         // bounds and see if we can derive region bounds from those.
2171         let derived_region_bounds =
2172             object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2173
2174         // If there are no derived region bounds, then report back that we
2175         // can find no region bound. The caller will use the default.
2176         if derived_region_bounds.is_empty() {
2177             return None;
2178         }
2179
2180         // If any of the derived region bounds are 'static, that is always
2181         // the best choice.
2182         if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2183             return Some(ty::ReStatic);
2184         }
2185
2186         // Determine whether there is exactly one unique region in the set
2187         // of derived region bounds. If so, use that. Otherwise, report an
2188         // error.
2189         let r = derived_region_bounds[0];
2190         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2191             span_err!(tcx.sess, span, E0227,
2192                       "ambiguous lifetime bound, explicit lifetime bound required");
2193         }
2194         return Some(r);
2195     }
2196 }
2197
2198 pub struct PartitionedBounds<'a> {
2199     pub builtin_bounds: ty::BuiltinBounds,
2200     pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2201     pub region_bounds: Vec<&'a hir::Lifetime>,
2202 }
2203
2204 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2205 /// general trait bounds, and region bounds.
2206 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
2207                                             _span: Span,
2208                                             ast_bounds: &'b [hir::TyParamBound])
2209                                             -> PartitionedBounds<'b>
2210 {
2211     let mut builtin_bounds = ty::BuiltinBounds::empty();
2212     let mut region_bounds = Vec::new();
2213     let mut trait_bounds = Vec::new();
2214     for ast_bound in ast_bounds {
2215         match *ast_bound {
2216             hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2217                 match tcx.expect_def(b.trait_ref.ref_id) {
2218                     Def::Trait(trait_did) => {
2219                         if tcx.try_add_builtin_trait(trait_did,
2220                                                      &mut builtin_bounds) {
2221                             let segments = &b.trait_ref.path.segments;
2222                             let parameters = &segments[segments.len() - 1].parameters;
2223                             if !parameters.types().is_empty() {
2224                                 check_type_argument_count(tcx, b.trait_ref.path.span,
2225                                                           parameters.types().len(), 0, 0);
2226                             }
2227                             if !parameters.lifetimes().is_empty() {
2228                                 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2229                                                              parameters.lifetimes().len(), 0);
2230                             }
2231                             continue; // success
2232                         }
2233                     }
2234                     _ => {
2235                         // Not a trait? that's an error, but it'll get
2236                         // reported later.
2237                     }
2238                 }
2239                 trait_bounds.push(b);
2240             }
2241             hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2242             hir::RegionTyParamBound(ref l) => {
2243                 region_bounds.push(l);
2244             }
2245         }
2246     }
2247
2248     PartitionedBounds {
2249         builtin_bounds: builtin_bounds,
2250         trait_bounds: trait_bounds,
2251         region_bounds: region_bounds,
2252     }
2253 }
2254
2255 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
2256                              required: usize, accepted: usize) {
2257     if supplied < required {
2258         let expected = if required < accepted {
2259             "expected at least"
2260         } else {
2261             "expected"
2262         };
2263         struct_span_err!(tcx.sess, span, E0243, "wrong number of type arguments")
2264             .span_label(
2265                 span,
2266                 &format!("{} {} type arguments, found {}", expected, required, supplied)
2267             )
2268             .emit();
2269     } else if supplied > accepted {
2270         let expected = if required == 0 {
2271             "expected no".to_string()
2272         } else if required < accepted {
2273             format!("expected at most {}", accepted)
2274         } else {
2275             format!("expected {}", accepted)
2276         };
2277
2278         struct_span_err!(tcx.sess, span, E0244, "wrong number of type arguments")
2279             .span_label(
2280                 span,
2281                 &format!("{} type arguments, found {}", expected, supplied)
2282             )
2283             .emit();
2284     }
2285 }
2286
2287 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
2288     let label = if number < expected {
2289         if expected == 1 {
2290             format!("expected {} lifetime parameter", expected)
2291         } else {
2292             format!("expected {} lifetime parameters", expected)
2293         }
2294     } else {
2295         let additional = number - expected;
2296         if additional == 1 {
2297             "unexpected lifetime parameter".to_string()
2298         } else {
2299             format!("{} unexpected lifetime parameters", additional)
2300         }
2301     };
2302     struct_span_err!(tcx.sess, span, E0107,
2303                      "wrong number of lifetime parameters: expected {}, found {}",
2304                      expected, number)
2305         .span_label(span, &label)
2306         .emit();
2307 }
2308
2309 // A helper struct for conveniently grouping a set of bounds which we pass to
2310 // and return from functions in multiple places.
2311 #[derive(PartialEq, Eq, Clone, Debug)]
2312 pub struct Bounds<'tcx> {
2313     pub region_bounds: Vec<ty::Region>,
2314     pub builtin_bounds: ty::BuiltinBounds,
2315     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2316     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2317 }
2318
2319 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2320     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2321                       -> Vec<ty::Predicate<'tcx>>
2322     {
2323         let mut vec = Vec::new();
2324
2325         for builtin_bound in &self.builtin_bounds {
2326             match tcx.trait_ref_for_builtin_bound(builtin_bound, param_ty) {
2327                 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2328                 Err(ErrorReported) => { }
2329             }
2330         }
2331
2332         for &region_bound in &self.region_bounds {
2333             // account for the binder being introduced below; no need to shift `param_ty`
2334             // because, at present at least, it can only refer to early-bound regions
2335             let region_bound = ty::fold::shift_region(region_bound, 1);
2336             vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2337         }
2338
2339         for bound_trait_ref in &self.trait_bounds {
2340             vec.push(bound_trait_ref.to_predicate());
2341         }
2342
2343         for projection in &self.projection_bounds {
2344             vec.push(projection.to_predicate());
2345         }
2346
2347         vec
2348     }
2349 }