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