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