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