]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Add a doctest for the std::string::as_string method.
[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_ty()` function
20 //! triggers a recursive call to `ty_of_item()`  (note that
21 //! `ast_ty_to_ty()` will detect recursive types and report an error).
22 //! In the check phase, when the FnCtxt is used as the `AstConv`,
23 //! `get_item_ty()` just looks up the item type in `tcx.tcache`.
24 //!
25 //! The `RegionScope` trait controls what happens when the user does
26 //! not specify a region in some location where a region is required
27 //! (e.g., if the user writes `&Foo` as a type rather than `&'a Foo`).
28 //! See the `rscope` module for more details.
29 //!
30 //! Unlike the `AstConv` trait, the region scope can change as we descend
31 //! the type.  This is to accommodate the fact that (a) fn types are binding
32 //! scopes and (b) the default region may change.  To understand case (a),
33 //! consider something like:
34 //!
35 //!   type foo = { x: &a.int, y: |&a.int| }
36 //!
37 //! The type of `x` is an error because there is no region `a` in scope.
38 //! In the type of `y`, however, region `a` is considered a bound region
39 //! as it does not already appear in scope.
40 //!
41 //! Case (b) says that if you have a type:
42 //!   type foo<'a> = ...;
43 //!   type bar = fn(&foo, &a.foo)
44 //! The fully expanded version of type bar is:
45 //!   type bar = fn(&'foo &, &a.foo<'a>)
46 //! Note that the self region for the `foo` defaulted to `&` in the first
47 //! case but `&a` in the second.  Basically, defaults that appear inside
48 //! an rptr (`&r.T`) use the region `r` that appears in the rptr.
49
50 use middle::astconv_util::{ast_ty_to_prim_ty, check_path_args, NO_TPS, NO_REGIONS};
51 use middle::const_eval;
52 use middle::def;
53 use middle::resolve_lifetime as rl;
54 use middle::subst::{FnSpace, TypeSpace, AssocSpace, SelfSpace, Subst, Substs};
55 use middle::subst::{VecPerParamSpace};
56 use middle::ty::{mod, Ty};
57 use rscope::{mod, UnelidableRscope, RegionScope, SpecificRscope,
58              ShiftedRscope, BindingRscope};
59 use TypeAndSubsts;
60 use util::common::ErrorReported;
61 use util::nodemap::DefIdMap;
62 use util::ppaux::{mod, Repr, UserString};
63
64 use std::rc::Rc;
65 use std::iter::AdditiveIterator;
66 use syntax::{abi, ast, ast_util};
67 use syntax::codemap::Span;
68 use syntax::parse::token;
69 use syntax::print::pprust;
70
71 pub trait AstConv<'tcx> {
72     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
73     fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype<'tcx>;
74     fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef<'tcx>>;
75
76     /// What type should we use when a type is omitted?
77     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
78
79     /// Returns true if associated types from the given trait and type are
80     /// allowed to be used here and false otherwise.
81     fn associated_types_of_trait_are_valid(&self,
82                                            ty: Ty<'tcx>,
83                                            trait_id: ast::DefId)
84                                            -> bool;
85
86     /// Returns the binding of the given associated type for some type.
87     fn associated_type_binding(&self,
88                                span: Span,
89                                ty: Option<Ty<'tcx>>,
90                                trait_id: ast::DefId,
91                                associated_type_id: ast::DefId)
92                                -> Ty<'tcx>;
93 }
94
95 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &ast::Lifetime)
96                             -> ty::Region {
97     let r = match tcx.named_region_map.get(&lifetime.id) {
98         None => {
99             // should have been recorded by the `resolve_lifetime` pass
100             tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
101         }
102
103         Some(&rl::DefStaticRegion) => {
104             ty::ReStatic
105         }
106
107         Some(&rl::DefLateBoundRegion(debruijn, id)) => {
108             ty::ReLateBound(debruijn, ty::BrNamed(ast_util::local_def(id), lifetime.name))
109         }
110
111         Some(&rl::DefEarlyBoundRegion(space, index, id)) => {
112             ty::ReEarlyBound(id, space, index, lifetime.name)
113         }
114
115         Some(&rl::DefFreeRegion(scope, id)) => {
116             ty::ReFree(ty::FreeRegion {
117                     scope: scope,
118                     bound_region: ty::BrNamed(ast_util::local_def(id),
119                                               lifetime.name)
120                 })
121         }
122     };
123
124     debug!("ast_region_to_region(lifetime={} id={}) yields {}",
125            lifetime.repr(tcx),
126            lifetime.id,
127            r.repr(tcx));
128
129     r
130 }
131
132 pub fn opt_ast_region_to_region<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
133     this: &AC,
134     rscope: &RS,
135     default_span: Span,
136     opt_lifetime: &Option<ast::Lifetime>) -> ty::Region
137 {
138     let r = match *opt_lifetime {
139         Some(ref lifetime) => {
140             ast_region_to_region(this.tcx(), lifetime)
141         }
142
143         None => {
144             match rscope.anon_regions(default_span, 1) {
145                 Err(v) => {
146                     debug!("optional region in illegal location");
147                     span_err!(this.tcx().sess, default_span, E0106,
148                         "missing lifetime specifier");
149                     match v {
150                         Some(v) => {
151                             let mut m = String::new();
152                             let len = v.len();
153                             for (i, (name, n)) in v.into_iter().enumerate() {
154                                 m.push_str(if n == 1 {
155                                     format!("`{}`", name)
156                                 } else {
157                                     format!("one of `{}`'s {} elided lifetimes", name, n)
158                                 }.as_slice());
159
160                                 if len == 2 && i == 0 {
161                                     m.push_str(" or ");
162                                 } else if i == len - 2 {
163                                     m.push_str(", or ");
164                                 } else if i != len - 1 {
165                                     m.push_str(", ");
166                                 }
167                             }
168                             if len == 1 {
169                                 span_help!(this.tcx().sess, default_span,
170                                     "this function's return type contains a borrowed value, but \
171                                      the signature does not say which {} it is borrowed from",
172                                     m);
173                             } else if len == 0 {
174                                 span_help!(this.tcx().sess, default_span,
175                                     "this function's return type contains a borrowed value, but \
176                                      there is no value for it to be borrowed from");
177                                 span_help!(this.tcx().sess, default_span,
178                                     "consider giving it a 'static lifetime");
179                             } else {
180                                 span_help!(this.tcx().sess, default_span,
181                                     "this function's return type contains a borrowed value, but \
182                                      the signature does not say whether it is borrowed from {}",
183                                     m);
184                             }
185                         }
186                         None => {},
187                     }
188                     ty::ReStatic
189                 }
190
191                 Ok(rs) => rs[0],
192             }
193         }
194     };
195
196     debug!("opt_ast_region_to_region(opt_lifetime={}) yields {}",
197             opt_lifetime.repr(this.tcx()),
198             r.repr(this.tcx()));
199
200     r
201 }
202
203 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
204 /// returns an appropriate set of substitutions for this particular reference to `I`.
205 fn ast_path_substs_for_ty<'tcx,AC,RS>(
206     this: &AC,
207     rscope: &RS,
208     decl_def_id: ast::DefId,
209     decl_generics: &ty::Generics<'tcx>,
210     self_ty: Option<Ty<'tcx>>,
211     path: &ast::Path)
212     -> Substs<'tcx>
213     where AC: AstConv<'tcx>, RS: RegionScope
214 {
215     let tcx = this.tcx();
216
217     // ast_path_substs() is only called to convert paths that are
218     // known to refer to traits, types, or structs. In these cases,
219     // all type parameters defined for the item being referenced will
220     // be in the TypeSpace or SelfSpace.
221     //
222     // Note: in the case of traits, the self parameter is also
223     // defined, but we don't currently create a `type_param_def` for
224     // `Self` because it is implicit.
225     assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
226     assert!(decl_generics.types.all(|d| d.space != FnSpace));
227
228     let (regions, types) = match path.segments.last().unwrap().parameters {
229         ast::AngleBracketedParameters(ref data) => {
230             convert_angle_bracketed_parameters(this, rscope, data)
231         }
232         ast::ParenthesizedParameters(ref data) => {
233             span_err!(tcx.sess, path.span, E0169,
234                       "parenthesized parameters may only be used with a trait");
235             (Vec::new(), convert_parenthesized_parameters(this, data))
236         }
237     };
238
239     create_substs_for_ast_path(this, rscope, path.span, decl_def_id,
240                                decl_generics, self_ty, types, regions)
241 }
242
243 fn create_substs_for_ast_path<'tcx,AC,RS>(
244     this: &AC,
245     rscope: &RS,
246     span: Span,
247     decl_def_id: ast::DefId,
248     decl_generics: &ty::Generics<'tcx>,
249     self_ty: Option<Ty<'tcx>>,
250     types: Vec<Ty<'tcx>>,
251     regions: Vec<ty::Region>)
252     -> Substs<'tcx>
253     where AC: AstConv<'tcx>, RS: RegionScope
254 {
255     let tcx = this.tcx();
256
257     // If the type is parameterized by the this region, then replace this
258     // region with the current anon region binding (in other words,
259     // whatever & would get replaced with).
260     let expected_num_region_params = decl_generics.regions.len(TypeSpace);
261     let supplied_num_region_params = regions.len();
262     let regions = if expected_num_region_params == supplied_num_region_params {
263         regions
264     } else {
265         let anon_regions =
266             rscope.anon_regions(span, expected_num_region_params);
267
268         if supplied_num_region_params != 0 || anon_regions.is_err() {
269             span_err!(tcx.sess, span, E0107,
270                       "wrong number of lifetime parameters: expected {}, found {}",
271                       expected_num_region_params, supplied_num_region_params);
272         }
273
274         match anon_regions {
275             Ok(v) => v.into_iter().collect(),
276             Err(_) => Vec::from_fn(expected_num_region_params,
277                                    |_| ty::ReStatic) // hokey
278         }
279     };
280
281     // Convert the type parameters supplied by the user.
282     let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
283     let supplied_ty_param_count = types.len();
284     let formal_ty_param_count =
285         ty_param_defs.iter()
286         .take_while(|x| !ty::is_associated_type(tcx, x.def_id))
287         .count();
288     let required_ty_param_count =
289         ty_param_defs.iter()
290         .take_while(|x| {
291             x.default.is_none() &&
292                 !ty::is_associated_type(tcx, x.def_id)
293         })
294         .count();
295     if supplied_ty_param_count < required_ty_param_count {
296         let expected = if required_ty_param_count < formal_ty_param_count {
297             "expected at least"
298         } else {
299             "expected"
300         };
301         this.tcx().sess.span_fatal(span,
302                                    format!("wrong number of type arguments: {} {}, found {}",
303                                            expected,
304                                            required_ty_param_count,
305                                            supplied_ty_param_count).as_slice());
306     } else if supplied_ty_param_count > formal_ty_param_count {
307         let expected = if required_ty_param_count < formal_ty_param_count {
308             "expected at most"
309         } else {
310             "expected"
311         };
312         this.tcx().sess.span_fatal(span,
313                                    format!("wrong number of type arguments: {} {}, found {}",
314                                            expected,
315                                            formal_ty_param_count,
316                                            supplied_ty_param_count).as_slice());
317     }
318
319     if supplied_ty_param_count > required_ty_param_count
320         && !this.tcx().sess.features.borrow().default_type_params {
321         span_err!(this.tcx().sess, span, E0108,
322             "default type parameters are experimental and possibly buggy");
323         span_help!(this.tcx().sess, span,
324             "add #![feature(default_type_params)] to the crate attributes to enable");
325     }
326
327     let mut substs = Substs::new_type(types, regions);
328
329     match self_ty {
330         None => {
331             // If no self-type is provided, it's still possible that
332             // one was declared, because this could be an object type.
333         }
334         Some(ty) => {
335             // If a self-type is provided, one should have been
336             // "declared" (in other words, this should be a
337             // trait-ref).
338             assert!(decl_generics.types.get_self().is_some());
339             substs.types.push(SelfSpace, ty);
340         }
341     }
342
343     for param in ty_param_defs[supplied_ty_param_count..].iter() {
344         match param.default {
345             Some(default) => {
346                 // This is a default type parameter.
347                 let default = default.subst_spanned(tcx,
348                                                     &substs,
349                                                     Some(span));
350                 substs.types.push(TypeSpace, default);
351             }
352             None => {
353                 tcx.sess.span_bug(span, "extra parameter without default");
354             }
355         }
356     }
357
358     for param in decl_generics.types.get_slice(AssocSpace).iter() {
359         substs.types.push(
360             AssocSpace,
361             this.associated_type_binding(span,
362                                          self_ty,
363                                          decl_def_id,
364                                          param.def_id));
365     }
366
367     return substs;
368 }
369
370 fn convert_angle_bracketed_parameters<'tcx, AC, RS>(this: &AC,
371                                                     rscope: &RS,
372                                                     data: &ast::AngleBracketedParameterData)
373                                                     -> (Vec<ty::Region>, Vec<Ty<'tcx>>)
374     where AC: AstConv<'tcx>, RS: RegionScope
375 {
376     let regions: Vec<_> =
377         data.lifetimes.iter()
378         .map(|l| ast_region_to_region(this.tcx(), l))
379         .collect();
380
381     let types: Vec<_> =
382         data.types.iter()
383         .map(|t| ast_ty_to_ty(this, rscope, &**t))
384         .collect();
385
386     (regions, types)
387 }
388
389 fn convert_parenthesized_parameters<'tcx,AC>(this: &AC,
390                                              data: &ast::ParenthesizedParameterData)
391                                              -> Vec<Ty<'tcx>>
392     where AC: AstConv<'tcx>
393 {
394     let binding_rscope = BindingRscope::new();
395
396     let inputs = data.inputs.iter()
397                             .map(|a_t| ast_ty_to_ty(this, &binding_rscope, &**a_t))
398                             .collect();
399     let input_ty = ty::mk_tup(this.tcx(), inputs);
400
401     let output = match data.output {
402         Some(ref output_ty) => ast_ty_to_ty(this, &binding_rscope, &**output_ty),
403         None => ty::mk_nil(this.tcx()),
404     };
405
406     vec![input_ty, output]
407 }
408
409 pub fn instantiate_poly_trait_ref<'tcx,AC,RS>(
410     this: &AC,
411     rscope: &RS,
412     ast_trait_ref: &ast::PolyTraitRef,
413     self_ty: Option<Ty<'tcx>>)
414     -> Rc<ty::TraitRef<'tcx>>
415     where AC: AstConv<'tcx>, RS: RegionScope
416 {
417     instantiate_trait_ref(this, rscope, &ast_trait_ref.trait_ref, self_ty)
418 }
419
420 /// Instantiates the path for the given trait reference, assuming that it's bound to a valid trait
421 /// type. Returns the def_id for the defining trait. Fails if the type is a type other than a trait
422 /// type.
423 pub fn instantiate_trait_ref<'tcx,AC,RS>(this: &AC,
424                                          rscope: &RS,
425                                          ast_trait_ref: &ast::TraitRef,
426                                          self_ty: Option<Ty<'tcx>>)
427                                          -> Rc<ty::TraitRef<'tcx>>
428                                          where AC: AstConv<'tcx>,
429                                                RS: RegionScope
430 {
431     match ::lookup_def_tcx(this.tcx(),
432                            ast_trait_ref.path.span,
433                            ast_trait_ref.ref_id) {
434         def::DefTrait(trait_def_id) => {
435             let trait_ref = Rc::new(ast_path_to_trait_ref(this, rscope, trait_def_id,
436                                                           self_ty, &ast_trait_ref.path));
437             this.tcx().trait_refs.borrow_mut().insert(ast_trait_ref.ref_id,
438                                                       trait_ref.clone());
439             trait_ref
440         }
441         _ => {
442             this.tcx().sess.span_fatal(
443                 ast_trait_ref.path.span,
444                 format!("`{}` is not a trait", ast_trait_ref.path.user_string(this.tcx()))[]);
445         }
446     }
447 }
448
449 fn ast_path_to_trait_ref<'tcx,AC,RS>(
450     this: &AC,
451     rscope: &RS,
452     trait_def_id: ast::DefId,
453     self_ty: Option<Ty<'tcx>>,
454     path: &ast::Path)
455     -> ty::TraitRef<'tcx>
456     where AC: AstConv<'tcx>, RS: RegionScope
457 {
458     let trait_def = this.get_trait_def(trait_def_id);
459
460     // the trait reference introduces a binding level here, so
461     // we need to shift the `rscope`. It'd be nice if we could
462     // do away with this rscope stuff and work this knowledge
463     // into resolve_lifetimes, as we do with non-omitted
464     // lifetimes. Oh well, not there yet.
465     let shifted_rscope = ShiftedRscope::new(rscope);
466
467     let (regions, types) = match path.segments.last().unwrap().parameters {
468         ast::AngleBracketedParameters(ref data) => {
469             convert_angle_bracketed_parameters(this, &shifted_rscope, data)
470         }
471         ast::ParenthesizedParameters(ref data) => {
472             (Vec::new(), convert_parenthesized_parameters(this, data))
473         }
474     };
475
476     let substs = create_substs_for_ast_path(this,
477                                             &shifted_rscope,
478                                             path.span,
479                                             trait_def_id,
480                                             &trait_def.generics,
481                                             self_ty,
482                                             types,
483                                             regions);
484
485     ty::TraitRef::new(trait_def_id, substs)
486 }
487
488 pub fn ast_path_to_ty<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
489     this: &AC,
490     rscope: &RS,
491     did: ast::DefId,
492     path: &ast::Path)
493     -> TypeAndSubsts<'tcx>
494 {
495     let tcx = this.tcx();
496     let ty::Polytype {
497         generics,
498         ty: decl_ty
499     } = this.get_item_ty(did);
500
501     let substs = ast_path_substs_for_ty(this,
502                                         rscope,
503                                         did,
504                                         &generics,
505                                         None,
506                                         path);
507     let ty = decl_ty.subst(tcx, &substs);
508     TypeAndSubsts { substs: substs, ty: ty }
509 }
510
511 /// Returns the type that this AST path refers to. If the path has no type
512 /// parameters and the corresponding type has type parameters, fresh type
513 /// and/or region variables are substituted.
514 ///
515 /// This is used when checking the constructor in struct literals.
516 pub fn ast_path_to_ty_relaxed<'tcx,AC,RS>(
517     this: &AC,
518     rscope: &RS,
519     did: ast::DefId,
520     path: &ast::Path)
521     -> TypeAndSubsts<'tcx>
522     where AC : AstConv<'tcx>, RS : RegionScope
523 {
524     let tcx = this.tcx();
525     let ty::Polytype {
526         generics,
527         ty: decl_ty
528     } = this.get_item_ty(did);
529
530     let wants_params =
531         generics.has_type_params(TypeSpace) || generics.has_region_params(TypeSpace);
532
533     let needs_defaults =
534         wants_params &&
535         path.segments.iter().all(|s| s.parameters.is_empty());
536
537     let substs = if needs_defaults {
538         let type_params = Vec::from_fn(generics.types.len(TypeSpace),
539                                        |_| this.ty_infer(path.span));
540         let region_params =
541             rscope.anon_regions(path.span, generics.regions.len(TypeSpace))
542                   .unwrap();
543         Substs::new(VecPerParamSpace::params_from_type(type_params),
544                     VecPerParamSpace::params_from_type(region_params))
545     } else {
546         ast_path_substs_for_ty(this, rscope, did, &generics, None, path)
547     };
548
549     let ty = decl_ty.subst(tcx, &substs);
550     TypeAndSubsts {
551         substs: substs,
552         ty: ty,
553     }
554 }
555
556 /// Converts the given AST type to a built-in type. A "built-in type" is, at
557 /// present, either a core numeric type, a string, or `Box`.
558 pub fn ast_ty_to_builtin_ty<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
559         this: &AC,
560         rscope: &RS,
561         ast_ty: &ast::Ty)
562         -> Option<Ty<'tcx>> {
563     match ast_ty_to_prim_ty(this.tcx(), ast_ty) {
564         Some(typ) => return Some(typ),
565         None => {}
566     }
567
568     match ast_ty.node {
569         ast::TyPath(ref path, id) => {
570             let a_def = match this.tcx().def_map.borrow().get(&id) {
571                 None => {
572                     this.tcx()
573                         .sess
574                         .span_bug(ast_ty.span,
575                                   format!("unbound path {}",
576                                           path.repr(this.tcx())).as_slice())
577                 }
578                 Some(&d) => d
579             };
580
581             // FIXME(#12938): This is a hack until we have full support for
582             // DST.
583             match a_def {
584                 def::DefTy(did, _) |
585                 def::DefStruct(did) if Some(did) == this.tcx().lang_items.owned_box() => {
586                     let ty = ast_path_to_ty(this, rscope, did, path).ty;
587                     match ty.sty {
588                         ty::ty_struct(struct_def_id, ref substs) => {
589                             assert_eq!(struct_def_id, did);
590                             assert_eq!(substs.types.len(TypeSpace), 1);
591                             let referent_ty = *substs.types.get(TypeSpace, 0);
592                             Some(ty::mk_uniq(this.tcx(), referent_ty))
593                         }
594                         _ => {
595                             this.tcx().sess.span_bug(
596                                 path.span,
597                                 format!("converting `Box` to `{}`",
598                                         ty.repr(this.tcx()))[]);
599                         }
600                     }
601                 }
602                 _ => None
603             }
604         }
605         _ => None
606     }
607 }
608
609 fn ast_ty_to_trait_ref<'tcx,AC,RS>(this: &AC,
610                                    rscope: &RS,
611                                    ty: &ast::Ty,
612                                    bounds: &[ast::TyParamBound])
613                                    -> Result<ty::TraitRef<'tcx>, ErrorReported>
614     where AC : AstConv<'tcx>, RS : RegionScope
615 {
616     /*!
617      * In a type like `Foo + Send`, we want to wait to collect the
618      * full set of bounds before we make the object type, because we
619      * need them to infer a region bound.  (For example, if we tried
620      * made a type from just `Foo`, then it wouldn't be enough to
621      * infer a 'static bound, and hence the user would get an error.)
622      * So this function is used when we're dealing with a sum type to
623      * convert the LHS. It only accepts a type that refers to a trait
624      * name, and reports an error otherwise.
625      */
626
627     match ty.node {
628         ast::TyPath(ref path, id) => {
629             match this.tcx().def_map.borrow().get(&id) {
630                 Some(&def::DefTrait(trait_def_id)) => {
631                     return Ok(ast_path_to_trait_ref(this,
632                                                     rscope,
633                                                     trait_def_id,
634                                                     None,
635                                                     path));
636                 }
637                 _ => {
638                     span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
639                     Err(ErrorReported)
640                 }
641             }
642         }
643         _ => {
644             span_err!(this.tcx().sess, ty.span, E0171,
645                       "expected a path on the left-hand side of `+`, not `{}`",
646                       pprust::ty_to_string(ty));
647             match ty.node {
648                 ast::TyRptr(None, ref mut_ty) => {
649                     span_note!(this.tcx().sess, ty.span,
650                                "perhaps you meant `&{}({} +{})`? (per RFC 248)",
651                                ppaux::mutability_to_string(mut_ty.mutbl),
652                                pprust::ty_to_string(&*mut_ty.ty),
653                                pprust::bounds_to_string(bounds));
654                 }
655
656                 ast::TyRptr(Some(ref lt), ref mut_ty) => {
657                     span_note!(this.tcx().sess, ty.span,
658                                "perhaps you meant `&{} {}({} +{})`? (per RFC 248)",
659                                pprust::lifetime_to_string(lt),
660                                ppaux::mutability_to_string(mut_ty.mutbl),
661                                pprust::ty_to_string(&*mut_ty.ty),
662                                pprust::bounds_to_string(bounds));
663                 }
664
665                 _ => {
666                     span_note!(this.tcx().sess, ty.span,
667                                "perhaps you forgot parentheses? (per RFC 248)");
668                 }
669             }
670             Err(ErrorReported)
671         }
672     }
673
674 }
675
676 fn trait_ref_to_object_type<'tcx,AC,RS>(this: &AC,
677                                         rscope: &RS,
678                                         span: Span,
679                                         trait_ref: ty::TraitRef<'tcx>,
680                                         bounds: &[ast::TyParamBound])
681                                         -> Ty<'tcx>
682     where AC : AstConv<'tcx>, RS : RegionScope
683 {
684     let existential_bounds = conv_existential_bounds(this,
685                                                      rscope,
686                                                      span,
687                                                      &[Rc::new(trait_ref.clone())],
688                                                      bounds);
689
690     let result = ty::mk_trait(this.tcx(), trait_ref, existential_bounds);
691     debug!("trait_ref_to_object_type: result={}",
692            result.repr(this.tcx()));
693
694     result
695 }
696
697 fn qpath_to_ty<'tcx,AC,RS>(this: &AC,
698                            rscope: &RS,
699                            ast_ty: &ast::Ty, // the TyQPath
700                            qpath: &ast::QPath)
701                            -> Ty<'tcx>
702     where AC: AstConv<'tcx>, RS: RegionScope
703 {
704     debug!("qpath_to_ty(ast_ty={})",
705            ast_ty.repr(this.tcx()));
706
707     let self_type = ast_ty_to_ty(this, rscope, &*qpath.self_type);
708
709     debug!("qpath_to_ty: self_type={}", self_type.repr(this.tcx()));
710
711     let trait_ref = instantiate_trait_ref(this,
712                                           rscope,
713                                           &*qpath.trait_ref,
714                                           Some(self_type));
715
716     debug!("qpath_to_ty: trait_ref={}", trait_ref.repr(this.tcx()));
717
718     let trait_def = this.get_trait_def(trait_ref.def_id);
719
720     for ty_param_def in trait_def.generics.types.get_slice(AssocSpace).iter() {
721         if ty_param_def.name == qpath.item_name.name {
722             debug!("qpath_to_ty: corresponding ty_param_def={}", ty_param_def);
723             return trait_ref.substs.type_for_def(ty_param_def);
724         }
725     }
726
727     this.tcx().sess.span_bug(ast_ty.span,
728                              "this associated type didn't get added \
729                               as a parameter for some reason")
730 }
731
732 // Parses the programmer's textual representation of a type into our
733 // internal notion of a type.
734 pub fn ast_ty_to_ty<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
735         this: &AC, rscope: &RS, ast_ty: &ast::Ty) -> Ty<'tcx>
736 {
737     debug!("ast_ty_to_ty(ast_ty={})",
738            ast_ty.repr(this.tcx()));
739
740     let tcx = this.tcx();
741
742     let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
743     match ast_ty_to_ty_cache.get(&ast_ty.id) {
744         Some(&ty::atttce_resolved(ty)) => return ty,
745         Some(&ty::atttce_unresolved) => {
746             tcx.sess.span_fatal(ast_ty.span,
747                                 "illegal recursive type; insert an enum \
748                                  or struct in the cycle, if this is \
749                                  desired");
750         }
751         None => { /* go on */ }
752     }
753     ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
754     drop(ast_ty_to_ty_cache);
755
756     let typ = ast_ty_to_builtin_ty(this, rscope, ast_ty).unwrap_or_else(|| {
757         match ast_ty.node {
758             ast::TyVec(ref ty) => {
759                 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty), None)
760             }
761             ast::TyObjectSum(ref ty, ref bounds) => {
762                 match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.as_slice()) {
763                     Ok(trait_ref) => {
764                         trait_ref_to_object_type(this, rscope, ast_ty.span,
765                                                  trait_ref, bounds.as_slice())
766                     }
767                     Err(ErrorReported) => {
768                         ty::mk_err()
769                     }
770                 }
771             }
772             ast::TyPtr(ref mt) => {
773                 ty::mk_ptr(tcx, ty::mt {
774                     ty: ast_ty_to_ty(this, rscope, &*mt.ty),
775                     mutbl: mt.mutbl
776                 })
777             }
778             ast::TyRptr(ref region, ref mt) => {
779                 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
780                 debug!("ty_rptr r={}", r.repr(this.tcx()));
781                 let t = ast_ty_to_ty(this, rscope, &*mt.ty);
782                 ty::mk_rptr(tcx, r, ty::mt {ty: t, mutbl: mt.mutbl})
783             }
784             ast::TyTup(ref fields) => {
785                 let flds = fields.iter()
786                                  .map(|t| ast_ty_to_ty(this, rscope, &**t))
787                                  .collect();
788                 ty::mk_tup(tcx, flds)
789             }
790             ast::TyParen(ref typ) => ast_ty_to_ty(this, rscope, &**typ),
791             ast::TyBareFn(ref bf) => {
792                 if bf.decl.variadic && bf.abi != abi::C {
793                     tcx.sess.span_err(ast_ty.span,
794                                       "variadic function must have C calling convention");
795                 }
796                 ty::mk_bare_fn(tcx, ty_of_bare_fn(this, bf.fn_style, bf.abi, &*bf.decl))
797             }
798             ast::TyClosure(ref f) => {
799                 // Use corresponding trait store to figure out default bounds
800                 // if none were specified.
801                 let bounds = conv_existential_bounds(this,
802                                                      rscope,
803                                                      ast_ty.span,
804                                                      [].as_slice(),
805                                                      f.bounds.as_slice());
806                 let fn_decl = ty_of_closure(this,
807                                             f.fn_style,
808                                             f.onceness,
809                                             bounds,
810                                             ty::RegionTraitStore(
811                                                 bounds.region_bound,
812                                                 ast::MutMutable),
813                                             &*f.decl,
814                                             abi::Rust,
815                                             None);
816                 ty::mk_closure(tcx, fn_decl)
817             }
818             ast::TyProc(ref f) => {
819                 // Use corresponding trait store to figure out default bounds
820                 // if none were specified.
821                 let bounds = conv_existential_bounds(this, rscope,
822                                                      ast_ty.span,
823                                                      [].as_slice(),
824                                                      f.bounds.as_slice());
825
826                 let fn_decl = ty_of_closure(this,
827                                             f.fn_style,
828                                             f.onceness,
829                                             bounds,
830                                             ty::UniqTraitStore,
831                                             &*f.decl,
832                                             abi::Rust,
833                                             None);
834
835                 ty::mk_closure(tcx, fn_decl)
836             }
837             ast::TyPolyTraitRef(ref bounds) => {
838                 conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds.as_slice())
839             }
840             ast::TyPath(ref path, id) => {
841                 let a_def = match tcx.def_map.borrow().get(&id) {
842                     None => {
843                         tcx.sess
844                            .span_bug(ast_ty.span,
845                                      format!("unbound path {}",
846                                              path.repr(tcx)).as_slice())
847                     }
848                     Some(&d) => d
849                 };
850                 match a_def {
851                     def::DefTrait(trait_def_id) => {
852                         // N.B. this case overlaps somewhat with
853                         // TyObjectSum, see that fn for details
854                         let result = ast_path_to_trait_ref(this,
855                                                            rscope,
856                                                            trait_def_id,
857                                                            None,
858                                                            path);
859                         trait_ref_to_object_type(this, rscope, path.span, result, &[])
860                     }
861                     def::DefTy(did, _) | def::DefStruct(did) => {
862                         ast_path_to_ty(this, rscope, did, path).ty
863                     }
864                     def::DefTyParam(space, id, n) => {
865                         check_path_args(tcx, path, NO_TPS | NO_REGIONS);
866                         ty::mk_param(tcx, space, n, id)
867                     }
868                     def::DefSelfTy(id) => {
869                         // n.b.: resolve guarantees that the this type only appears in a
870                         // trait, which we rely upon in various places when creating
871                         // substs
872                         check_path_args(tcx, path, NO_TPS | NO_REGIONS);
873                         let did = ast_util::local_def(id);
874                         ty::mk_self_type(tcx, did)
875                     }
876                     def::DefMod(id) => {
877                         tcx.sess.span_fatal(ast_ty.span,
878                             format!("found module name used as a type: {}",
879                                     tcx.map.node_to_string(id.node)).as_slice());
880                     }
881                     def::DefPrimTy(_) => {
882                         panic!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call");
883                     }
884                     def::DefAssociatedTy(trait_type_id) => {
885                         let path_str = tcx.map.path_to_string(
886                             tcx.map.get_parent(trait_type_id.node));
887                         tcx.sess.span_err(ast_ty.span,
888                                           format!("ambiguous associated \
889                                                    type; specify the type \
890                                                    using the syntax `<Type \
891                                                    as {}>::{}`",
892                                                   path_str,
893                                                   token::get_ident(
894                                                       path.segments
895                                                           .last()
896                                                           .unwrap()
897                                                           .identifier)
898                                                   .get()).as_slice());
899                         ty::mk_err()
900                     }
901                     _ => {
902                         tcx.sess.span_fatal(ast_ty.span,
903                                             format!("found value name used \
904                                                      as a type: {}",
905                                                     a_def).as_slice());
906                     }
907                 }
908             }
909             ast::TyQPath(ref qpath) => {
910                 qpath_to_ty(this, rscope, ast_ty, &**qpath)
911             }
912             ast::TyFixedLengthVec(ref ty, ref e) => {
913                 match const_eval::eval_const_expr_partial(tcx, &**e) {
914                     Ok(ref r) => {
915                         match *r {
916                             const_eval::const_int(i) =>
917                                 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
918                                            Some(i as uint)),
919                             const_eval::const_uint(i) =>
920                                 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
921                                            Some(i as uint)),
922                             _ => {
923                                 tcx.sess.span_fatal(
924                                     ast_ty.span, "expected constant expr for array length");
925                             }
926                         }
927                     }
928                     Err(ref r) => {
929                         tcx.sess.span_fatal(
930                             ast_ty.span,
931                             format!("expected constant expr for array \
932                                      length: {}",
933                                     *r).as_slice());
934                     }
935                 }
936             }
937             ast::TyTypeof(ref _e) => {
938                 tcx.sess.span_bug(ast_ty.span, "typeof is reserved but unimplemented");
939             }
940             ast::TyInfer => {
941                 // TyInfer also appears as the type of arguments or return
942                 // values in a ExprClosure or ExprProc, or as
943                 // the type of local variables. Both of these cases are
944                 // handled specially and will not descend into this routine.
945                 this.ty_infer(ast_ty.span)
946             }
947         }
948     });
949
950     tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, ty::atttce_resolved(typ));
951     return typ;
952 }
953
954 pub fn ty_of_arg<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(this: &AC, rscope: &RS,
955                                                            a: &ast::Arg,
956                                                            expected_ty: Option<Ty<'tcx>>)
957                                                            -> Ty<'tcx> {
958     match a.ty.node {
959         ast::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
960         ast::TyInfer => this.ty_infer(a.ty.span),
961         _ => ast_ty_to_ty(this, rscope, &*a.ty),
962     }
963 }
964
965 struct SelfInfo<'a, 'tcx> {
966     untransformed_self_ty: Ty<'tcx>,
967     explicit_self: &'a ast::ExplicitSelf,
968 }
969
970 pub fn ty_of_method<'tcx, AC: AstConv<'tcx>>(
971                     this: &AC,
972                     fn_style: ast::FnStyle,
973                     untransformed_self_ty: Ty<'tcx>,
974                     explicit_self: &ast::ExplicitSelf,
975                     decl: &ast::FnDecl,
976                     abi: abi::Abi)
977                     -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
978     let self_info = Some(SelfInfo {
979         untransformed_self_ty: untransformed_self_ty,
980         explicit_self: explicit_self,
981     });
982     let (bare_fn_ty, optional_explicit_self_category) =
983         ty_of_method_or_bare_fn(this,
984                                 fn_style,
985                                 abi,
986                                 self_info,
987                                 decl);
988     (bare_fn_ty, optional_explicit_self_category.unwrap())
989 }
990
991 pub fn ty_of_bare_fn<'tcx, AC: AstConv<'tcx>>(this: &AC, fn_style: ast::FnStyle, abi: abi::Abi,
992                                               decl: &ast::FnDecl) -> ty::BareFnTy<'tcx> {
993     let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, fn_style, abi, None, decl);
994     bare_fn_ty
995 }
996
997 fn ty_of_method_or_bare_fn<'a, 'tcx, AC: AstConv<'tcx>>(
998                            this: &AC,
999                            fn_style: ast::FnStyle,
1000                            abi: abi::Abi,
1001                            opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1002                            decl: &ast::FnDecl)
1003                            -> (ty::BareFnTy<'tcx>,
1004                                Option<ty::ExplicitSelfCategory>) {
1005     debug!("ty_of_method_or_bare_fn");
1006
1007     // New region names that appear inside of the arguments of the function
1008     // declaration are bound to that function type.
1009     let rb = rscope::BindingRscope::new();
1010
1011     // `implied_output_region` is the region that will be assumed for any
1012     // region parameters in the return type. In accordance with the rules for
1013     // lifetime elision, we can determine it in two ways. First (determined
1014     // here), if self is by-reference, then the implied output region is the
1015     // region of the self parameter.
1016     let mut explicit_self_category_result = None;
1017     let (self_ty, mut implied_output_region) = match opt_self_info {
1018         None => (None, None),
1019         Some(self_info) => {
1020             // Figure out and record the explicit self category.
1021             let explicit_self_category =
1022                 determine_explicit_self_category(this, &rb, &self_info);
1023             explicit_self_category_result = Some(explicit_self_category);
1024             match explicit_self_category {
1025                 ty::StaticExplicitSelfCategory => {
1026                     (None, None)
1027                 }
1028                 ty::ByValueExplicitSelfCategory => {
1029                     (Some(self_info.untransformed_self_ty), None)
1030                 }
1031                 ty::ByReferenceExplicitSelfCategory(region, mutability) => {
1032                     (Some(ty::mk_rptr(this.tcx(),
1033                                       region,
1034                                       ty::mt {
1035                                         ty: self_info.untransformed_self_ty,
1036                                         mutbl: mutability
1037                                       })),
1038                      Some(region))
1039                 }
1040                 ty::ByBoxExplicitSelfCategory => {
1041                     (Some(ty::mk_uniq(this.tcx(),
1042                                       self_info.untransformed_self_ty)),
1043                      None)
1044                 }
1045             }
1046         }
1047     };
1048
1049     // HACK(eddyb) replace the fake self type in the AST with the actual type.
1050     let input_params = if self_ty.is_some() {
1051         decl.inputs.slice_from(1)
1052     } else {
1053         decl.inputs.as_slice()
1054     };
1055     let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None));
1056     let input_pats: Vec<String> = input_params.iter()
1057                                               .map(|a| pprust::pat_to_string(&*a.pat))
1058                                               .collect();
1059     let self_and_input_tys: Vec<Ty> =
1060         self_ty.into_iter().chain(input_tys).collect();
1061
1062     let mut lifetimes_for_params: Vec<(String, Vec<ty::Region>)> = Vec::new();
1063
1064     // Second, if there was exactly one lifetime (either a substitution or a
1065     // reference) in the arguments, then any anonymous regions in the output
1066     // have that lifetime.
1067     if implied_output_region.is_none() {
1068         let mut self_and_input_tys_iter = self_and_input_tys.iter();
1069         if self_ty.is_some() {
1070             // Skip the first argument if `self` is present.
1071             drop(self_and_input_tys_iter.next())
1072         }
1073
1074         for (input_type, input_pat) in self_and_input_tys_iter.zip(input_pats.into_iter()) {
1075             let mut accumulator = Vec::new();
1076             ty::accumulate_lifetimes_in_type(&mut accumulator, *input_type);
1077             lifetimes_for_params.push((input_pat, accumulator));
1078         }
1079
1080         if lifetimes_for_params.iter().map(|&(_, ref x)| x.len()).sum() == 1 {
1081             implied_output_region =
1082                 Some(lifetimes_for_params.iter()
1083                                          .filter_map(|&(_, ref x)|
1084                                             if x.len() == 1 { Some(x[0]) } else { None })
1085                                          .next().unwrap());
1086         }
1087     }
1088
1089     let param_lifetimes: Vec<(String, uint)> = lifetimes_for_params.into_iter()
1090                                                                    .map(|(n, v)| (n, v.len()))
1091                                                                    .filter(|&(_, l)| l != 0)
1092                                                                    .collect();
1093
1094     let output_ty = match decl.output {
1095         ast::Return(ref output) if output.node == ast::TyInfer =>
1096             ty::FnConverging(this.ty_infer(output.span)),
1097         ast::Return(ref output) =>
1098             ty::FnConverging(match implied_output_region {
1099                 Some(implied_output_region) => {
1100                     let rb = SpecificRscope::new(implied_output_region);
1101                     ast_ty_to_ty(this, &rb, &**output)
1102                 }
1103                 None => {
1104                     // All regions must be explicitly specified in the output
1105                     // if the lifetime elision rules do not apply. This saves
1106                     // the user from potentially-confusing errors.
1107                     let rb = UnelidableRscope::new(param_lifetimes);
1108                     ast_ty_to_ty(this, &rb, &**output)
1109                 }
1110             }),
1111         ast::NoReturn(_) => ty::FnDiverging
1112     };
1113
1114     (ty::BareFnTy {
1115         fn_style: fn_style,
1116         abi: abi,
1117         sig: ty::FnSig {
1118             inputs: self_and_input_tys,
1119             output: output_ty,
1120             variadic: decl.variadic
1121         }
1122     }, explicit_self_category_result)
1123 }
1124
1125 fn determine_explicit_self_category<'a, 'tcx, AC: AstConv<'tcx>,
1126                                     RS:RegionScope>(
1127                                     this: &AC,
1128                                     rscope: &RS,
1129                                     self_info: &SelfInfo<'a, 'tcx>)
1130                                     -> ty::ExplicitSelfCategory
1131 {
1132     return match self_info.explicit_self.node {
1133         ast::SelfStatic => ty::StaticExplicitSelfCategory,
1134         ast::SelfValue(_) => ty::ByValueExplicitSelfCategory,
1135         ast::SelfRegion(ref lifetime, mutability, _) => {
1136             let region =
1137                 opt_ast_region_to_region(this,
1138                                          rscope,
1139                                          self_info.explicit_self.span,
1140                                          lifetime);
1141             ty::ByReferenceExplicitSelfCategory(region, mutability)
1142         }
1143         ast::SelfExplicit(ref ast_type, _) => {
1144             let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1145
1146             // We wish to (for now) categorize an explicit self
1147             // declaration like `self: SomeType` into either `self`,
1148             // `&self`, `&mut self`, or `Box<self>`. We do this here
1149             // by some simple pattern matching. A more precise check
1150             // is done later in `check_method_self_type()`.
1151             //
1152             // Examples:
1153             //
1154             // ```
1155             // impl Foo for &T {
1156             //     // Legal declarations:
1157             //     fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1158             //     fn method2(self: &T); // ByValueExplicitSelfCategory
1159             //     fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1160             //
1161             //     // Invalid cases will be caught later by `check_method_self_type`:
1162             //     fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1163             // }
1164             // ```
1165             //
1166             // To do the check we just count the number of "modifiers"
1167             // on each type and compare them. If they are the same or
1168             // the impl has more, we call it "by value". Otherwise, we
1169             // look at the outermost modifier on the method decl and
1170             // call it by-ref, by-box as appropriate. For method1, for
1171             // example, the impl type has one modifier, but the method
1172             // type has two, so we end up with
1173             // ByReferenceExplicitSelfCategory.
1174
1175             let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1176             let method_modifiers = count_modifiers(explicit_type);
1177
1178             debug!("determine_explicit_self_category(self_info.untransformed_self_ty={} \
1179                    explicit_type={} \
1180                    modifiers=({},{})",
1181                    self_info.untransformed_self_ty.repr(this.tcx()),
1182                    explicit_type.repr(this.tcx()),
1183                    impl_modifiers,
1184                    method_modifiers);
1185
1186             if impl_modifiers >= method_modifiers {
1187                 ty::ByValueExplicitSelfCategory
1188             } else {
1189                 match explicit_type.sty {
1190                     ty::ty_rptr(r, mt) => ty::ByReferenceExplicitSelfCategory(r, mt.mutbl),
1191                     ty::ty_uniq(_) => ty::ByBoxExplicitSelfCategory,
1192                     _ => ty::ByValueExplicitSelfCategory,
1193                 }
1194             }
1195         }
1196     };
1197
1198     fn count_modifiers(ty: Ty) -> uint {
1199         match ty.sty {
1200             ty::ty_rptr(_, mt) => count_modifiers(mt.ty) + 1,
1201             ty::ty_uniq(t) => count_modifiers(t) + 1,
1202             _ => 0,
1203         }
1204     }
1205 }
1206
1207 pub fn ty_of_closure<'tcx, AC: AstConv<'tcx>>(
1208     this: &AC,
1209     fn_style: ast::FnStyle,
1210     onceness: ast::Onceness,
1211     bounds: ty::ExistentialBounds,
1212     store: ty::TraitStore,
1213     decl: &ast::FnDecl,
1214     abi: abi::Abi,
1215     expected_sig: Option<ty::FnSig<'tcx>>)
1216     -> ty::ClosureTy<'tcx>
1217 {
1218     debug!("ty_of_closure(expected_sig={})",
1219            expected_sig.repr(this.tcx()));
1220
1221     // new region names that appear inside of the fn decl are bound to
1222     // that function type
1223     let rb = rscope::BindingRscope::new();
1224
1225     let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1226         let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1227             // no guarantee that the correct number of expected args
1228             // were supplied
1229             if i < e.inputs.len() {
1230                 Some(e.inputs[i])
1231             } else {
1232                 None
1233             }
1234         });
1235         ty_of_arg(this, &rb, a, expected_arg_ty)
1236     }).collect();
1237
1238     let expected_ret_ty = expected_sig.map(|e| e.output);
1239
1240     let output_ty = match decl.output {
1241         ast::Return(ref output) if output.node == ast::TyInfer && expected_ret_ty.is_some() =>
1242             expected_ret_ty.unwrap(),
1243         ast::Return(ref output) if output.node == ast::TyInfer =>
1244             ty::FnConverging(this.ty_infer(output.span)),
1245         ast::Return(ref output) =>
1246             ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1247         ast::NoReturn(_) => ty::FnDiverging
1248     };
1249
1250     debug!("ty_of_closure: input_tys={}", input_tys.repr(this.tcx()));
1251     debug!("ty_of_closure: output_ty={}", output_ty.repr(this.tcx()));
1252
1253     ty::ClosureTy {
1254         fn_style: fn_style,
1255         onceness: onceness,
1256         store: store,
1257         bounds: bounds,
1258         abi: abi,
1259         sig: ty::FnSig {inputs: input_tys,
1260                         output: output_ty,
1261                         variadic: decl.variadic}
1262     }
1263 }
1264
1265 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1266 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1267 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1268 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1269 pub fn conv_existential_bounds<'tcx, AC: AstConv<'tcx>, RS:RegionScope>(
1270     this: &AC,
1271     rscope: &RS,
1272     span: Span,
1273     main_trait_refs: &[Rc<ty::TraitRef<'tcx>>],
1274     ast_bounds: &[ast::TyParamBound])
1275     -> ty::ExistentialBounds
1276 {
1277     let ast_bound_refs: Vec<&ast::TyParamBound> =
1278         ast_bounds.iter().collect();
1279
1280     let partitioned_bounds =
1281         partition_bounds(this.tcx(), span, ast_bound_refs.as_slice());
1282
1283     conv_existential_bounds_from_partitioned_bounds(
1284         this, rscope, span, main_trait_refs, partitioned_bounds)
1285 }
1286
1287 fn conv_ty_poly_trait_ref<'tcx, AC, RS>(
1288     this: &AC,
1289     rscope: &RS,
1290     span: Span,
1291     ast_bounds: &[ast::TyParamBound])
1292     -> Ty<'tcx>
1293     where AC: AstConv<'tcx>, RS:RegionScope
1294 {
1295     let ast_bounds: Vec<&ast::TyParamBound> = ast_bounds.iter().collect();
1296     let mut partitioned_bounds = partition_bounds(this.tcx(), span, ast_bounds[]);
1297
1298     let main_trait_bound = match partitioned_bounds.trait_bounds.remove(0) {
1299         Some(trait_bound) => {
1300             Some(instantiate_poly_trait_ref(this, rscope, trait_bound, None))
1301         }
1302         None => {
1303             this.tcx().sess.span_err(
1304                 span,
1305                 "at least one non-builtin trait is required for an object type");
1306             None
1307         }
1308     };
1309
1310     let bounds = conv_existential_bounds_from_partitioned_bounds(this,
1311                                                                  rscope,
1312                                                                  span,
1313                                                                  main_trait_bound.as_slice(),
1314                                                                  partitioned_bounds);
1315
1316     match main_trait_bound {
1317         None => ty::mk_err(),
1318         Some(principal) => ty::mk_trait(this.tcx(), (*principal).clone(), bounds)
1319     }
1320 }
1321
1322 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx, AC, RS>(
1323     this: &AC,
1324     rscope: &RS,
1325     span: Span,
1326     main_trait_refs: &[Rc<ty::TraitRef<'tcx>>],
1327     partitioned_bounds: PartitionedBounds)
1328     -> ty::ExistentialBounds
1329     where AC: AstConv<'tcx>, RS:RegionScope
1330 {
1331     let PartitionedBounds { builtin_bounds,
1332                             trait_bounds,
1333                             region_bounds } =
1334         partitioned_bounds;
1335
1336     if !trait_bounds.is_empty() {
1337         let b = &trait_bounds[0];
1338         this.tcx().sess.span_err(
1339             b.trait_ref.path.span,
1340             format!("only the builtin traits can be used \
1341                      as closure or object bounds").as_slice());
1342     }
1343
1344     // The "main trait refs", rather annoyingly, have no type
1345     // specified for the `Self` parameter of the trait. The reason for
1346     // this is that they are, after all, *existential* types, and
1347     // hence that type is unknown. However, leaving this type missing
1348     // causes the substitution code to go all awry when walking the
1349     // bounds, so here we clone those trait refs and insert ty::err as
1350     // the self type. Perhaps we should do this more generally, it'd
1351     // be convenient (or perhaps something else, i.e., ty::erased).
1352     let main_trait_refs: Vec<Rc<ty::TraitRef>> =
1353         main_trait_refs.iter()
1354         .map(|t|
1355              Rc::new(ty::TraitRef {
1356                  def_id: t.def_id,
1357                  substs: t.substs.with_self_ty(ty::mk_err()) }))
1358         .collect();
1359
1360     let region_bound = compute_region_bound(this,
1361                                             rscope,
1362                                             span,
1363                                             builtin_bounds,
1364                                             region_bounds.as_slice(),
1365                                             main_trait_refs.as_slice());
1366
1367     ty::ExistentialBounds {
1368         region_bound: region_bound,
1369         builtin_bounds: builtin_bounds,
1370     }
1371 }
1372
1373 /// Given the bounds on a type parameter / existential type, determines what single region bound
1374 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
1375 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
1376 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
1377 pub fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>,
1378                                       span: Span,
1379                                       builtin_bounds: ty::BuiltinBounds,
1380                                       region_bounds: &[&ast::Lifetime],
1381                                       trait_bounds: &[Rc<ty::TraitRef<'tcx>>])
1382                                       -> Option<ty::Region>
1383 {
1384     if region_bounds.len() > 1 {
1385         tcx.sess.span_err(
1386             region_bounds[1].span,
1387             format!("only a single explicit lifetime bound is permitted").as_slice());
1388     }
1389
1390     if region_bounds.len() != 0 {
1391         // Explicitly specified region bound. Use that.
1392         let r = region_bounds[0];
1393         return Some(ast_region_to_region(tcx, r));
1394     }
1395
1396     // No explicit region bound specified. Therefore, examine trait
1397     // bounds and see if we can derive region bounds from those.
1398     let derived_region_bounds =
1399         ty::required_region_bounds(
1400             tcx,
1401             &[],
1402             builtin_bounds,
1403             trait_bounds);
1404
1405     // If there are no derived region bounds, then report back that we
1406     // can find no region bound.
1407     if derived_region_bounds.len() == 0 {
1408         return None;
1409     }
1410
1411     // If any of the derived region bounds are 'static, that is always
1412     // the best choice.
1413     if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
1414         return Some(ty::ReStatic);
1415     }
1416
1417     // Determine whether there is exactly one unique region in the set
1418     // of derived region bounds. If so, use that. Otherwise, report an
1419     // error.
1420     let r = derived_region_bounds[0];
1421     if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) {
1422         tcx.sess.span_err(
1423             span,
1424             format!("ambiguous lifetime bound, \
1425                      explicit lifetime bound required").as_slice());
1426     }
1427     return Some(r);
1428 }
1429
1430 /// A version of `compute_opt_region_bound` for use where some region bound is required
1431 /// (existential types, basically). Reports an error if no region bound can be derived and we are
1432 /// in an `rscope` that does not provide a default.
1433 fn compute_region_bound<'tcx, AC: AstConv<'tcx>, RS:RegionScope>(
1434     this: &AC,
1435     rscope: &RS,
1436     span: Span,
1437     builtin_bounds: ty::BuiltinBounds,
1438     region_bounds: &[&ast::Lifetime],
1439     trait_bounds: &[Rc<ty::TraitRef<'tcx>>])
1440     -> ty::Region
1441 {
1442     match compute_opt_region_bound(this.tcx(), span, builtin_bounds,
1443                                    region_bounds, trait_bounds) {
1444         Some(r) => r,
1445         None => {
1446             match rscope.default_region_bound(span) {
1447                 Some(r) => { r }
1448                 None => {
1449                     this.tcx().sess.span_err(
1450                         span,
1451                         format!("explicit lifetime bound required").as_slice());
1452                     ty::ReStatic
1453                 }
1454             }
1455         }
1456     }
1457 }
1458
1459 pub struct PartitionedBounds<'a> {
1460     pub builtin_bounds: ty::BuiltinBounds,
1461     pub trait_bounds: Vec<&'a ast::PolyTraitRef>,
1462     pub region_bounds: Vec<&'a ast::Lifetime>,
1463 }
1464
1465 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
1466 /// general trait bounds, and region bounds.
1467 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
1468                             _span: Span,
1469                             ast_bounds: &'a [&ast::TyParamBound])
1470                             -> PartitionedBounds<'a>
1471 {
1472     let mut builtin_bounds = ty::empty_builtin_bounds();
1473     let mut region_bounds = Vec::new();
1474     let mut trait_bounds = Vec::new();
1475     let mut trait_def_ids = DefIdMap::new();
1476     for &ast_bound in ast_bounds.iter() {
1477         match *ast_bound {
1478             ast::TraitTyParamBound(ref b) => {
1479                 match ::lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
1480                     def::DefTrait(trait_did) => {
1481                         match trait_def_ids.get(&trait_did) {
1482                             // Already seen this trait. We forbid
1483                             // duplicates in the list (for some
1484                             // reason).
1485                             Some(span) => {
1486                                 span_err!(
1487                                     tcx.sess, b.trait_ref.path.span, E0127,
1488                                     "trait `{}` already appears in the \
1489                                      list of bounds",
1490                                     b.trait_ref.path.user_string(tcx));
1491                                 tcx.sess.span_note(
1492                                     *span,
1493                                     "previous appearance is here");
1494
1495                                 continue;
1496                             }
1497
1498                             None => { }
1499                         }
1500
1501                         trait_def_ids.insert(trait_did, b.trait_ref.path.span);
1502
1503                         if ty::try_add_builtin_trait(tcx,
1504                                                      trait_did,
1505                                                      &mut builtin_bounds) {
1506                             continue; // success
1507                         }
1508                     }
1509                     _ => {
1510                         // Not a trait? that's an error, but it'll get
1511                         // reported later.
1512                     }
1513                 }
1514                 trait_bounds.push(b);
1515             }
1516             ast::RegionTyParamBound(ref l) => {
1517                 region_bounds.push(l);
1518             }
1519         }
1520     }
1521
1522     PartitionedBounds {
1523         builtin_bounds: builtin_bounds,
1524         trait_bounds: trait_bounds,
1525         region_bounds: region_bounds,
1526     }
1527 }