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