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