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