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