]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
don't use type_parameter_def during astconv
[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::{prim_ty_to_ty, check_path_args, NO_TPS, NO_REGIONS};
52 use middle::const_eval::{self, ConstVal};
53 use middle::def;
54 use middle::implicator::object_region_bounds;
55 use middle::resolve_lifetime as rl;
56 use middle::privacy::{AllPublic, LastMod};
57 use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs};
58 use middle::traits;
59 use middle::ty::{self, RegionEscape, Ty, ToPredicate, HasTypeFlags};
60 use middle::ty_fold;
61 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope, ExplicitRscope,
62              ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
63              ElisionFailureInfo, ElidedLifetime};
64 use util::common::{ErrorReported, FN_OUTPUT_NAME};
65 use util::nodemap::FnvHashSet;
66
67 use std::iter::repeat;
68 use std::slice;
69 use syntax::{abi, ast, ast_util};
70 use syntax::codemap::{Span, Pos};
71 use syntax::parse::token;
72 use syntax::print::pprust;
73
74 pub trait AstConv<'tcx> {
75     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
76
77     /// Identify the type scheme for an item with a type, like a type
78     /// alias, fn, or struct. This allows you to figure out the set of
79     /// type parameters defined on the item.
80     fn get_item_type_scheme(&self, span: Span, id: ast::DefId)
81                             -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
82
83     /// Returns the `TraitDef` for a given trait. This allows you to
84     /// figure out the set of type parameters defined on the trait.
85     fn get_trait_def(&self, span: Span, id: ast::DefId)
86                      -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
87
88     /// Ensure that the super-predicates for the trait with the given
89     /// id are available and also for the transitive set of
90     /// super-predicates.
91     fn ensure_super_predicates(&self, span: Span, id: ast::DefId)
92                                -> Result<(), ErrorReported>;
93
94     /// Returns the set of bounds in scope for the type parameter with
95     /// the given id.
96     fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
97                                  -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
98
99     /// Returns true if the trait with id `trait_def_id` defines an
100     /// associated type with the name `name`.
101     fn trait_defines_associated_type_named(&self, trait_def_id: ast::DefId, name: ast::Name)
102                                            -> bool;
103
104     /// Return an (optional) substitution to convert bound type parameters that
105     /// are in scope into free ones. This function should only return Some
106     /// within a fn body.
107     /// See ParameterEnvironment::free_substs for more information.
108     fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
109         None
110     }
111
112     /// What type should we use when a type is omitted?
113     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
114
115     /// Projecting an associated type from a (potentially)
116     /// higher-ranked trait reference is more complicated, because of
117     /// the possibility of late-bound regions appearing in the
118     /// associated type binding. This is not legal in function
119     /// signatures for that reason. In a function body, we can always
120     /// handle it because we can use inference variables to remove the
121     /// late-bound regions.
122     fn projected_ty_from_poly_trait_ref(&self,
123                                         span: Span,
124                                         poly_trait_ref: ty::PolyTraitRef<'tcx>,
125                                         item_name: ast::Name)
126                                         -> Ty<'tcx>
127     {
128         if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
129             self.projected_ty(span, trait_ref, item_name)
130         } else {
131             // no late-bound regions, we can just ignore the binder
132             span_err!(self.tcx().sess, span, E0212,
133                 "cannot extract an associated type from a higher-ranked trait bound \
134                  in this context");
135             self.tcx().types.err
136         }
137     }
138
139     /// Project an associated type from a non-higher-ranked trait reference.
140     /// This is fairly straightforward and can be accommodated in any context.
141     fn projected_ty(&self,
142                     span: Span,
143                     _trait_ref: ty::TraitRef<'tcx>,
144                     _item_name: ast::Name)
145                     -> Ty<'tcx>;
146 }
147
148 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &ast::Lifetime)
149                             -> ty::Region {
150     let r = match tcx.named_region_map.get(&lifetime.id) {
151         None => {
152             // should have been recorded by the `resolve_lifetime` pass
153             tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
154         }
155
156         Some(&rl::DefStaticRegion) => {
157             ty::ReStatic
158         }
159
160         Some(&rl::DefLateBoundRegion(debruijn, id)) => {
161             ty::ReLateBound(debruijn, ty::BrNamed(ast_util::local_def(id), lifetime.name))
162         }
163
164         Some(&rl::DefEarlyBoundRegion(space, index, id)) => {
165             ty::ReEarlyBound(ty::EarlyBoundRegion {
166                 param_id: id,
167                 space: space,
168                 index: index,
169                 name: lifetime.name
170             })
171         }
172
173         Some(&rl::DefFreeRegion(scope, id)) => {
174             ty::ReFree(ty::FreeRegion {
175                     scope: scope,
176                     bound_region: ty::BrNamed(ast_util::local_def(id),
177                                               lifetime.name)
178                 })
179         }
180     };
181
182     debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
183            lifetime,
184            lifetime.id,
185            r);
186
187     r
188 }
189
190 fn report_elision_failure(
191     tcx: &ty::ctxt,
192     default_span: Span,
193     params: Vec<ElisionFailureInfo>)
194 {
195     let mut m = String::new();
196     let len = params.len();
197     for (i, info) in params.into_iter().enumerate() {
198         let ElisionFailureInfo {
199             name, lifetime_count: n, have_bound_regions
200         } = info;
201
202         let help_name = if name.is_empty() {
203             format!("argument {}", i + 1)
204         } else {
205             format!("`{}`", name)
206         };
207
208         m.push_str(&(if n == 1 {
209             help_name
210         } else {
211             format!("one of {}'s {} elided {}lifetimes", help_name, n,
212                     if have_bound_regions { "free " } else { "" } )
213         })[..]);
214
215         if len == 2 && i == 0 {
216             m.push_str(" or ");
217         } else if i + 2 == len {
218             m.push_str(", or ");
219         } else if i + 1 != len {
220             m.push_str(", ");
221         }
222     }
223     if len == 1 {
224         fileline_help!(tcx.sess, default_span,
225                        "this function's return type contains a borrowed value, but \
226                         the signature does not say which {} it is borrowed from",
227                        m);
228     } else if len == 0 {
229         fileline_help!(tcx.sess, default_span,
230                        "this function's return type contains a borrowed value, but \
231                         there is no value for it to be borrowed from");
232         fileline_help!(tcx.sess, default_span,
233                        "consider giving it a 'static lifetime");
234     } else {
235         fileline_help!(tcx.sess, default_span,
236                        "this function's return type contains a borrowed value, but \
237                         the signature does not say whether it is borrowed from {}",
238                        m);
239     }
240 }
241
242 pub fn opt_ast_region_to_region<'tcx>(
243     this: &AstConv<'tcx>,
244     rscope: &RegionScope,
245     default_span: Span,
246     opt_lifetime: &Option<ast::Lifetime>) -> ty::Region
247 {
248     let r = match *opt_lifetime {
249         Some(ref lifetime) => {
250             ast_region_to_region(this.tcx(), lifetime)
251         }
252
253         None => match rscope.anon_regions(default_span, 1) {
254             Ok(rs) => rs[0],
255             Err(params) => {
256                 span_err!(this.tcx().sess, default_span, E0106,
257                           "missing lifetime specifier");
258                 if let Some(params) = params {
259                     report_elision_failure(this.tcx(), default_span, params);
260                 }
261                 ty::ReStatic
262             }
263         }
264     };
265
266     debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
267             opt_lifetime,
268             r);
269
270     r
271 }
272
273 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
274 /// returns an appropriate set of substitutions for this particular reference to `I`.
275 pub fn ast_path_substs_for_ty<'tcx>(
276     this: &AstConv<'tcx>,
277     rscope: &RegionScope,
278     span: Span,
279     param_mode: PathParamMode,
280     decl_generics: &ty::Generics<'tcx>,
281     item_segment: &ast::PathSegment)
282     -> Substs<'tcx>
283 {
284     let tcx = this.tcx();
285
286     // ast_path_substs() is only called to convert paths that are
287     // known to refer to traits, types, or structs. In these cases,
288     // all type parameters defined for the item being referenced will
289     // be in the TypeSpace or SelfSpace.
290     //
291     // Note: in the case of traits, the self parameter is also
292     // defined, but we don't currently create a `type_param_def` for
293     // `Self` because it is implicit.
294     assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
295     assert!(decl_generics.types.all(|d| d.space != FnSpace));
296
297     let (regions, types, assoc_bindings) = match item_segment.parameters {
298         ast::AngleBracketedParameters(ref data) => {
299             convert_angle_bracketed_parameters(this, rscope, span, decl_generics, data)
300         }
301         ast::ParenthesizedParameters(..) => {
302             span_err!(tcx.sess, span, E0214,
303                       "parenthesized parameters may only be used with a trait");
304             let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
305             (Substs::empty(),
306              ty_param_defs.iter().map(|_| tcx.types.err).collect(),
307              vec![])
308         }
309     };
310
311     prohibit_projections(this.tcx(), &assoc_bindings);
312
313     create_substs_for_ast_path(this,
314                                span,
315                                param_mode,
316                                decl_generics,
317                                None,
318                                types,
319                                regions)
320 }
321
322 #[derive(PartialEq, Eq)]
323 pub enum PathParamMode {
324     // Any path in a type context.
325     Explicit,
326     // The `module::Type` in `module::Type::method` in an expression.
327     Optional
328 }
329
330 fn create_region_substs<'tcx>(
331     this: &AstConv<'tcx>,
332     rscope: &RegionScope,
333     span: Span,
334     decl_generics: &ty::Generics<'tcx>,
335     regions_provided: Vec<ty::Region>)
336     -> Substs<'tcx>
337 {
338     let tcx = this.tcx();
339
340     // If the type is parameterized by the this region, then replace this
341     // region with the current anon region binding (in other words,
342     // whatever & would get replaced with).
343     let expected_num_region_params = decl_generics.regions.len(TypeSpace);
344     let supplied_num_region_params = regions_provided.len();
345     let regions = if expected_num_region_params == supplied_num_region_params {
346         regions_provided
347     } else {
348         let anon_regions =
349             rscope.anon_regions(span, expected_num_region_params);
350
351         if supplied_num_region_params != 0 || anon_regions.is_err() {
352             report_lifetime_number_error(tcx, span,
353                                          supplied_num_region_params,
354                                          expected_num_region_params);
355         }
356
357         match anon_regions {
358             Ok(anon_regions) => anon_regions,
359             Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
360         }
361     };
362     Substs::new_type(vec![], regions)
363 }
364
365 /// Given the type/region arguments provided to some path (along with
366 /// an implicit Self, if this is a trait reference) returns the complete
367 /// set of substitutions. This may involve applying defaulted type parameters.
368 ///
369 /// Note that the type listing given here is *exactly* what the user provided.
370 ///
371 /// The `region_substs` should be the result of `create_region_substs`
372 /// -- that is, a substitution with no types but the correct number of
373 /// regions.
374 fn create_substs_for_ast_path<'tcx>(
375     this: &AstConv<'tcx>,
376     span: Span,
377     param_mode: PathParamMode,
378     decl_generics: &ty::Generics<'tcx>,
379     self_ty: Option<Ty<'tcx>>,
380     types_provided: Vec<Ty<'tcx>>,
381     region_substs: Substs<'tcx>)
382     -> Substs<'tcx>
383 {
384     let tcx = this.tcx();
385
386     debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}, \
387            types_provided={:?}, region_substs={:?}",
388            decl_generics, self_ty, types_provided,
389            region_substs);
390
391     assert_eq!(region_substs.regions().len(TypeSpace), decl_generics.regions.len(TypeSpace));
392     assert!(region_substs.types.is_empty());
393
394     // Convert the type parameters supplied by the user.
395     let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
396     let formal_ty_param_count = ty_param_defs.len();
397     let required_ty_param_count = ty_param_defs.iter()
398                                                .take_while(|x| x.default.is_none())
399                                                .count();
400
401     // Fill with `ty_infer` if no params were specified, as long as
402     // they were optional (e.g. paths inside expressions).
403     let mut type_substs = if param_mode == PathParamMode::Optional &&
404                              types_provided.is_empty() {
405         (0..formal_ty_param_count).map(|_| this.ty_infer(span)).collect()
406     } else {
407         types_provided
408     };
409
410     let supplied_ty_param_count = type_substs.len();
411     check_type_argument_count(this.tcx(), span, supplied_ty_param_count,
412                               required_ty_param_count, formal_ty_param_count);
413
414     if supplied_ty_param_count < required_ty_param_count {
415         while type_substs.len() < required_ty_param_count {
416             type_substs.push(tcx.types.err);
417         }
418     } else if supplied_ty_param_count > formal_ty_param_count {
419         type_substs.truncate(formal_ty_param_count);
420     }
421     assert!(type_substs.len() >= required_ty_param_count &&
422             type_substs.len() <= formal_ty_param_count);
423
424     let mut substs = region_substs;
425     substs.types.extend(TypeSpace, type_substs.into_iter());
426
427     match self_ty {
428         None => {
429             // If no self-type is provided, it's still possible that
430             // one was declared, because this could be an object type.
431         }
432         Some(ty) => {
433             // If a self-type is provided, one should have been
434             // "declared" (in other words, this should be a
435             // trait-ref).
436             assert!(decl_generics.types.get_self().is_some());
437             substs.types.push(SelfSpace, ty);
438         }
439     }
440
441     let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
442     for param in &ty_param_defs[actual_supplied_ty_param_count..] {
443         if let Some(default) = param.default {
444             // If we are converting an object type, then the
445             // `Self` parameter is unknown. However, some of the
446             // other type parameters may reference `Self` in their
447             // defaults. This will lead to an ICE if we are not
448             // careful!
449             if self_ty.is_none() && default.has_self_ty() {
450                 span_err!(tcx.sess, span, E0393,
451                           "the type parameter `{}` must be explicitly specified \
452                            in an object type because its default value `{}` references \
453                            the type `Self`",
454                           param.name,
455                           default);
456                 substs.types.push(TypeSpace, tcx.types.err);
457             } else {
458                 // This is a default type parameter.
459                 let default = default.subst_spanned(tcx,
460                                                     &substs,
461                                                     Some(span));
462                 substs.types.push(TypeSpace, default);
463             }
464         } else {
465             tcx.sess.span_bug(span, "extra parameter without default");
466         }
467     }
468
469     substs
470 }
471
472 struct ConvertedBinding<'tcx> {
473     item_name: ast::Name,
474     ty: Ty<'tcx>,
475     span: Span,
476 }
477
478 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
479                                             rscope: &RegionScope,
480                                             span: Span,
481                                             decl_generics: &ty::Generics<'tcx>,
482                                             data: &ast::AngleBracketedParameterData)
483                                             -> (Substs<'tcx>,
484                                                 Vec<Ty<'tcx>>,
485                                                 Vec<ConvertedBinding<'tcx>>)
486 {
487     let regions: Vec<_> =
488         data.lifetimes.iter()
489                       .map(|l| ast_region_to_region(this.tcx(), l))
490                       .collect();
491
492     let region_substs =
493         create_region_substs(this, rscope, span, decl_generics, regions);
494
495     let types: Vec<_> =
496         data.types.iter()
497                   .enumerate()
498                   .map(|(i,t)| ast_ty_arg_to_ty(this, rscope, decl_generics,
499                                                 i, &region_substs, t))
500                   .collect();
501
502     let assoc_bindings: Vec<_> =
503         data.bindings.iter()
504                      .map(|b| ConvertedBinding { item_name: b.ident.name,
505                                                  ty: ast_ty_to_ty(this, rscope, &*b.ty),
506                                                  span: b.span })
507                      .collect();
508
509     (region_substs, types, assoc_bindings)
510 }
511
512 /// Returns the appropriate lifetime to use for any output lifetimes
513 /// (if one exists) and a vector of the (pattern, number of lifetimes)
514 /// corresponding to each input type/pattern.
515 fn find_implied_output_region<'tcx>(tcx: &ty::ctxt<'tcx>,
516                                     input_tys: &[Ty<'tcx>],
517                                     input_pats: Vec<String>) -> ElidedLifetime
518 {
519     let mut lifetimes_for_params = Vec::new();
520     let mut possible_implied_output_region = None;
521
522     for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
523         let mut regions = FnvHashSet();
524         let have_bound_regions = ty_fold::collect_regions(tcx,
525                                                           input_type,
526                                                           &mut regions);
527
528         debug!("find_implied_output_regions: collected {:?} from {:?} \
529                 have_bound_regions={:?}", &regions, input_type, have_bound_regions);
530
531         if regions.len() == 1 {
532             // there's a chance that the unique lifetime of this
533             // iteration will be the appropriate lifetime for output
534             // parameters, so lets store it.
535             possible_implied_output_region = regions.iter().cloned().next();
536         }
537
538         lifetimes_for_params.push(ElisionFailureInfo {
539             name: input_pat,
540             lifetime_count: regions.len(),
541             have_bound_regions: have_bound_regions
542         });
543     }
544
545     if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
546         Ok(possible_implied_output_region.unwrap())
547     } else {
548         Err(Some(lifetimes_for_params))
549     }
550 }
551
552 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
553                                           elided_lifetime: ElidedLifetime,
554                                           ty: &ast::Ty)
555                                           -> Ty<'tcx>
556 {
557     match elided_lifetime {
558         Ok(implied_output_region) => {
559             let rb = ElidableRscope::new(implied_output_region);
560             ast_ty_to_ty(this, &rb, ty)
561         }
562         Err(param_lifetimes) => {
563             // All regions must be explicitly specified in the output
564             // if the lifetime elision rules do not apply. This saves
565             // the user from potentially-confusing errors.
566             let rb = UnelidableRscope::new(param_lifetimes);
567             ast_ty_to_ty(this, &rb, ty)
568         }
569     }
570 }
571
572 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
573                                           rscope: &RegionScope,
574                                           span: Span,
575                                           decl_generics: &ty::Generics<'tcx>,
576                                           data: &ast::ParenthesizedParameterData)
577                                           -> (Substs<'tcx>,
578                                               Vec<Ty<'tcx>>,
579                                               Vec<ConvertedBinding<'tcx>>)
580 {
581     let region_substs =
582         create_region_substs(this, rscope, span, decl_generics, Vec::new());
583
584     let binding_rscope = BindingRscope::new();
585     let inputs =
586         data.inputs.iter()
587                    .map(|a_t| ast_ty_arg_to_ty(this, &binding_rscope, decl_generics,
588                                                0, &region_substs, a_t))
589                    .collect::<Vec<Ty<'tcx>>>();
590
591     let input_params: Vec<_> = repeat(String::new()).take(inputs.len()).collect();
592     let implied_output_region = find_implied_output_region(this.tcx(), &inputs, input_params);
593
594     let input_ty = this.tcx().mk_tup(inputs);
595
596     let (output, output_span) = match data.output {
597         Some(ref output_ty) => {
598             (convert_ty_with_lifetime_elision(this,
599                                               implied_output_region,
600                                               &output_ty),
601              output_ty.span)
602         }
603         None => {
604             (this.tcx().mk_nil(), data.span)
605         }
606     };
607
608     let output_binding = ConvertedBinding {
609         item_name: token::intern(FN_OUTPUT_NAME),
610         ty: output,
611         span: output_span
612     };
613
614     (region_substs, vec![input_ty], vec![output_binding])
615 }
616
617 pub fn instantiate_poly_trait_ref<'tcx>(
618     this: &AstConv<'tcx>,
619     rscope: &RegionScope,
620     ast_trait_ref: &ast::PolyTraitRef,
621     self_ty: Option<Ty<'tcx>>,
622     poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
623     -> ty::PolyTraitRef<'tcx>
624 {
625     let trait_ref = &ast_trait_ref.trait_ref;
626     let trait_def_id = trait_def_id(this, trait_ref);
627     ast_path_to_poly_trait_ref(this,
628                                rscope,
629                                trait_ref.path.span,
630                                PathParamMode::Explicit,
631                                trait_def_id,
632                                self_ty,
633                                trait_ref.path.segments.last().unwrap(),
634                                poly_projections)
635 }
636
637 /// Instantiates the path for the given trait reference, assuming that it's
638 /// bound to a valid trait type. Returns the def_id for the defining trait.
639 /// Fails if the type is a type other than a trait type.
640 ///
641 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
642 /// are disallowed. Otherwise, they are pushed onto the vector given.
643 pub fn instantiate_mono_trait_ref<'tcx>(
644     this: &AstConv<'tcx>,
645     rscope: &RegionScope,
646     trait_ref: &ast::TraitRef,
647     self_ty: Option<Ty<'tcx>>)
648     -> ty::TraitRef<'tcx>
649 {
650     let trait_def_id = trait_def_id(this, trait_ref);
651     ast_path_to_mono_trait_ref(this,
652                                rscope,
653                                trait_ref.path.span,
654                                PathParamMode::Explicit,
655                                trait_def_id,
656                                self_ty,
657                                trait_ref.path.segments.last().unwrap())
658 }
659
660 fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &ast::TraitRef) -> ast::DefId {
661     let path = &trait_ref.path;
662     match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
663         def::DefTrait(trait_def_id) => trait_def_id,
664         _ => {
665             span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
666                         path);
667         }
668     }
669 }
670
671 fn object_path_to_poly_trait_ref<'a,'tcx>(
672     this: &AstConv<'tcx>,
673     rscope: &RegionScope,
674     span: Span,
675     param_mode: PathParamMode,
676     trait_def_id: ast::DefId,
677     trait_segment: &ast::PathSegment,
678     mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
679     -> ty::PolyTraitRef<'tcx>
680 {
681     ast_path_to_poly_trait_ref(this,
682                                rscope,
683                                span,
684                                param_mode,
685                                trait_def_id,
686                                None,
687                                trait_segment,
688                                projections)
689 }
690
691 fn ast_path_to_poly_trait_ref<'a,'tcx>(
692     this: &AstConv<'tcx>,
693     rscope: &RegionScope,
694     span: Span,
695     param_mode: PathParamMode,
696     trait_def_id: ast::DefId,
697     self_ty: Option<Ty<'tcx>>,
698     trait_segment: &ast::PathSegment,
699     poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
700     -> ty::PolyTraitRef<'tcx>
701 {
702     // The trait reference introduces a binding level here, so
703     // we need to shift the `rscope`. It'd be nice if we could
704     // do away with this rscope stuff and work this knowledge
705     // into resolve_lifetimes, as we do with non-omitted
706     // lifetimes. Oh well, not there yet.
707     let shifted_rscope = &ShiftedRscope::new(rscope);
708
709     let (substs, assoc_bindings) =
710         create_substs_for_ast_trait_ref(this,
711                                         shifted_rscope,
712                                         span,
713                                         param_mode,
714                                         trait_def_id,
715                                         self_ty,
716                                         trait_segment);
717     let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
718
719     {
720         let converted_bindings =
721             assoc_bindings
722             .iter()
723             .filter_map(|binding| {
724                 // specify type to assert that error was already reported in Err case:
725                 let predicate: Result<_, ErrorReported> =
726                     ast_type_binding_to_poly_projection_predicate(this,
727                                                                   poly_trait_ref.clone(),
728                                                                   self_ty,
729                                                                   binding);
730                 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
731             });
732         poly_projections.extend(converted_bindings);
733     }
734
735     poly_trait_ref
736 }
737
738 fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
739                                        rscope: &RegionScope,
740                                        span: Span,
741                                        param_mode: PathParamMode,
742                                        trait_def_id: ast::DefId,
743                                        self_ty: Option<Ty<'tcx>>,
744                                        trait_segment: &ast::PathSegment)
745                                        -> ty::TraitRef<'tcx>
746 {
747     let (substs, assoc_bindings) =
748         create_substs_for_ast_trait_ref(this,
749                                         rscope,
750                                         span,
751                                         param_mode,
752                                         trait_def_id,
753                                         self_ty,
754                                         trait_segment);
755     prohibit_projections(this.tcx(), &assoc_bindings);
756     ty::TraitRef::new(trait_def_id, substs)
757 }
758
759 fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
760                                             rscope: &RegionScope,
761                                             span: Span,
762                                             param_mode: PathParamMode,
763                                             trait_def_id: ast::DefId,
764                                             self_ty: Option<Ty<'tcx>>,
765                                             trait_segment: &ast::PathSegment)
766                                             -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
767 {
768     debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
769            trait_segment);
770
771     let trait_def = match this.get_trait_def(span, trait_def_id) {
772         Ok(trait_def) => trait_def,
773         Err(ErrorReported) => {
774             // No convenient way to recover from a cycle here. Just bail. Sorry!
775             this.tcx().sess.abort_if_errors();
776             this.tcx().sess.bug("ErrorReported returned, but no errors reports?")
777         }
778     };
779
780     let (regions, types, assoc_bindings) = match trait_segment.parameters {
781         ast::AngleBracketedParameters(ref data) => {
782             // For now, require that parenthetical notation be used
783             // only with `Fn()` etc.
784             if !this.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
785                 span_err!(this.tcx().sess, span, E0215,
786                                          "angle-bracket notation is not stable when \
787                                          used with the `Fn` family of traits, use parentheses");
788                 fileline_help!(this.tcx().sess, span,
789                            "add `#![feature(unboxed_closures)]` to \
790                             the crate attributes to enable");
791             }
792
793             convert_angle_bracketed_parameters(this, rscope, span, &trait_def.generics, data)
794         }
795         ast::ParenthesizedParameters(ref data) => {
796             // For now, require that parenthetical notation be used
797             // only with `Fn()` etc.
798             if !this.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
799                 span_err!(this.tcx().sess, span, E0216,
800                                          "parenthetical notation is only stable when \
801                                          used with the `Fn` family of traits");
802                 fileline_help!(this.tcx().sess, span,
803                            "add `#![feature(unboxed_closures)]` to \
804                             the crate attributes to enable");
805             }
806
807             convert_parenthesized_parameters(this, rscope, span, &trait_def.generics, data)
808         }
809     };
810
811     let substs = create_substs_for_ast_path(this,
812                                             span,
813                                             param_mode,
814                                             &trait_def.generics,
815                                             self_ty,
816                                             types,
817                                             regions);
818
819     (this.tcx().mk_substs(substs), assoc_bindings)
820 }
821
822 fn ast_type_binding_to_poly_projection_predicate<'tcx>(
823     this: &AstConv<'tcx>,
824     mut trait_ref: ty::PolyTraitRef<'tcx>,
825     self_ty: Option<Ty<'tcx>>,
826     binding: &ConvertedBinding<'tcx>)
827     -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
828 {
829     let tcx = this.tcx();
830
831     // Given something like `U : SomeTrait<T=X>`, we want to produce a
832     // predicate like `<U as SomeTrait>::T = X`. This is somewhat
833     // subtle in the event that `T` is defined in a supertrait of
834     // `SomeTrait`, because in that case we need to upcast.
835     //
836     // That is, consider this case:
837     //
838     // ```
839     // trait SubTrait : SuperTrait<int> { }
840     // trait SuperTrait<A> { type T; }
841     //
842     // ... B : SubTrait<T=foo> ...
843     // ```
844     //
845     // We want to produce `<B as SuperTrait<int>>::T == foo`.
846
847     // Simple case: X is defined in the current trait.
848     if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
849         return Ok(ty::Binder(ty::ProjectionPredicate {      // <-------------------+
850             projection_ty: ty::ProjectionTy {               //                     |
851                 trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
852                 item_name: binding.item_name,
853             },
854             ty: binding.ty,
855         }));
856     }
857
858     // Otherwise, we have to walk through the supertraits to find
859     // those that do.  This is complicated by the fact that, for an
860     // object type, the `Self` type is not present in the
861     // substitutions (after all, it's being constructed right now),
862     // but the `supertraits` iterator really wants one. To handle
863     // this, we currently insert a dummy type and then remove it
864     // later. Yuck.
865
866     let dummy_self_ty = tcx.mk_infer(ty::FreshTy(0));
867     if self_ty.is_none() { // if converting for an object type
868         let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
869         assert!(dummy_substs.self_ty().is_none());                     //                    |
870         dummy_substs.types.push(SelfSpace, dummy_self_ty);             //                    |
871         trait_ref = ty::Binder(ty::TraitRef::new(trait_ref.def_id(),   // <------------+
872                                                  tcx.mk_substs(dummy_substs)));
873     }
874
875     try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
876
877     let mut candidates: Vec<ty::PolyTraitRef> =
878         traits::supertraits(tcx, trait_ref.clone())
879         .filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
880         .collect();
881
882     // If converting for an object type, then remove the dummy-ty from `Self` now.
883     // Yuckety yuck.
884     if self_ty.is_none() {
885         for candidate in &mut candidates {
886             let mut dummy_substs = candidate.0.substs.clone();
887             assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
888             dummy_substs.types.pop(SelfSpace);
889             *candidate = ty::Binder(ty::TraitRef::new(candidate.def_id(),
890                                                       tcx.mk_substs(dummy_substs)));
891         }
892     }
893
894     let candidate = try!(one_bound_for_assoc_type(tcx,
895                                                   candidates,
896                                                   &trait_ref.to_string(),
897                                                   &token::get_name(binding.item_name),
898                                                   binding.span));
899
900     Ok(ty::Binder(ty::ProjectionPredicate {             // <-------------------------+
901         projection_ty: ty::ProjectionTy {               //                           |
902             trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
903             item_name: binding.item_name,
904         },
905         ty: binding.ty,
906     }))
907 }
908
909 fn ast_path_to_ty<'tcx>(
910     this: &AstConv<'tcx>,
911     rscope: &RegionScope,
912     span: Span,
913     param_mode: PathParamMode,
914     did: ast::DefId,
915     item_segment: &ast::PathSegment)
916     -> Ty<'tcx>
917 {
918     let tcx = this.tcx();
919     let (generics, decl_ty) = match this.get_item_type_scheme(span, did) {
920         Ok(ty::TypeScheme { generics,  ty: decl_ty }) => {
921             (generics, decl_ty)
922         }
923         Err(ErrorReported) => {
924             return tcx.types.err;
925         }
926     };
927
928     let substs = ast_path_substs_for_ty(this,
929                                         rscope,
930                                         span,
931                                         param_mode,
932                                         &generics,
933                                         item_segment);
934
935     // FIXME(#12938): This is a hack until we have full support for DST.
936     if Some(did) == this.tcx().lang_items.owned_box() {
937         assert_eq!(substs.types.len(TypeSpace), 1);
938         return this.tcx().mk_box(*substs.types.get(TypeSpace, 0));
939     }
940
941     decl_ty.subst(this.tcx(), &substs)
942 }
943
944 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
945
946 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
947                              rscope: &RegionScope,
948                              ty: &ast::Ty,
949                              bounds: &[ast::TyParamBound])
950                              -> Result<TraitAndProjections<'tcx>, ErrorReported>
951 {
952     /*!
953      * In a type like `Foo + Send`, we want to wait to collect the
954      * full set of bounds before we make the object type, because we
955      * need them to infer a region bound.  (For example, if we tried
956      * made a type from just `Foo`, then it wouldn't be enough to
957      * infer a 'static bound, and hence the user would get an error.)
958      * So this function is used when we're dealing with a sum type to
959      * convert the LHS. It only accepts a type that refers to a trait
960      * name, and reports an error otherwise.
961      */
962
963     match ty.node {
964         ast::TyPath(None, ref path) => {
965             let def = match this.tcx().def_map.borrow().get(&ty.id) {
966                 Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
967                 _ => None
968             };
969             match def {
970                 Some(def::DefTrait(trait_def_id)) => {
971                     let mut projection_bounds = Vec::new();
972                     let trait_ref = object_path_to_poly_trait_ref(this,
973                                                                   rscope,
974                                                                   path.span,
975                                                                   PathParamMode::Explicit,
976                                                                   trait_def_id,
977                                                                   path.segments.last().unwrap(),
978                                                                   &mut projection_bounds);
979                     Ok((trait_ref, projection_bounds))
980                 }
981                 _ => {
982                     span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
983                     Err(ErrorReported)
984                 }
985             }
986         }
987         _ => {
988             span_err!(this.tcx().sess, ty.span, E0178,
989                       "expected a path on the left-hand side of `+`, not `{}`",
990                       pprust::ty_to_string(ty));
991             let hi = bounds.iter().map(|x| match *x {
992                 ast::TraitTyParamBound(ref tr, _) => tr.span.hi,
993                 ast::RegionTyParamBound(ref r) => r.span.hi,
994             }).max_by(|x| x.to_usize());
995             let full_span = hi.map(|hi| Span {
996                 lo: ty.span.lo,
997                 hi: hi,
998                 expn_id: ty.span.expn_id,
999             });
1000             match (&ty.node, full_span) {
1001                 (&ast::TyRptr(None, ref mut_ty), Some(full_span)) => {
1002                     let mutbl_str = if mut_ty.mutbl == ast::MutMutable { "mut " } else { "" };
1003                     this.tcx().sess
1004                         .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1005                                          format!("&{}({} +{})",
1006                                                  mutbl_str,
1007                                                  pprust::ty_to_string(&*mut_ty.ty),
1008                                                  pprust::bounds_to_string(bounds)));
1009                 }
1010                 (&ast::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1011                     let mutbl_str = if mut_ty.mutbl == ast::MutMutable { "mut " } else { "" };
1012                     this.tcx().sess
1013                         .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1014                                          format!("&{} {}({} +{})",
1015                                                  pprust::lifetime_to_string(lt),
1016                                                  mutbl_str,
1017                                                  pprust::ty_to_string(&*mut_ty.ty),
1018                                                  pprust::bounds_to_string(bounds)));
1019                 }
1020
1021                 _ => {
1022                     fileline_help!(this.tcx().sess, ty.span,
1023                                "perhaps you forgot parentheses? (per RFC 438)");
1024                 }
1025             }
1026             Err(ErrorReported)
1027         }
1028     }
1029 }
1030
1031 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
1032                                   rscope: &RegionScope,
1033                                   span: Span,
1034                                   trait_ref: ty::PolyTraitRef<'tcx>,
1035                                   projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1036                                   bounds: &[ast::TyParamBound])
1037                                   -> Ty<'tcx>
1038 {
1039     let existential_bounds = conv_existential_bounds(this,
1040                                                      rscope,
1041                                                      span,
1042                                                      trait_ref.clone(),
1043                                                      projection_bounds,
1044                                                      bounds);
1045
1046     let result = make_object_type(this, span, trait_ref, existential_bounds);
1047     debug!("trait_ref_to_object_type: result={:?}",
1048            result);
1049
1050     result
1051 }
1052
1053 fn make_object_type<'tcx>(this: &AstConv<'tcx>,
1054                           span: Span,
1055                           principal: ty::PolyTraitRef<'tcx>,
1056                           bounds: ty::ExistentialBounds<'tcx>)
1057                           -> Ty<'tcx> {
1058     let tcx = this.tcx();
1059     let object = ty::TraitTy {
1060         principal: principal,
1061         bounds: bounds
1062     };
1063     let object_trait_ref =
1064         object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
1065
1066     // ensure the super predicates and stop if we encountered an error
1067     if this.ensure_super_predicates(span, object.principal_def_id()).is_err() {
1068         return tcx.types.err;
1069     }
1070
1071     let mut associated_types: FnvHashSet<(ast::DefId, ast::Name)> =
1072         traits::supertraits(tcx, object_trait_ref)
1073         .flat_map(|tr| {
1074             let trait_def = tcx.lookup_trait_def(tr.def_id());
1075             trait_def.associated_type_names
1076                 .clone()
1077                 .into_iter()
1078                 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1079         })
1080         .collect();
1081
1082     for projection_bound in &object.bounds.projection_bounds {
1083         let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1084                     projection_bound.0.projection_ty.item_name);
1085         associated_types.remove(&pair);
1086     }
1087
1088     for (trait_def_id, name) in associated_types {
1089         span_err!(tcx.sess, span, E0191,
1090             "the value of the associated type `{}` (from the trait `{}`) must be specified",
1091                     name,
1092                     tcx.item_path_str(trait_def_id));
1093     }
1094
1095     tcx.mk_trait(object.principal, object.bounds)
1096 }
1097
1098 fn report_ambiguous_associated_type(tcx: &ty::ctxt,
1099                                     span: Span,
1100                                     type_str: &str,
1101                                     trait_str: &str,
1102                                     name: &str) {
1103     span_err!(tcx.sess, span, E0223,
1104               "ambiguous associated type; specify the type using the syntax \
1105                `<{} as {}>::{}`",
1106               type_str, trait_str, name);
1107 }
1108
1109 // Search for a bound on a type parameter which includes the associated item
1110 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1111 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1112 // impl). This function will fail if there are no suitable bounds or there is
1113 // any ambiguity.
1114 fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>,
1115                                    ty_param_node_id: ast::NodeId,
1116                                    ty_param_name: Option<ast::Name>,
1117                                    assoc_name: ast::Name,
1118                                    span: Span)
1119                                    -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1120 {
1121     let tcx = this.tcx();
1122
1123     let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
1124         Ok(v) => v,
1125         Err(ErrorReported) => {
1126             return Err(ErrorReported);
1127         }
1128     };
1129
1130     // Ensure the super predicates and stop if we encountered an error.
1131     if bounds.iter().any(|b| this.ensure_super_predicates(span, b.def_id()).is_err()) {
1132         return Err(ErrorReported);
1133     }
1134
1135     // Check that there is exactly one way to find an associated type with the
1136     // correct name.
1137     let suitable_bounds: Vec<_> =
1138         traits::transitive_bounds(tcx, &bounds)
1139         .filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name))
1140         .collect();
1141
1142     if let Some(s) = ty_param_name {
1143         // borrowck doesn't like this any other way
1144         one_bound_for_assoc_type(tcx,
1145                                  suitable_bounds,
1146                                  &token::get_name(s),
1147                                  &token::get_name(assoc_name),
1148                                  span)
1149     } else {
1150         one_bound_for_assoc_type(tcx,
1151                                  suitable_bounds,
1152                                  "Self",
1153                                  &token::get_name(assoc_name),
1154                                  span)
1155
1156     }
1157 }
1158
1159
1160 // Checks that bounds contains exactly one element and reports appropriate
1161 // errors otherwise.
1162 fn one_bound_for_assoc_type<'tcx>(tcx: &ty::ctxt<'tcx>,
1163                                   bounds: Vec<ty::PolyTraitRef<'tcx>>,
1164                                   ty_param_name: &str,
1165                                   assoc_name: &str,
1166                                   span: Span)
1167     -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1168 {
1169     if bounds.is_empty() {
1170         span_err!(tcx.sess, span, E0220,
1171                   "associated type `{}` not found for `{}`",
1172                   assoc_name,
1173                   ty_param_name);
1174         return Err(ErrorReported);
1175     }
1176
1177     if bounds.len() > 1 {
1178         span_err!(tcx.sess, span, E0221,
1179                   "ambiguous associated type `{}` in bounds of `{}`",
1180                   assoc_name,
1181                   ty_param_name);
1182
1183         for bound in &bounds {
1184             span_note!(tcx.sess, span,
1185                        "associated type `{}` could derive from `{}`",
1186                        ty_param_name,
1187                        bound);
1188         }
1189     }
1190
1191     Ok(bounds[0].clone())
1192 }
1193
1194 // Create a type from a a path to an associated type.
1195 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1196 // and item_segment is the path segment for D. We return a type and a def for
1197 // the whole path.
1198 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1199 // parameter or Self.
1200 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1201                                    span: Span,
1202                                    ty: Ty<'tcx>,
1203                                    ty_path_def: def::Def,
1204                                    item_segment: &ast::PathSegment)
1205                                    -> (Ty<'tcx>, def::Def)
1206 {
1207     let tcx = this.tcx();
1208     let assoc_name = item_segment.identifier.name;
1209
1210     debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1211
1212     check_path_args(tcx, slice::ref_slice(item_segment), NO_TPS | NO_REGIONS);
1213
1214     // Find the type of the associated item, and the trait where the associated
1215     // item is declared.
1216     let bound = match (&ty.sty, ty_path_def) {
1217         (_, def::DefSelfTy(Some(trait_did), Some((impl_id, _)))) => {
1218             // `Self` in an impl of a trait - we have a concrete self type and a
1219             // trait reference.
1220             match tcx.map.expect_item(impl_id).node {
1221                 ast::ItemImpl(_, _, _, Some(ref trait_ref), _, _) => {
1222                     if this.ensure_super_predicates(span, trait_did).is_err() {
1223                         return (tcx.types.err, ty_path_def);
1224                     }
1225
1226                     let trait_segment = &trait_ref.path.segments.last().unwrap();
1227                     let trait_ref = ast_path_to_mono_trait_ref(this,
1228                                                                &ExplicitRscope,
1229                                                                span,
1230                                                                PathParamMode::Explicit,
1231                                                                trait_did,
1232                                                                Some(ty),
1233                                                                trait_segment);
1234
1235                     let candidates: Vec<ty::PolyTraitRef> =
1236                         traits::supertraits(tcx, ty::Binder(trait_ref.clone()))
1237                         .filter(|r| this.trait_defines_associated_type_named(r.def_id(),
1238                                                                              assoc_name))
1239                         .collect();
1240
1241                     match one_bound_for_assoc_type(tcx,
1242                                                    candidates,
1243                                                    "Self",
1244                                                    &token::get_name(assoc_name),
1245                                                    span) {
1246                         Ok(bound) => bound,
1247                         Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1248                     }
1249                 }
1250                 _ => unreachable!()
1251             }
1252         }
1253         (&ty::TyParam(_), def::DefSelfTy(Some(trait_did),  None)) => {
1254             assert_eq!(trait_did.krate, ast::LOCAL_CRATE);
1255             match find_bound_for_assoc_item(this, trait_did.node, None, assoc_name, span) {
1256                 Ok(bound) => bound,
1257                 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1258             }
1259         }
1260         (&ty::TyParam(_), def::DefTyParam(_, _, param_did, param_name)) => {
1261             assert_eq!(param_did.krate, ast::LOCAL_CRATE);
1262             match find_bound_for_assoc_item(this,
1263                                             param_did.node,
1264                                             Some(param_name),
1265                                             assoc_name,
1266                                             span) {
1267                 Ok(bound) => bound,
1268                 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1269             }
1270         }
1271         _ => {
1272             report_ambiguous_associated_type(tcx,
1273                                              span,
1274                                              &ty.to_string(),
1275                                              "Trait",
1276                                              &token::get_name(assoc_name));
1277             return (tcx.types.err, ty_path_def);
1278         }
1279     };
1280
1281     let trait_did = bound.0.def_id;
1282     let ty = this.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1283
1284     let item_did = if trait_did.krate == ast::LOCAL_CRATE {
1285         // `ty::trait_items` used below requires information generated
1286         // by type collection, which may be in progress at this point.
1287         match tcx.map.expect_item(trait_did.node).node {
1288             ast::ItemTrait(_, _, _, ref trait_items) => {
1289                 let item = trait_items.iter()
1290                                       .find(|i| i.ident.name == assoc_name)
1291                                       .expect("missing associated type");
1292                 ast_util::local_def(item.id)
1293             }
1294             _ => unreachable!()
1295         }
1296     } else {
1297         let trait_items = tcx.trait_items(trait_did);
1298         let item = trait_items.iter().find(|i| i.name() == assoc_name);
1299         item.expect("missing associated type").def_id()
1300     };
1301
1302     (ty, def::DefAssociatedTy(trait_did, item_did))
1303 }
1304
1305 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
1306                      rscope: &RegionScope,
1307                      span: Span,
1308                      param_mode: PathParamMode,
1309                      opt_self_ty: Option<Ty<'tcx>>,
1310                      trait_def_id: ast::DefId,
1311                      trait_segment: &ast::PathSegment,
1312                      item_segment: &ast::PathSegment)
1313                      -> Ty<'tcx>
1314 {
1315     let tcx = this.tcx();
1316
1317     check_path_args(tcx, slice::ref_slice(item_segment), NO_TPS | NO_REGIONS);
1318
1319     let self_ty = if let Some(ty) = opt_self_ty {
1320         ty
1321     } else {
1322         let path_str = tcx.item_path_str(trait_def_id);
1323         report_ambiguous_associated_type(tcx,
1324                                          span,
1325                                          "Type",
1326                                          &path_str,
1327                                          &token::get_ident(item_segment.identifier));
1328         return tcx.types.err;
1329     };
1330
1331     debug!("qpath_to_ty: self_type={:?}", self_ty);
1332
1333     let trait_ref = ast_path_to_mono_trait_ref(this,
1334                                                rscope,
1335                                                span,
1336                                                param_mode,
1337                                                trait_def_id,
1338                                                Some(self_ty),
1339                                                trait_segment);
1340
1341     debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1342
1343     this.projected_ty(span, trait_ref, item_segment.identifier.name)
1344 }
1345
1346 /// Convert a type supplied as value for a type argument from AST into our
1347 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1348 /// it applies the object lifetime default.
1349 ///
1350 /// # Parameters
1351 ///
1352 /// * `this`, `rscope`: the surrounding context
1353 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1354 ///   referenced
1355 /// * `index`: the index of the type parameter being instantiated from the list
1356 ///   (we assume it is in the `TypeSpace`)
1357 /// * `region_substs`: a partial substitution consisting of
1358 ///   only the region type parameters being supplied to this type.
1359 /// * `ast_ty`: the ast representation of the type being supplied
1360 pub fn ast_ty_arg_to_ty<'tcx>(this: &AstConv<'tcx>,
1361                               rscope: &RegionScope,
1362                               decl_generics: &ty::Generics<'tcx>,
1363                               index: usize,
1364                               region_substs: &Substs<'tcx>,
1365                               ast_ty: &ast::Ty)
1366                               -> Ty<'tcx>
1367 {
1368     let tcx = this.tcx();
1369
1370     if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1371         let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1372         let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1373         ast_ty_to_ty(this, rscope1, ast_ty)
1374     } else {
1375         ast_ty_to_ty(this, rscope, ast_ty)
1376     }
1377 }
1378
1379 // Check the base def in a PathResolution and convert it to a Ty. If there are
1380 // associated types in the PathResolution, these will need to be separately
1381 // resolved.
1382 fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1383                         rscope: &RegionScope,
1384                         span: Span,
1385                         param_mode: PathParamMode,
1386                         def: &def::Def,
1387                         opt_self_ty: Option<Ty<'tcx>>,
1388                         base_segments: &[ast::PathSegment])
1389                         -> Ty<'tcx> {
1390     let tcx = this.tcx();
1391
1392     match *def {
1393         def::DefTrait(trait_def_id) => {
1394             // N.B. this case overlaps somewhat with
1395             // TyObjectSum, see that fn for details
1396             let mut projection_bounds = Vec::new();
1397
1398             let trait_ref = object_path_to_poly_trait_ref(this,
1399                                                           rscope,
1400                                                           span,
1401                                                           param_mode,
1402                                                           trait_def_id,
1403                                                           base_segments.last().unwrap(),
1404                                                           &mut projection_bounds);
1405
1406             check_path_args(tcx, base_segments.init(), NO_TPS | NO_REGIONS);
1407             trait_ref_to_object_type(this,
1408                                      rscope,
1409                                      span,
1410                                      trait_ref,
1411                                      projection_bounds,
1412                                      &[])
1413         }
1414         def::DefTy(did, _) | def::DefStruct(did) => {
1415             check_path_args(tcx, base_segments.init(), NO_TPS | NO_REGIONS);
1416             ast_path_to_ty(this,
1417                            rscope,
1418                            span,
1419                            param_mode,
1420                            did,
1421                            base_segments.last().unwrap())
1422         }
1423         def::DefTyParam(space, index, _, name) => {
1424             check_path_args(tcx, base_segments, NO_TPS | NO_REGIONS);
1425             tcx.mk_param(space, index, name)
1426         }
1427         def::DefSelfTy(_, Some((_, self_ty_id))) => {
1428             // Self in impl (we know the concrete type).
1429             check_path_args(tcx, base_segments, NO_TPS | NO_REGIONS);
1430             if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&self_ty_id) {
1431                 if let Some(free_substs) = this.get_free_substs() {
1432                     ty.subst(tcx, free_substs)
1433                 } else {
1434                     ty
1435                 }
1436             } else {
1437                 tcx.sess.span_bug(span, "self type has not been fully resolved")
1438             }
1439         }
1440         def::DefSelfTy(Some(_), None) => {
1441             // Self in trait.
1442             check_path_args(tcx, base_segments, NO_TPS | NO_REGIONS);
1443             tcx.mk_self_type()
1444         }
1445         def::DefAssociatedTy(trait_did, _) => {
1446             check_path_args(tcx, &base_segments[..base_segments.len()-2], NO_TPS | NO_REGIONS);
1447             qpath_to_ty(this,
1448                         rscope,
1449                         span,
1450                         param_mode,
1451                         opt_self_ty,
1452                         trait_did,
1453                         &base_segments[base_segments.len()-2],
1454                         base_segments.last().unwrap())
1455         }
1456         def::DefMod(id) => {
1457             // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1458             // FIXME(#22519) This part of the resolution logic should be
1459             // avoided entirely for that form, once we stop needed a Def
1460             // for `associated_path_def_to_ty`.
1461             // Fixing this will also let use resolve <Self>::Foo the same way we
1462             // resolve Self::Foo, at the moment we can't resolve the former because
1463             // we don't have the trait information around, which is just sad.
1464
1465             if !base_segments.is_empty() {
1466                 span_err!(tcx.sess,
1467                           span,
1468                           E0247,
1469                           "found module name used as a type: {}",
1470                           tcx.map.node_to_string(id.node));
1471                 return this.tcx().types.err;
1472             }
1473
1474             opt_self_ty.expect("missing T in <T>::a::b::c")
1475         }
1476         def::DefPrimTy(prim_ty) => {
1477             prim_ty_to_ty(tcx, base_segments, prim_ty)
1478         }
1479         _ => {
1480             span_err!(tcx.sess, span, E0248,
1481                       "found value name used as a type: {:?}", *def);
1482             return this.tcx().types.err;
1483         }
1484     }
1485 }
1486
1487 // Note that both base_segments and assoc_segments may be empty, although not at
1488 // the same time.
1489 pub fn finish_resolving_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1490                                         rscope: &RegionScope,
1491                                         span: Span,
1492                                         param_mode: PathParamMode,
1493                                         def: &def::Def,
1494                                         opt_self_ty: Option<Ty<'tcx>>,
1495                                         base_segments: &[ast::PathSegment],
1496                                         assoc_segments: &[ast::PathSegment])
1497                                         -> Ty<'tcx> {
1498     let mut ty = base_def_to_ty(this,
1499                                 rscope,
1500                                 span,
1501                                 param_mode,
1502                                 def,
1503                                 opt_self_ty,
1504                                 base_segments);
1505     let mut def = *def;
1506     // If any associated type segments remain, attempt to resolve them.
1507     for segment in assoc_segments {
1508         if ty.sty == ty::TyError {
1509             break;
1510         }
1511         // This is pretty bad (it will fail except for T::A and Self::A).
1512         let (a_ty, a_def) = associated_path_def_to_ty(this,
1513                                                       span,
1514                                                       ty,
1515                                                       def,
1516                                                       segment);
1517         ty = a_ty;
1518         def = a_def;
1519     }
1520     ty
1521 }
1522
1523 /// Parses the programmer's textual representation of a type into our
1524 /// internal notion of a type.
1525 pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
1526                           rscope: &RegionScope,
1527                           ast_ty: &ast::Ty)
1528                           -> Ty<'tcx>
1529 {
1530     debug!("ast_ty_to_ty(ast_ty={:?})",
1531            ast_ty);
1532
1533     let tcx = this.tcx();
1534
1535     if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&ast_ty.id) {
1536         return ty;
1537     }
1538
1539     let typ = match ast_ty.node {
1540         ast::TyVec(ref ty) => {
1541             tcx.mk_slice(ast_ty_to_ty(this, rscope, &**ty))
1542         }
1543         ast::TyObjectSum(ref ty, ref bounds) => {
1544             match ast_ty_to_trait_ref(this, rscope, &**ty, bounds) {
1545                 Ok((trait_ref, projection_bounds)) => {
1546                     trait_ref_to_object_type(this,
1547                                              rscope,
1548                                              ast_ty.span,
1549                                              trait_ref,
1550                                              projection_bounds,
1551                                              bounds)
1552                 }
1553                 Err(ErrorReported) => {
1554                     this.tcx().types.err
1555                 }
1556             }
1557         }
1558         ast::TyPtr(ref mt) => {
1559             tcx.mk_ptr(ty::mt {
1560                 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
1561                 mutbl: mt.mutbl
1562             })
1563         }
1564         ast::TyRptr(ref region, ref mt) => {
1565             let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1566             debug!("TyRef r={:?}", r);
1567             let rscope1 =
1568                 &ObjectLifetimeDefaultRscope::new(
1569                     rscope,
1570                     ty::ObjectLifetimeDefault::Specific(r));
1571             let t = ast_ty_to_ty(this, rscope1, &*mt.ty);
1572             tcx.mk_ref(tcx.mk_region(r), ty::mt {ty: t, mutbl: mt.mutbl})
1573         }
1574         ast::TyTup(ref fields) => {
1575             let flds = fields.iter()
1576                              .map(|t| ast_ty_to_ty(this, rscope, &**t))
1577                              .collect();
1578             tcx.mk_tup(flds)
1579         }
1580         ast::TyParen(ref typ) => ast_ty_to_ty(this, rscope, &**typ),
1581         ast::TyBareFn(ref bf) => {
1582             if bf.decl.variadic && bf.abi != abi::C {
1583                 span_err!(tcx.sess, ast_ty.span, E0045,
1584                           "variadic function must have C calling convention");
1585             }
1586             let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
1587             tcx.mk_fn(None, tcx.mk_bare_fn(bare_fn))
1588         }
1589         ast::TyPolyTraitRef(ref bounds) => {
1590             conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds)
1591         }
1592         ast::TyPath(ref maybe_qself, ref path) => {
1593             let path_res = if let Some(&d) = tcx.def_map.borrow().get(&ast_ty.id) {
1594                 d
1595             } else if let Some(ast::QSelf { position: 0, .. }) = *maybe_qself {
1596                 // Create some fake resolution that can't possibly be a type.
1597                 def::PathResolution {
1598                     base_def: def::DefMod(ast_util::local_def(ast::CRATE_NODE_ID)),
1599                     last_private: LastMod(AllPublic),
1600                     depth: path.segments.len()
1601                 }
1602             } else {
1603                 tcx.sess.span_bug(ast_ty.span, &format!("unbound path {:?}", ast_ty))
1604             };
1605             let def = path_res.base_def;
1606             let base_ty_end = path.segments.len() - path_res.depth;
1607             let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1608                 ast_ty_to_ty(this, rscope, &qself.ty)
1609             });
1610             let ty = finish_resolving_def_to_ty(this,
1611                                                 rscope,
1612                                                 ast_ty.span,
1613                                                 PathParamMode::Explicit,
1614                                                 &def,
1615                                                 opt_self_ty,
1616                                                 &path.segments[..base_ty_end],
1617                                                 &path.segments[base_ty_end..]);
1618
1619             if path_res.depth != 0 && ty.sty != ty::TyError {
1620                 // Write back the new resolution.
1621                 tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
1622                     base_def: def,
1623                     last_private: path_res.last_private,
1624                     depth: 0
1625                 });
1626             }
1627
1628             ty
1629         }
1630         ast::TyFixedLengthVec(ref ty, ref e) => {
1631             match const_eval::eval_const_expr_partial(tcx, &**e, Some(tcx.types.usize)) {
1632                 Ok(r) => {
1633                     match r {
1634                         ConstVal::Int(i) =>
1635                             tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1636                                          i as usize),
1637                         ConstVal::Uint(i) =>
1638                             tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1639                                          i as usize),
1640                         _ => {
1641                             span_err!(tcx.sess, ast_ty.span, E0249,
1642                                       "expected constant integer expression \
1643                                        for array length");
1644                             this.tcx().types.err
1645                         }
1646                     }
1647                 }
1648                 Err(ref r) => {
1649                     let subspan  =
1650                         ast_ty.span.lo <= r.span.lo && r.span.hi <= ast_ty.span.hi;
1651                     span_err!(tcx.sess, r.span, E0250,
1652                               "array length constant evaluation error: {}",
1653                               r.description());
1654                     if !subspan {
1655                         span_note!(tcx.sess, ast_ty.span, "for array length here")
1656                     }
1657                     this.tcx().types.err
1658                 }
1659             }
1660         }
1661         ast::TyTypeof(ref _e) => {
1662             tcx.sess.span_bug(ast_ty.span, "typeof is reserved but unimplemented");
1663         }
1664         ast::TyInfer => {
1665             // TyInfer also appears as the type of arguments or return
1666             // values in a ExprClosure, or as
1667             // the type of local variables. Both of these cases are
1668             // handled specially and will not descend into this routine.
1669             this.ty_infer(ast_ty.span)
1670         }
1671     };
1672
1673     tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, typ);
1674     return typ;
1675 }
1676
1677 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1678                        rscope: &RegionScope,
1679                        a: &ast::Arg,
1680                        expected_ty: Option<Ty<'tcx>>)
1681                        -> Ty<'tcx>
1682 {
1683     match a.ty.node {
1684         ast::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1685         ast::TyInfer => this.ty_infer(a.ty.span),
1686         _ => ast_ty_to_ty(this, rscope, &*a.ty),
1687     }
1688 }
1689
1690 struct SelfInfo<'a, 'tcx> {
1691     untransformed_self_ty: Ty<'tcx>,
1692     explicit_self: &'a ast::ExplicitSelf,
1693 }
1694
1695 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1696                           sig: &ast::MethodSig,
1697                           untransformed_self_ty: Ty<'tcx>)
1698                           -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1699     let self_info = Some(SelfInfo {
1700         untransformed_self_ty: untransformed_self_ty,
1701         explicit_self: &sig.explicit_self,
1702     });
1703     let (bare_fn_ty, optional_explicit_self_category) =
1704         ty_of_method_or_bare_fn(this,
1705                                 sig.unsafety,
1706                                 sig.abi,
1707                                 self_info,
1708                                 &sig.decl);
1709     (bare_fn_ty, optional_explicit_self_category.unwrap())
1710 }
1711
1712 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: ast::Unsafety, abi: abi::Abi,
1713                                               decl: &ast::FnDecl) -> ty::BareFnTy<'tcx> {
1714     let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1715     bare_fn_ty
1716 }
1717
1718 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1719                                      unsafety: ast::Unsafety,
1720                                      abi: abi::Abi,
1721                                      opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1722                                      decl: &ast::FnDecl)
1723                                      -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1724 {
1725     debug!("ty_of_method_or_bare_fn");
1726
1727     // New region names that appear inside of the arguments of the function
1728     // declaration are bound to that function type.
1729     let rb = rscope::BindingRscope::new();
1730
1731     // `implied_output_region` is the region that will be assumed for any
1732     // region parameters in the return type. In accordance with the rules for
1733     // lifetime elision, we can determine it in two ways. First (determined
1734     // here), if self is by-reference, then the implied output region is the
1735     // region of the self parameter.
1736     let mut explicit_self_category_result = None;
1737     let (self_ty, implied_output_region) = match opt_self_info {
1738         None => (None, None),
1739         Some(self_info) => {
1740             // This type comes from an impl or trait; no late-bound
1741             // regions should be present.
1742             assert!(!self_info.untransformed_self_ty.has_escaping_regions());
1743
1744             // Figure out and record the explicit self category.
1745             let explicit_self_category =
1746                 determine_explicit_self_category(this, &rb, &self_info);
1747             explicit_self_category_result = Some(explicit_self_category);
1748             match explicit_self_category {
1749                 ty::StaticExplicitSelfCategory => {
1750                     (None, None)
1751                 }
1752                 ty::ByValueExplicitSelfCategory => {
1753                     (Some(self_info.untransformed_self_ty), None)
1754                 }
1755                 ty::ByReferenceExplicitSelfCategory(region, mutability) => {
1756                     (Some(this.tcx().mk_ref(
1757                                       this.tcx().mk_region(region),
1758                                       ty::mt {
1759                                         ty: self_info.untransformed_self_ty,
1760                                         mutbl: mutability
1761                                       })),
1762                      Some(region))
1763                 }
1764                 ty::ByBoxExplicitSelfCategory => {
1765                     (Some(this.tcx().mk_box(self_info.untransformed_self_ty)), None)
1766                 }
1767             }
1768         }
1769     };
1770
1771     // HACK(eddyb) replace the fake self type in the AST with the actual type.
1772     let input_params = if self_ty.is_some() {
1773         &decl.inputs[1..]
1774     } else {
1775         &decl.inputs[..]
1776     };
1777     let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None));
1778     let input_pats: Vec<String> = input_params.iter()
1779                                               .map(|a| pprust::pat_to_string(&*a.pat))
1780                                               .collect();
1781     let self_and_input_tys: Vec<Ty> =
1782         self_ty.into_iter().chain(input_tys).collect();
1783
1784
1785     // Second, if there was exactly one lifetime (either a substitution or a
1786     // reference) in the arguments, then any anonymous regions in the output
1787     // have that lifetime.
1788     let implied_output_region = match implied_output_region {
1789         Some(r) => Ok(r),
1790         None => {
1791             let input_tys = if self_ty.is_some() {
1792                 // Skip the first argument if `self` is present.
1793                 &self_and_input_tys[1..]
1794             } else {
1795                 &self_and_input_tys[..]
1796             };
1797
1798             find_implied_output_region(this.tcx(), input_tys, input_pats)
1799         }
1800     };
1801
1802     let output_ty = match decl.output {
1803         ast::Return(ref output) if output.node == ast::TyInfer =>
1804             ty::FnConverging(this.ty_infer(output.span)),
1805         ast::Return(ref output) =>
1806             ty::FnConverging(convert_ty_with_lifetime_elision(this,
1807                                                               implied_output_region,
1808                                                               &output)),
1809         ast::DefaultReturn(..) => ty::FnConverging(this.tcx().mk_nil()),
1810         ast::NoReturn(..) => ty::FnDiverging
1811     };
1812
1813     (ty::BareFnTy {
1814         unsafety: unsafety,
1815         abi: abi,
1816         sig: ty::Binder(ty::FnSig {
1817             inputs: self_and_input_tys,
1818             output: output_ty,
1819             variadic: decl.variadic
1820         }),
1821     }, explicit_self_category_result)
1822 }
1823
1824 fn determine_explicit_self_category<'a, 'tcx>(this: &AstConv<'tcx>,
1825                                               rscope: &RegionScope,
1826                                               self_info: &SelfInfo<'a, 'tcx>)
1827                                               -> ty::ExplicitSelfCategory
1828 {
1829     return match self_info.explicit_self.node {
1830         ast::SelfStatic => ty::StaticExplicitSelfCategory,
1831         ast::SelfValue(_) => ty::ByValueExplicitSelfCategory,
1832         ast::SelfRegion(ref lifetime, mutability, _) => {
1833             let region =
1834                 opt_ast_region_to_region(this,
1835                                          rscope,
1836                                          self_info.explicit_self.span,
1837                                          lifetime);
1838             ty::ByReferenceExplicitSelfCategory(region, mutability)
1839         }
1840         ast::SelfExplicit(ref ast_type, _) => {
1841             let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1842
1843             // We wish to (for now) categorize an explicit self
1844             // declaration like `self: SomeType` into either `self`,
1845             // `&self`, `&mut self`, or `Box<self>`. We do this here
1846             // by some simple pattern matching. A more precise check
1847             // is done later in `check_method_self_type()`.
1848             //
1849             // Examples:
1850             //
1851             // ```
1852             // impl Foo for &T {
1853             //     // Legal declarations:
1854             //     fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1855             //     fn method2(self: &T); // ByValueExplicitSelfCategory
1856             //     fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1857             //
1858             //     // Invalid cases will be caught later by `check_method_self_type`:
1859             //     fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1860             // }
1861             // ```
1862             //
1863             // To do the check we just count the number of "modifiers"
1864             // on each type and compare them. If they are the same or
1865             // the impl has more, we call it "by value". Otherwise, we
1866             // look at the outermost modifier on the method decl and
1867             // call it by-ref, by-box as appropriate. For method1, for
1868             // example, the impl type has one modifier, but the method
1869             // type has two, so we end up with
1870             // ByReferenceExplicitSelfCategory.
1871
1872             let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1873             let method_modifiers = count_modifiers(explicit_type);
1874
1875             debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1876                    explicit_type={:?} \
1877                    modifiers=({},{})",
1878                    self_info.untransformed_self_ty,
1879                    explicit_type,
1880                    impl_modifiers,
1881                    method_modifiers);
1882
1883             if impl_modifiers >= method_modifiers {
1884                 ty::ByValueExplicitSelfCategory
1885             } else {
1886                 match explicit_type.sty {
1887                     ty::TyRef(r, mt) => ty::ByReferenceExplicitSelfCategory(*r, mt.mutbl),
1888                     ty::TyBox(_) => ty::ByBoxExplicitSelfCategory,
1889                     _ => ty::ByValueExplicitSelfCategory,
1890                 }
1891             }
1892         }
1893     };
1894
1895     fn count_modifiers(ty: Ty) -> usize {
1896         match ty.sty {
1897             ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1898             ty::TyBox(t) => count_modifiers(t) + 1,
1899             _ => 0,
1900         }
1901     }
1902 }
1903
1904 pub fn ty_of_closure<'tcx>(
1905     this: &AstConv<'tcx>,
1906     unsafety: ast::Unsafety,
1907     decl: &ast::FnDecl,
1908     abi: abi::Abi,
1909     expected_sig: Option<ty::FnSig<'tcx>>)
1910     -> ty::ClosureTy<'tcx>
1911 {
1912     debug!("ty_of_closure(expected_sig={:?})",
1913            expected_sig);
1914
1915     // new region names that appear inside of the fn decl are bound to
1916     // that function type
1917     let rb = rscope::BindingRscope::new();
1918
1919     let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1920         let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1921             // no guarantee that the correct number of expected args
1922             // were supplied
1923             if i < e.inputs.len() {
1924                 Some(e.inputs[i])
1925             } else {
1926                 None
1927             }
1928         });
1929         ty_of_arg(this, &rb, a, expected_arg_ty)
1930     }).collect();
1931
1932     let expected_ret_ty = expected_sig.map(|e| e.output);
1933
1934     let is_infer = match decl.output {
1935         ast::Return(ref output) if output.node == ast::TyInfer => true,
1936         ast::DefaultReturn(..) => true,
1937         _ => false
1938     };
1939
1940     let output_ty = match decl.output {
1941         _ if is_infer && expected_ret_ty.is_some() =>
1942             expected_ret_ty.unwrap(),
1943         _ if is_infer =>
1944             ty::FnConverging(this.ty_infer(decl.output.span())),
1945         ast::Return(ref output) =>
1946             ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1947         ast::DefaultReturn(..) => unreachable!(),
1948         ast::NoReturn(..) => ty::FnDiverging
1949     };
1950
1951     debug!("ty_of_closure: input_tys={:?}", input_tys);
1952     debug!("ty_of_closure: output_ty={:?}", output_ty);
1953
1954     ty::ClosureTy {
1955         unsafety: unsafety,
1956         abi: abi,
1957         sig: ty::Binder(ty::FnSig {inputs: input_tys,
1958                                    output: output_ty,
1959                                    variadic: decl.variadic}),
1960     }
1961 }
1962
1963 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1964 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1965 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1966 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1967 fn conv_existential_bounds<'tcx>(
1968     this: &AstConv<'tcx>,
1969     rscope: &RegionScope,
1970     span: Span,
1971     principal_trait_ref: ty::PolyTraitRef<'tcx>,
1972     projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1973     ast_bounds: &[ast::TyParamBound])
1974     -> ty::ExistentialBounds<'tcx>
1975 {
1976     let partitioned_bounds =
1977         partition_bounds(this.tcx(), span, ast_bounds);
1978
1979     conv_existential_bounds_from_partitioned_bounds(
1980         this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
1981 }
1982
1983 fn conv_ty_poly_trait_ref<'tcx>(
1984     this: &AstConv<'tcx>,
1985     rscope: &RegionScope,
1986     span: Span,
1987     ast_bounds: &[ast::TyParamBound])
1988     -> Ty<'tcx>
1989 {
1990     let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[..]);
1991
1992     let mut projection_bounds = Vec::new();
1993     let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1994         let trait_bound = partitioned_bounds.trait_bounds.remove(0);
1995         instantiate_poly_trait_ref(this,
1996                                    rscope,
1997                                    trait_bound,
1998                                    None,
1999                                    &mut projection_bounds)
2000     } else {
2001         span_err!(this.tcx().sess, span, E0224,
2002                   "at least one non-builtin trait is required for an object type");
2003         return this.tcx().types.err;
2004     };
2005
2006     let bounds =
2007         conv_existential_bounds_from_partitioned_bounds(this,
2008                                                         rscope,
2009                                                         span,
2010                                                         main_trait_bound.clone(),
2011                                                         projection_bounds,
2012                                                         partitioned_bounds);
2013
2014     make_object_type(this, span, main_trait_bound, bounds)
2015 }
2016
2017 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
2018     this: &AstConv<'tcx>,
2019     rscope: &RegionScope,
2020     span: Span,
2021     principal_trait_ref: ty::PolyTraitRef<'tcx>,
2022     mut projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2023     partitioned_bounds: PartitionedBounds)
2024     -> ty::ExistentialBounds<'tcx>
2025 {
2026     let PartitionedBounds { builtin_bounds,
2027                             trait_bounds,
2028                             region_bounds } =
2029         partitioned_bounds;
2030
2031     if !trait_bounds.is_empty() {
2032         let b = &trait_bounds[0];
2033         span_err!(this.tcx().sess, b.trait_ref.path.span, E0225,
2034                   "only the builtin traits can be used as closure or object bounds");
2035     }
2036
2037     let region_bound =
2038         compute_object_lifetime_bound(this,
2039                                       span,
2040                                       &region_bounds,
2041                                       principal_trait_ref,
2042                                       builtin_bounds);
2043
2044     let (region_bound, will_change) = match region_bound {
2045         Some(r) => (r, false),
2046         None => {
2047             match rscope.object_lifetime_default(span) {
2048                 Some(r) => (r, rscope.object_lifetime_default_will_change_in_1_3()),
2049                 None => {
2050                     span_err!(this.tcx().sess, span, E0228,
2051                               "the lifetime bound for this object type cannot be deduced \
2052                                from context; please supply an explicit bound");
2053                     (ty::ReStatic, false)
2054                 }
2055             }
2056         }
2057     };
2058
2059     debug!("region_bound: {:?} will_change: {:?}",
2060            region_bound, will_change);
2061
2062     ty::sort_bounds_list(&mut projection_bounds);
2063
2064     ty::ExistentialBounds {
2065         region_bound: region_bound,
2066         builtin_bounds: builtin_bounds,
2067         projection_bounds: projection_bounds,
2068         region_bound_will_change: will_change,
2069     }
2070 }
2071
2072 /// Given the bounds on an object, determines what single region bound
2073 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
2074 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
2075 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
2076 fn compute_object_lifetime_bound<'tcx>(
2077     this: &AstConv<'tcx>,
2078     span: Span,
2079     explicit_region_bounds: &[&ast::Lifetime],
2080     principal_trait_ref: ty::PolyTraitRef<'tcx>,
2081     builtin_bounds: ty::BuiltinBounds)
2082     -> Option<ty::Region> // if None, use the default
2083 {
2084     let tcx = this.tcx();
2085
2086     debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2087            principal_trait_ref={:?}, builtin_bounds={:?})",
2088            explicit_region_bounds,
2089            principal_trait_ref,
2090            builtin_bounds);
2091
2092     if explicit_region_bounds.len() > 1 {
2093         span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2094             "only a single explicit lifetime bound is permitted");
2095     }
2096
2097     if !explicit_region_bounds.is_empty() {
2098         // Explicitly specified region bound. Use that.
2099         let r = explicit_region_bounds[0];
2100         return Some(ast_region_to_region(tcx, r));
2101     }
2102
2103     if let Err(ErrorReported) = this.ensure_super_predicates(span,principal_trait_ref.def_id()) {
2104         return Some(ty::ReStatic);
2105     }
2106
2107     // No explicit region bound specified. Therefore, examine trait
2108     // bounds and see if we can derive region bounds from those.
2109     let derived_region_bounds =
2110         object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2111
2112     // If there are no derived region bounds, then report back that we
2113     // can find no region bound. The caller will use the default.
2114     if derived_region_bounds.is_empty() {
2115         return None;
2116     }
2117
2118     // If any of the derived region bounds are 'static, that is always
2119     // the best choice.
2120     if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2121         return Some(ty::ReStatic);
2122     }
2123
2124     // Determine whether there is exactly one unique region in the set
2125     // of derived region bounds. If so, use that. Otherwise, report an
2126     // error.
2127     let r = derived_region_bounds[0];
2128     if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2129         span_err!(tcx.sess, span, E0227,
2130                   "ambiguous lifetime bound, explicit lifetime bound required");
2131     }
2132     return Some(r);
2133 }
2134
2135 pub struct PartitionedBounds<'a> {
2136     pub builtin_bounds: ty::BuiltinBounds,
2137     pub trait_bounds: Vec<&'a ast::PolyTraitRef>,
2138     pub region_bounds: Vec<&'a ast::Lifetime>,
2139 }
2140
2141 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2142 /// general trait bounds, and region bounds.
2143 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
2144                             _span: Span,
2145                             ast_bounds: &'a [ast::TyParamBound])
2146                             -> PartitionedBounds<'a>
2147 {
2148     let mut builtin_bounds = ty::BuiltinBounds::empty();
2149     let mut region_bounds = Vec::new();
2150     let mut trait_bounds = Vec::new();
2151     for ast_bound in ast_bounds {
2152         match *ast_bound {
2153             ast::TraitTyParamBound(ref b, ast::TraitBoundModifier::None) => {
2154                 match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
2155                     def::DefTrait(trait_did) => {
2156                         if tcx.try_add_builtin_trait(trait_did,
2157                                                      &mut builtin_bounds) {
2158                             let segments = &b.trait_ref.path.segments;
2159                             let parameters = &segments[segments.len() - 1].parameters;
2160                             if !parameters.types().is_empty() {
2161                                 check_type_argument_count(tcx, b.trait_ref.path.span,
2162                                                           parameters.types().len(), 0, 0);
2163                             }
2164                             if !parameters.lifetimes().is_empty() {
2165                                 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2166                                                              parameters.lifetimes().len(), 0);
2167                             }
2168                             continue; // success
2169                         }
2170                     }
2171                     _ => {
2172                         // Not a trait? that's an error, but it'll get
2173                         // reported later.
2174                     }
2175                 }
2176                 trait_bounds.push(b);
2177             }
2178             ast::TraitTyParamBound(_, ast::TraitBoundModifier::Maybe) => {}
2179             ast::RegionTyParamBound(ref l) => {
2180                 region_bounds.push(l);
2181             }
2182         }
2183     }
2184
2185     PartitionedBounds {
2186         builtin_bounds: builtin_bounds,
2187         trait_bounds: trait_bounds,
2188         region_bounds: region_bounds,
2189     }
2190 }
2191
2192 fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
2193                               bindings: &[ConvertedBinding<'tcx>])
2194 {
2195     for binding in bindings.iter().take(1) {
2196         span_err!(tcx.sess, binding.span, E0229,
2197             "associated type bindings are not allowed here");
2198     }
2199 }
2200
2201 fn check_type_argument_count(tcx: &ty::ctxt, span: Span, supplied: usize,
2202                              required: usize, accepted: usize) {
2203     if supplied < required {
2204         let expected = if required < accepted {
2205             "expected at least"
2206         } else {
2207             "expected"
2208         };
2209         span_err!(tcx.sess, span, E0243,
2210                   "wrong number of type arguments: {} {}, found {}",
2211                   expected, required, supplied);
2212     } else if supplied > accepted {
2213         let expected = if required < accepted {
2214             "expected at most"
2215         } else {
2216             "expected"
2217         };
2218         span_err!(tcx.sess, span, E0244,
2219                   "wrong number of type arguments: {} {}, found {}",
2220                   expected,
2221                   accepted,
2222                   supplied);
2223     }
2224 }
2225
2226 fn report_lifetime_number_error(tcx: &ty::ctxt, span: Span, number: usize, expected: usize) {
2227     span_err!(tcx.sess, span, E0107,
2228               "wrong number of lifetime parameters: expected {}, found {}",
2229               expected, number);
2230 }
2231
2232 // A helper struct for conveniently grouping a set of bounds which we pass to
2233 // and return from functions in multiple places.
2234 #[derive(PartialEq, Eq, Clone, Debug)]
2235 pub struct Bounds<'tcx> {
2236     pub region_bounds: Vec<ty::Region>,
2237     pub builtin_bounds: ty::BuiltinBounds,
2238     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2239     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2240 }
2241
2242 impl<'tcx> Bounds<'tcx> {
2243     pub fn predicates(&self,
2244         tcx: &ty::ctxt<'tcx>,
2245         param_ty: Ty<'tcx>)
2246         -> Vec<ty::Predicate<'tcx>>
2247     {
2248         let mut vec = Vec::new();
2249
2250         for builtin_bound in &self.builtin_bounds {
2251             match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
2252                 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2253                 Err(ErrorReported) => { }
2254             }
2255         }
2256
2257         for &region_bound in &self.region_bounds {
2258             // account for the binder being introduced below; no need to shift `param_ty`
2259             // because, at present at least, it can only refer to early-bound regions
2260             let region_bound = ty_fold::shift_region(region_bound, 1);
2261             vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2262         }
2263
2264         for bound_trait_ref in &self.trait_bounds {
2265             vec.push(bound_trait_ref.to_predicate());
2266         }
2267
2268         for projection in &self.projection_bounds {
2269             vec.push(projection.to_predicate());
2270         }
2271
2272         vec
2273     }
2274 }