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