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