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