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