]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Unignore u128 test for stage 0,1
[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`.
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()`
20 //! function triggers a recursive call to `type_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()` just looks up the item type in
24 //! `tcx.types` (using `TyCtxt::item_type`).
25
26 use rustc_const_eval::eval_length;
27 use rustc_data_structures::accumulate_vec::AccumulateVec;
28 use hir;
29 use hir::def::Def;
30 use hir::def_id::DefId;
31 use middle::resolve_lifetime as rl;
32 use rustc::lint;
33 use rustc::ty::subst::{Kind, Subst, Substs};
34 use rustc::traits;
35 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
36 use rustc::ty::wf::object_region_bounds;
37 use rustc_back::slice;
38 use require_c_abi_if_variadic;
39 use util::common::{ErrorReported, FN_OUTPUT_NAME};
40 use util::nodemap::{NodeMap, FxHashSet};
41
42 use std::cell::RefCell;
43 use std::iter;
44 use syntax::{abi, ast};
45 use syntax::feature_gate::{GateIssue, emit_feature_err};
46 use syntax::symbol::{Symbol, keywords};
47 use syntax_pos::Span;
48
49 pub trait AstConv<'gcx, 'tcx> {
50     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
51
52     /// A cache used for the result of `ast_ty_to_ty_cache`
53     fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
54
55     /// Returns the generic type and lifetime parameters for an item.
56     fn get_generics(&self, span: Span, id: DefId)
57                     -> Result<&'tcx ty::Generics<'tcx>, ErrorReported>;
58
59     /// Identify the type for an item, like a type alias, fn, or struct.
60     fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported>;
61
62     /// Returns the `TraitDef` for a given trait. This allows you to
63     /// figure out the set of type parameters defined on the trait.
64     fn get_trait_def(&self, span: Span, id: DefId)
65                      -> Result<&'tcx ty::TraitDef, ErrorReported>;
66
67     /// Ensure that the super-predicates for the trait with the given
68     /// id are available and also for the transitive set of
69     /// super-predicates.
70     fn ensure_super_predicates(&self, span: Span, id: DefId)
71                                -> Result<(), ErrorReported>;
72
73     /// Returns the set of bounds in scope for the type parameter with
74     /// the given id.
75     fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
76                                  -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
77
78     /// Return an (optional) substitution to convert bound type parameters that
79     /// are in scope into free ones. This function should only return Some
80     /// within a fn body.
81     /// See ParameterEnvironment::free_substs for more information.
82     fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
83
84     /// What lifetime should we use when a lifetime is omitted (and not elided)?
85     fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
86                 -> Option<&'tcx ty::Region>;
87
88     /// What type should we use when a type is omitted?
89     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
90
91     /// Same as ty_infer, but with a known type parameter definition.
92     fn ty_infer_for_def(&self,
93                         _def: &ty::TypeParameterDef<'tcx>,
94                         _substs: &[Kind<'tcx>],
95                         span: Span) -> Ty<'tcx> {
96         self.ty_infer(span)
97     }
98
99     /// Projecting an associated type from a (potentially)
100     /// higher-ranked trait reference is more complicated, because of
101     /// the possibility of late-bound regions appearing in the
102     /// associated type binding. This is not legal in function
103     /// signatures for that reason. In a function body, we can always
104     /// handle it because we can use inference variables to remove the
105     /// late-bound regions.
106     fn projected_ty_from_poly_trait_ref(&self,
107                                         span: Span,
108                                         poly_trait_ref: ty::PolyTraitRef<'tcx>,
109                                         item_name: ast::Name)
110                                         -> Ty<'tcx>;
111
112     /// Project an associated type from a non-higher-ranked trait reference.
113     /// This is fairly straightforward and can be accommodated in any context.
114     fn projected_ty(&self,
115                     span: Span,
116                     _trait_ref: ty::TraitRef<'tcx>,
117                     _item_name: ast::Name)
118                     -> Ty<'tcx>;
119
120     /// Invoked when we encounter an error from some prior pass
121     /// (e.g. resolve) that is translated into a ty-error. This is
122     /// used to help suppress derived errors typeck might otherwise
123     /// report.
124     fn set_tainted_by_errors(&self);
125 }
126
127 struct ConvertedBinding<'tcx> {
128     item_name: ast::Name,
129     ty: Ty<'tcx>,
130     span: Span,
131 }
132
133 /// Dummy type used for the `Self` of a `TraitRef` created for converting
134 /// a trait object, and which gets removed in `ExistentialTraitRef`.
135 /// This type must not appear anywhere in other converted types.
136 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
137
138 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
139     pub fn ast_region_to_region(&self,
140         lifetime: &hir::Lifetime,
141         def: Option<&ty::RegionParameterDef>)
142         -> &'tcx ty::Region
143     {
144         let tcx = self.tcx();
145         let r = match tcx.named_region_map.defs.get(&lifetime.id) {
146             Some(&rl::Region::Static) => {
147                 tcx.mk_region(ty::ReStatic)
148             }
149
150             Some(&rl::Region::LateBound(debruijn, id)) => {
151                 // If this region is declared on a function, it will have
152                 // an entry in `late_bound`, but if it comes from
153                 // `for<'a>` in some type or something, it won't
154                 // necessarily have one. In that case though, we won't be
155                 // changed from late to early bound, so we can just
156                 // substitute false.
157                 let issue_32330 = tcx.named_region_map
158                                      .late_bound
159                                      .get(&id)
160                                      .cloned()
161                                      .unwrap_or(ty::Issue32330::WontChange);
162                 let name = tcx.hir.name(id);
163                 tcx.mk_region(ty::ReLateBound(debruijn,
164                     ty::BrNamed(tcx.hir.local_def_id(id), name, issue_32330)))
165             }
166
167             Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
168                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
169             }
170
171             Some(&rl::Region::EarlyBound(index, id)) => {
172                 let name = tcx.hir.name(id);
173                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
174                     index: index,
175                     name: name
176                 }))
177             }
178
179             Some(&rl::Region::Free(scope, id)) => {
180                 // As in Region::LateBound above, could be missing for some late-bound
181                 // regions, but also for early-bound regions.
182                 let issue_32330 = tcx.named_region_map
183                                      .late_bound
184                                      .get(&id)
185                                      .cloned()
186                                      .unwrap_or(ty::Issue32330::WontChange);
187                 let name = tcx.hir.name(id);
188                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
189                     scope: scope.to_code_extent(&tcx.region_maps),
190                     bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name, issue_32330)
191                 }))
192
193                     // (*) -- not late-bound, won't change
194             }
195
196             None => {
197                 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
198             }
199         };
200
201         debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
202                 lifetime,
203                 r);
204
205         r
206     }
207
208     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
209     /// returns an appropriate set of substitutions for this particular reference to `I`.
210     pub fn ast_path_substs_for_ty(&self,
211         span: Span,
212         def_id: DefId,
213         item_segment: &hir::PathSegment)
214         -> &'tcx Substs<'tcx>
215     {
216         let tcx = self.tcx();
217
218         match item_segment.parameters {
219             hir::AngleBracketedParameters(_) => {}
220             hir::ParenthesizedParameters(..) => {
221                 struct_span_err!(tcx.sess, span, E0214,
222                           "parenthesized parameters may only be used with a trait")
223                     .span_label(span, &format!("only traits may use parentheses"))
224                     .emit();
225
226                 return Substs::for_item(tcx, def_id, |_, _| {
227                     tcx.mk_region(ty::ReStatic)
228                 }, |_, _| {
229                     tcx.types.err
230                 });
231             }
232         }
233
234         let (substs, assoc_bindings) =
235             self.create_substs_for_ast_path(span,
236                                             def_id,
237                                             &item_segment.parameters,
238                                             None);
239
240         assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
241
242         substs
243     }
244
245     /// Given the type/region arguments provided to some path (along with
246     /// an implicit Self, if this is a trait reference) returns the complete
247     /// set of substitutions. This may involve applying defaulted type parameters.
248     ///
249     /// Note that the type listing given here is *exactly* what the user provided.
250     fn create_substs_for_ast_path(&self,
251         span: Span,
252         def_id: DefId,
253         parameters: &hir::PathParameters,
254         self_ty: Option<Ty<'tcx>>)
255         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
256     {
257         let tcx = self.tcx();
258
259         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
260                parameters={:?})",
261                def_id, self_ty, parameters);
262
263         let (lifetimes, num_types_provided, infer_types) = match *parameters {
264             hir::AngleBracketedParameters(ref data) => {
265                 (&data.lifetimes[..], data.types.len(), data.infer_types)
266             }
267             hir::ParenthesizedParameters(_) => (&[][..], 1, false)
268         };
269
270         // If the type is parameterized by this region, then replace this
271         // region with the current anon region binding (in other words,
272         // whatever & would get replaced with).
273         let decl_generics = match self.get_generics(span, def_id) {
274             Ok(generics) => generics,
275             Err(ErrorReported) => {
276                 // No convenient way to recover from a cycle here. Just bail. Sorry!
277                 self.tcx().sess.abort_if_errors();
278                 bug!("ErrorReported returned, but no errors reports?")
279             }
280         };
281         let expected_num_region_params = decl_generics.regions.len();
282         let supplied_num_region_params = lifetimes.len();
283         if expected_num_region_params != supplied_num_region_params {
284             report_lifetime_number_error(tcx, span,
285                                          supplied_num_region_params,
286                                          expected_num_region_params);
287         }
288
289         // If a self-type was declared, one should be provided.
290         assert_eq!(decl_generics.has_self, self_ty.is_some());
291
292         // Check the number of type parameters supplied by the user.
293         let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
294         if !infer_types || num_types_provided > ty_param_defs.len() {
295             check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
296         }
297
298         let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
299         let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
300             if let Some(ref default) = p.default {
301                 if is_object && default.has_self_ty() {
302                     // There is no suitable inference default for a type parameter
303                     // that references self, in an object type.
304                     return true;
305                 }
306             }
307
308             false
309         };
310
311         let mut output_assoc_binding = None;
312         let substs = Substs::for_item(tcx, def_id, |def, _| {
313             let i = def.index as usize - self_ty.is_some() as usize;
314             if let Some(lifetime) = lifetimes.get(i) {
315                 self.ast_region_to_region(lifetime, Some(def))
316             } else {
317                 tcx.mk_region(ty::ReStatic)
318             }
319         }, |def, substs| {
320             let i = def.index as usize;
321
322             // Handle Self first, so we can adjust the index to match the AST.
323             if let (0, Some(ty)) = (i, self_ty) {
324                 return ty;
325             }
326
327             let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
328             if i < num_types_provided {
329                 // A provided type parameter.
330                 match *parameters {
331                     hir::AngleBracketedParameters(ref data) => {
332                         self.ast_ty_to_ty(&data.types[i])
333                     }
334                     hir::ParenthesizedParameters(ref data) => {
335                         assert_eq!(i, 0);
336                         let (ty, assoc) = self.convert_parenthesized_parameters(data);
337                         output_assoc_binding = Some(assoc);
338                         ty
339                     }
340                 }
341             } else if infer_types {
342                 // No type parameters were provided, we can infer all.
343                 let ty_var = if !default_needs_object_self(def) {
344                     self.ty_infer_for_def(def, substs, span)
345                 } else {
346                     self.ty_infer(span)
347                 };
348                 ty_var
349             } else if let Some(default) = def.default {
350                 // No type parameter provided, but a default exists.
351
352                 // If we are converting an object type, then the
353                 // `Self` parameter is unknown. However, some of the
354                 // other type parameters may reference `Self` in their
355                 // defaults. This will lead to an ICE if we are not
356                 // careful!
357                 if default_needs_object_self(def) {
358                     struct_span_err!(tcx.sess, span, E0393,
359                                      "the type parameter `{}` must be explicitly specified",
360                                      def.name)
361                         .span_label(span, &format!("missing reference to `{}`", def.name))
362                         .note(&format!("because of the default `Self` reference, \
363                                         type parameters must be specified on object types"))
364                         .emit();
365                     tcx.types.err
366                 } else {
367                     // This is a default type parameter.
368                     default.subst_spanned(tcx, substs, Some(span))
369                 }
370             } else {
371                 // We've already errored above about the mismatch.
372                 tcx.types.err
373             }
374         });
375
376         let assoc_bindings = match *parameters {
377             hir::AngleBracketedParameters(ref data) => {
378                 data.bindings.iter().map(|b| {
379                     ConvertedBinding {
380                         item_name: b.name,
381                         ty: self.ast_ty_to_ty(&b.ty),
382                         span: b.span
383                     }
384                 }).collect()
385             }
386             hir::ParenthesizedParameters(ref data) => {
387                 vec![output_assoc_binding.unwrap_or_else(|| {
388                     // This is an error condition, but we should
389                     // get the associated type binding anyway.
390                     self.convert_parenthesized_parameters(data).1
391                 })]
392             }
393         };
394
395         debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
396                decl_generics, self_ty, substs);
397
398         (substs, assoc_bindings)
399     }
400
401     fn convert_parenthesized_parameters(&self,
402                                         data: &hir::ParenthesizedParameterData)
403                                         -> (Ty<'tcx>, ConvertedBinding<'tcx>)
404     {
405         let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
406             self.ast_ty_to_ty(a_t)
407         }));
408
409         let (output, output_span) = match data.output {
410             Some(ref output_ty) => {
411                 (self.ast_ty_to_ty(output_ty), output_ty.span)
412             }
413             None => {
414                 (self.tcx().mk_nil(), data.span)
415             }
416         };
417
418         let output_binding = ConvertedBinding {
419             item_name: Symbol::intern(FN_OUTPUT_NAME),
420             ty: output,
421             span: output_span
422         };
423
424         (self.tcx().mk_ty(ty::TyTuple(inputs, false)), output_binding)
425     }
426
427     /// Instantiates the path for the given trait reference, assuming that it's
428     /// bound to a valid trait type. Returns the def_id for the defining trait.
429     /// Fails if the type is a type other than a trait type.
430     ///
431     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
432     /// are disallowed. Otherwise, they are pushed onto the vector given.
433     pub fn instantiate_mono_trait_ref(&self,
434         trait_ref: &hir::TraitRef,
435         self_ty: Ty<'tcx>)
436         -> ty::TraitRef<'tcx>
437     {
438         let trait_def_id = self.trait_def_id(trait_ref);
439         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
440                                         trait_def_id,
441                                         self_ty,
442                                         trait_ref.path.segments.last().unwrap())
443     }
444
445     fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
446         let path = &trait_ref.path;
447         match path.def {
448             Def::Trait(trait_def_id) => trait_def_id,
449             Def::Err => {
450                 self.tcx().sess.fatal("cannot continue compilation due to previous error");
451             }
452             _ => {
453                 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
454                             self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
455             }
456         }
457     }
458
459     pub fn instantiate_poly_trait_ref(&self,
460         ast_trait_ref: &hir::PolyTraitRef,
461         self_ty: Ty<'tcx>,
462         poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
463         -> ty::PolyTraitRef<'tcx>
464     {
465         let trait_ref = &ast_trait_ref.trait_ref;
466         let trait_def_id = self.trait_def_id(trait_ref);
467
468         debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
469
470         let (substs, assoc_bindings) =
471             self.create_substs_for_ast_trait_ref(trait_ref.path.span,
472                                                  trait_def_id,
473                                                  self_ty,
474                                                  trait_ref.path.segments.last().unwrap());
475         let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
476
477         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
478             // specify type to assert that error was already reported in Err case:
479             let predicate: Result<_, ErrorReported> =
480                 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
481                                                                    poly_trait_ref,
482                                                                    binding);
483             predicate.ok() // ok to ignore Err() because ErrorReported (see above)
484         }));
485
486         debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
487                trait_ref, poly_projections, poly_trait_ref);
488         poly_trait_ref
489     }
490
491     fn ast_path_to_mono_trait_ref(&self,
492                                   span: Span,
493                                   trait_def_id: DefId,
494                                   self_ty: Ty<'tcx>,
495                                   trait_segment: &hir::PathSegment)
496                                   -> ty::TraitRef<'tcx>
497     {
498         let (substs, assoc_bindings) =
499             self.create_substs_for_ast_trait_ref(span,
500                                                  trait_def_id,
501                                                  self_ty,
502                                                  trait_segment);
503         assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
504         ty::TraitRef::new(trait_def_id, substs)
505     }
506
507     fn create_substs_for_ast_trait_ref(&self,
508                                        span: Span,
509                                        trait_def_id: DefId,
510                                        self_ty: Ty<'tcx>,
511                                        trait_segment: &hir::PathSegment)
512                                        -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
513     {
514         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
515                trait_segment);
516
517         let trait_def = match self.get_trait_def(span, trait_def_id) {
518             Ok(trait_def) => trait_def,
519             Err(ErrorReported) => {
520                 // No convenient way to recover from a cycle here. Just bail. Sorry!
521                 self.tcx().sess.abort_if_errors();
522                 bug!("ErrorReported returned, but no errors reports?")
523             }
524         };
525
526         match trait_segment.parameters {
527             hir::AngleBracketedParameters(_) => {
528                 // For now, require that parenthetical notation be used
529                 // only with `Fn()` etc.
530                 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
531                     emit_feature_err(&self.tcx().sess.parse_sess,
532                                      "unboxed_closures", span, GateIssue::Language,
533                                      "\
534                         the precise format of `Fn`-family traits' \
535                         type parameters is subject to change. \
536                         Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
537                 }
538             }
539             hir::ParenthesizedParameters(_) => {
540                 // For now, require that parenthetical notation be used
541                 // only with `Fn()` etc.
542                 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
543                     emit_feature_err(&self.tcx().sess.parse_sess,
544                                      "unboxed_closures", span, GateIssue::Language,
545                                      "\
546                         parenthetical notation is only stable when used with `Fn`-family traits");
547                 }
548             }
549         }
550
551         self.create_substs_for_ast_path(span,
552                                         trait_def_id,
553                                         &trait_segment.parameters,
554                                         Some(self_ty))
555     }
556
557     fn trait_defines_associated_type_named(&self,
558                                            trait_def_id: DefId,
559                                            assoc_name: ast::Name)
560                                            -> bool
561     {
562         self.tcx().associated_items(trait_def_id).any(|item| {
563             item.kind == ty::AssociatedKind::Type && item.name == assoc_name
564         })
565     }
566
567     fn ast_type_binding_to_poly_projection_predicate(
568         &self,
569         path_id: ast::NodeId,
570         trait_ref: ty::PolyTraitRef<'tcx>,
571         binding: &ConvertedBinding<'tcx>)
572         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
573     {
574         let tcx = self.tcx();
575
576         // Given something like `U : SomeTrait<T=X>`, we want to produce a
577         // predicate like `<U as SomeTrait>::T = X`. This is somewhat
578         // subtle in the event that `T` is defined in a supertrait of
579         // `SomeTrait`, because in that case we need to upcast.
580         //
581         // That is, consider this case:
582         //
583         // ```
584         // trait SubTrait : SuperTrait<int> { }
585         // trait SuperTrait<A> { type T; }
586         //
587         // ... B : SubTrait<T=foo> ...
588         // ```
589         //
590         // We want to produce `<B as SuperTrait<int>>::T == foo`.
591
592         // Find any late-bound regions declared in `ty` that are not
593         // declared in the trait-ref. These are not wellformed.
594         //
595         // Example:
596         //
597         //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
598         //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
599         let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
600         let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
601         debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
602         debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
603         for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
604             let br_name = match *br {
605                 ty::BrNamed(_, name, _) => name,
606                 _ => {
607                     span_bug!(
608                         binding.span,
609                         "anonymous bound region {:?} in binding but not trait ref",
610                         br);
611                 }
612             };
613             tcx.sess.add_lint(
614                 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
615                 path_id,
616                 binding.span,
617                 format!("binding for associated type `{}` references lifetime `{}`, \
618                          which does not appear in the trait input types",
619                         binding.item_name, br_name));
620         }
621
622         // Simple case: X is defined in the current trait.
623         if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
624             return Ok(trait_ref.map_bound(|trait_ref| {
625                 ty::ProjectionPredicate {
626                     projection_ty: ty::ProjectionTy {
627                         trait_ref: trait_ref,
628                         item_name: binding.item_name,
629                     },
630                     ty: binding.ty,
631                 }
632             }));
633         }
634
635         // Otherwise, we have to walk through the supertraits to find
636         // those that do.
637         self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
638
639         let candidates =
640             traits::supertraits(tcx, trait_ref.clone())
641             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
642
643         let candidate = self.one_bound_for_assoc_type(candidates,
644                                                       &trait_ref.to_string(),
645                                                       &binding.item_name.as_str(),
646                                                       binding.span)?;
647
648         Ok(candidate.map_bound(|trait_ref| {
649             ty::ProjectionPredicate {
650                 projection_ty: ty::ProjectionTy {
651                     trait_ref: trait_ref,
652                     item_name: binding.item_name,
653                 },
654                 ty: binding.ty,
655             }
656         }))
657     }
658
659     fn ast_path_to_ty(&self,
660         span: Span,
661         did: DefId,
662         item_segment: &hir::PathSegment)
663         -> Ty<'tcx>
664     {
665         let tcx = self.tcx();
666         let decl_ty = match self.get_item_type(span, did) {
667             Ok(ty) => ty,
668             Err(ErrorReported) => {
669                 return tcx.types.err;
670             }
671         };
672
673         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
674         decl_ty.subst(self.tcx(), substs)
675     }
676
677     /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
678     /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
679     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
680                                 -> ty::ExistentialTraitRef<'tcx> {
681         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
682         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
683     }
684
685     fn conv_object_ty_poly_trait_ref(&self,
686         span: Span,
687         trait_bounds: &[hir::PolyTraitRef],
688         lifetime: &hir::Lifetime)
689         -> Ty<'tcx>
690     {
691         let tcx = self.tcx();
692
693         if trait_bounds.is_empty() {
694             span_err!(tcx.sess, span, E0224,
695                       "at least one non-builtin trait is required for an object type");
696             return tcx.types.err;
697         }
698
699         let mut projection_bounds = vec![];
700         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
701         let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
702                                                         dummy_self,
703                                                         &mut projection_bounds);
704
705         let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
706
707         if !trait_bounds.is_empty() {
708             let b = &trait_bounds[0];
709             let span = b.trait_ref.path.span;
710             struct_span_err!(self.tcx().sess, span, E0225,
711                 "only Send/Sync traits can be used as additional traits in a trait object")
712                 .span_label(span, &format!("non-Send/Sync additional trait"))
713                 .emit();
714         }
715
716         // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
717         let existential_principal = principal.map_bound(|trait_ref| {
718             self.trait_ref_to_existential(trait_ref)
719         });
720         let existential_projections = projection_bounds.iter().map(|bound| {
721             bound.map_bound(|b| {
722                 let p = b.projection_ty;
723                 ty::ExistentialProjection {
724                     trait_ref: self.trait_ref_to_existential(p.trait_ref),
725                     item_name: p.item_name,
726                     ty: b.ty
727                 }
728             })
729         });
730
731         // ensure the super predicates and stop if we encountered an error
732         if self.ensure_super_predicates(span, principal.def_id()).is_err() {
733             return tcx.types.err;
734         }
735
736         // check that there are no gross object safety violations,
737         // most importantly, that the supertraits don't contain Self,
738         // to avoid ICE-s.
739         let object_safety_violations =
740             tcx.astconv_object_safety_violations(principal.def_id());
741         if !object_safety_violations.is_empty() {
742             tcx.report_object_safety_error(
743                 span, principal.def_id(), object_safety_violations)
744                 .emit();
745             return tcx.types.err;
746         }
747
748         let mut associated_types = FxHashSet::default();
749         for tr in traits::supertraits(tcx, principal) {
750             associated_types.extend(tcx.associated_items(tr.def_id())
751                 .filter(|item| item.kind == ty::AssociatedKind::Type)
752                 .map(|item| (tr.def_id(), item.name)));
753         }
754
755         for projection_bound in &projection_bounds {
756             let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
757                         projection_bound.0.projection_ty.item_name);
758             associated_types.remove(&pair);
759         }
760
761         for (trait_def_id, name) in associated_types {
762             struct_span_err!(tcx.sess, span, E0191,
763                 "the value of the associated type `{}` (from the trait `{}`) must be specified",
764                         name,
765                         tcx.item_path_str(trait_def_id))
766                         .span_label(span, &format!(
767                             "missing associated type `{}` value", name))
768                         .emit();
769         }
770
771         let mut v =
772             iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
773             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
774             .chain(existential_projections
775                    .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
776             .collect::<AccumulateVec<[_; 8]>>();
777         v.sort_by(|a, b| a.cmp(tcx, b));
778         let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
779
780
781         // Explicitly specified region bound. Use that.
782         let region_bound = if !lifetime.is_elided() {
783             self.ast_region_to_region(lifetime, None)
784         } else {
785             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
786                 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
787                     self.ast_region_to_region(lifetime, None)
788                 } else {
789                     self.re_infer(span, None).unwrap_or_else(|| {
790                         span_err!(tcx.sess, span, E0228,
791                                   "the lifetime bound for this object type cannot be deduced \
792                                    from context; please supply an explicit bound");
793                         tcx.mk_region(ty::ReStatic)
794                     })
795                 }
796             })
797         };
798
799         debug!("region_bound: {:?}", region_bound);
800
801         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
802         debug!("trait_object_type: {:?}", ty);
803         ty
804     }
805
806     fn report_ambiguous_associated_type(&self,
807                                         span: Span,
808                                         type_str: &str,
809                                         trait_str: &str,
810                                         name: &str) {
811         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
812             .span_label(span, &format!("ambiguous associated type"))
813             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
814                   type_str, trait_str, name))
815             .emit();
816
817     }
818
819     // Search for a bound on a type parameter which includes the associated item
820     // given by assoc_name. ty_param_node_id is the node id for the type parameter
821     // (which might be `Self`, but only if it is the `Self` of a trait, not an
822     // impl). This function will fail if there are no suitable bounds or there is
823     // any ambiguity.
824     fn find_bound_for_assoc_item(&self,
825                                  ty_param_node_id: ast::NodeId,
826                                  ty_param_name: ast::Name,
827                                  assoc_name: ast::Name,
828                                  span: Span)
829                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
830     {
831         let tcx = self.tcx();
832
833         let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
834             Ok(v) => v,
835             Err(ErrorReported) => {
836                 return Err(ErrorReported);
837             }
838         };
839
840         // Ensure the super predicates and stop if we encountered an error.
841         if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
842             return Err(ErrorReported);
843         }
844
845         // Check that there is exactly one way to find an associated type with the
846         // correct name.
847         let suitable_bounds =
848             traits::transitive_bounds(tcx, &bounds)
849             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
850
851         self.one_bound_for_assoc_type(suitable_bounds,
852                                       &ty_param_name.as_str(),
853                                       &assoc_name.as_str(),
854                                       span)
855     }
856
857
858     // Checks that bounds contains exactly one element and reports appropriate
859     // errors otherwise.
860     fn one_bound_for_assoc_type<I>(&self,
861                                 mut bounds: I,
862                                 ty_param_name: &str,
863                                 assoc_name: &str,
864                                 span: Span)
865         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
866         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
867     {
868         let bound = match bounds.next() {
869             Some(bound) => bound,
870             None => {
871                 struct_span_err!(self.tcx().sess, span, E0220,
872                           "associated type `{}` not found for `{}`",
873                           assoc_name,
874                           ty_param_name)
875                   .span_label(span, &format!("associated type `{}` not found", assoc_name))
876                   .emit();
877                 return Err(ErrorReported);
878             }
879         };
880
881         if let Some(bound2) = bounds.next() {
882             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
883             let mut err = struct_span_err!(
884                 self.tcx().sess, span, E0221,
885                 "ambiguous associated type `{}` in bounds of `{}`",
886                 assoc_name,
887                 ty_param_name);
888             err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
889
890             for bound in bounds {
891                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
892                     item.kind == ty::AssociatedKind::Type && item.name == assoc_name
893                 })
894                 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
895
896                 if let Some(span) = bound_span {
897                     err.span_label(span, &format!("ambiguous `{}` from `{}`",
898                                                   assoc_name,
899                                                   bound));
900                 } else {
901                     span_note!(&mut err, span,
902                                "associated type `{}` could derive from `{}`",
903                                ty_param_name,
904                                bound);
905                 }
906             }
907             err.emit();
908         }
909
910         return Ok(bound);
911     }
912
913     // Create a type from a path to an associated type.
914     // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
915     // and item_segment is the path segment for D. We return a type and a def for
916     // the whole path.
917     // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
918     // parameter or Self.
919     pub fn associated_path_def_to_ty(&self,
920                                      ref_id: ast::NodeId,
921                                      span: Span,
922                                      ty: Ty<'tcx>,
923                                      ty_path_def: Def,
924                                      item_segment: &hir::PathSegment)
925                                      -> (Ty<'tcx>, Def)
926     {
927         let tcx = self.tcx();
928         let assoc_name = item_segment.name;
929
930         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
931
932         tcx.prohibit_type_params(slice::ref_slice(item_segment));
933
934         // Find the type of the associated item, and the trait where the associated
935         // item is declared.
936         let bound = match (&ty.sty, ty_path_def) {
937             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
938                 // `Self` in an impl of a trait - we have a concrete self type and a
939                 // trait reference.
940                 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
941                 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
942                     trait_ref.subst(tcx, free_substs)
943                 } else {
944                     trait_ref
945                 };
946
947                 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
948                     return (tcx.types.err, Def::Err);
949                 }
950
951                 let candidates =
952                     traits::supertraits(tcx, ty::Binder(trait_ref))
953                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
954                                                                          assoc_name));
955
956                 match self.one_bound_for_assoc_type(candidates,
957                                                     "Self",
958                                                     &assoc_name.as_str(),
959                                                     span) {
960                     Ok(bound) => bound,
961                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
962                 }
963             }
964             (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
965                 let trait_node_id = tcx.hir.as_local_node_id(trait_did).unwrap();
966                 match self.find_bound_for_assoc_item(trait_node_id,
967                                                      keywords::SelfType.name(),
968                                                      assoc_name,
969                                                      span) {
970                     Ok(bound) => bound,
971                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
972                 }
973             }
974             (&ty::TyParam(_), Def::TyParam(param_did)) => {
975                 let param_node_id = tcx.hir.as_local_node_id(param_did).unwrap();
976                 let param_name = tcx.type_parameter_def(param_node_id).name;
977                 match self.find_bound_for_assoc_item(param_node_id,
978                                                      param_name,
979                                                      assoc_name,
980                                                      span) {
981                     Ok(bound) => bound,
982                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
983                 }
984             }
985             _ => {
986                 // Don't print TyErr to the user.
987                 if !ty.references_error() {
988                     self.report_ambiguous_associated_type(span,
989                                                           &ty.to_string(),
990                                                           "Trait",
991                                                           &assoc_name.as_str());
992                 }
993                 return (tcx.types.err, Def::Err);
994             }
995         };
996
997         let trait_did = bound.0.def_id;
998         let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
999
1000         let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
1001         let def_id = item.expect("missing associated type").def_id;
1002         tcx.check_stability(def_id, ref_id, span);
1003         (ty, Def::AssociatedTy(def_id))
1004     }
1005
1006     fn qpath_to_ty(&self,
1007                    span: Span,
1008                    opt_self_ty: Option<Ty<'tcx>>,
1009                    trait_def_id: DefId,
1010                    trait_segment: &hir::PathSegment,
1011                    item_segment: &hir::PathSegment)
1012                    -> Ty<'tcx>
1013     {
1014         let tcx = self.tcx();
1015
1016         tcx.prohibit_type_params(slice::ref_slice(item_segment));
1017
1018         let self_ty = if let Some(ty) = opt_self_ty {
1019             ty
1020         } else {
1021             let path_str = tcx.item_path_str(trait_def_id);
1022             self.report_ambiguous_associated_type(span,
1023                                                   "Type",
1024                                                   &path_str,
1025                                                   &item_segment.name.as_str());
1026             return tcx.types.err;
1027         };
1028
1029         debug!("qpath_to_ty: self_type={:?}", self_ty);
1030
1031         let trait_ref = self.ast_path_to_mono_trait_ref(span,
1032                                                         trait_def_id,
1033                                                         self_ty,
1034                                                         trait_segment);
1035
1036         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1037
1038         self.projected_ty(span, trait_ref, item_segment.name)
1039     }
1040
1041     // Check a type Path and convert it to a Ty.
1042     pub fn def_to_ty(&self,
1043                      opt_self_ty: Option<Ty<'tcx>>,
1044                      path: &hir::Path,
1045                      permit_variants: bool)
1046                      -> Ty<'tcx> {
1047         let tcx = self.tcx();
1048
1049         debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1050                path.def, opt_self_ty, path.segments);
1051
1052         let span = path.span;
1053         match path.def {
1054             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1055                 assert_eq!(opt_self_ty, None);
1056                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1057                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1058             }
1059             Def::Variant(did) if permit_variants => {
1060                 // Convert "variant type" as if it were a real type.
1061                 // The resulting `Ty` is type of the variant's enum for now.
1062                 assert_eq!(opt_self_ty, None);
1063                 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1064                 self.ast_path_to_ty(span,
1065                                     tcx.parent_def_id(did).unwrap(),
1066                                     path.segments.last().unwrap())
1067             }
1068             Def::TyParam(did) => {
1069                 assert_eq!(opt_self_ty, None);
1070                 tcx.prohibit_type_params(&path.segments);
1071
1072                 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1073                 let param = tcx.ty_param_defs.borrow().get(&node_id)
1074                                .map(ty::ParamTy::for_def);
1075                 if let Some(p) = param {
1076                     p.to_ty(tcx)
1077                 } else {
1078                     // Only while computing defaults of earlier type
1079                     // parameters can a type parameter be missing its def.
1080                     struct_span_err!(tcx.sess, span, E0128,
1081                                      "type parameters with a default cannot use \
1082                                       forward declared identifiers")
1083                         .span_label(span, &format!("defaulted type parameters \
1084                                                     cannot be forward declared"))
1085                         .emit();
1086                     tcx.types.err
1087                 }
1088             }
1089             Def::SelfTy(_, Some(def_id)) => {
1090                 // Self in impl (we know the concrete type).
1091
1092                 assert_eq!(opt_self_ty, None);
1093                 tcx.prohibit_type_params(&path.segments);
1094
1095                 // FIXME: Self type is not always computed when we are here because type parameter
1096                 // bounds may affect Self type and have to be converted before it.
1097                 let ty = if def_id.is_local() {
1098                     tcx.item_types.borrow().get(&def_id).cloned()
1099                 } else {
1100                     Some(tcx.item_type(def_id))
1101                 };
1102                 if let Some(ty) = ty {
1103                     if let Some(free_substs) = self.get_free_substs() {
1104                         ty.subst(tcx, free_substs)
1105                     } else {
1106                         ty
1107                     }
1108                 } else {
1109                     tcx.sess.span_err(span, "`Self` type is used before it's determined");
1110                     tcx.types.err
1111                 }
1112             }
1113             Def::SelfTy(Some(_), None) => {
1114                 // Self in trait.
1115                 assert_eq!(opt_self_ty, None);
1116                 tcx.prohibit_type_params(&path.segments);
1117                 tcx.mk_self_type()
1118             }
1119             Def::AssociatedTy(def_id) => {
1120                 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1121                 let trait_did = tcx.parent_def_id(def_id).unwrap();
1122                 self.qpath_to_ty(span,
1123                                  opt_self_ty,
1124                                  trait_did,
1125                                  &path.segments[path.segments.len()-2],
1126                                  path.segments.last().unwrap())
1127             }
1128             Def::PrimTy(prim_ty) => {
1129                 assert_eq!(opt_self_ty, None);
1130                 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1131             }
1132             Def::Err => {
1133                 self.set_tainted_by_errors();
1134                 return self.tcx().types.err;
1135             }
1136             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1137         }
1138     }
1139
1140     /// Parses the programmer's textual representation of a type into our
1141     /// internal notion of a type.
1142     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1143         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1144                ast_ty.id, ast_ty);
1145
1146         let tcx = self.tcx();
1147
1148         let cache = self.ast_ty_to_ty_cache();
1149         if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1150             return ty;
1151         }
1152
1153         let result_ty = match ast_ty.node {
1154             hir::TySlice(ref ty) => {
1155                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1156             }
1157             hir::TyPtr(ref mt) => {
1158                 tcx.mk_ptr(ty::TypeAndMut {
1159                     ty: self.ast_ty_to_ty(&mt.ty),
1160                     mutbl: mt.mutbl
1161                 })
1162             }
1163             hir::TyRptr(ref region, ref mt) => {
1164                 let r = self.ast_region_to_region(region, None);
1165                 debug!("TyRef r={:?}", r);
1166                 let t = self.ast_ty_to_ty(&mt.ty);
1167                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1168             }
1169             hir::TyNever => {
1170                 tcx.types.never
1171             },
1172             hir::TyTup(ref fields) => {
1173                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1174             }
1175             hir::TyBareFn(ref bf) => {
1176                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1177                 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1178
1179                 // Find any late-bound regions declared in return type that do
1180                 // not appear in the arguments. These are not wellformed.
1181                 //
1182                 // Example:
1183                 //
1184                 //     for<'a> fn() -> &'a str <-- 'a is bad
1185                 //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1186                 //
1187                 // Note that we do this check **here** and not in
1188                 // `ty_of_bare_fn` because the latter is also used to make
1189                 // the types for fn items, and we do not want to issue a
1190                 // warning then. (Once we fix #32330, the regions we are
1191                 // checking for here would be considered early bound
1192                 // anyway.)
1193                 let inputs = bare_fn_ty.sig.inputs();
1194                 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1195                     &inputs.map_bound(|i| i.to_owned()));
1196                 let output = bare_fn_ty.sig.output();
1197                 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1198                 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1199                     let br_name = match *br {
1200                         ty::BrNamed(_, name, _) => name,
1201                         _ => {
1202                             span_bug!(
1203                                 bf.decl.output.span(),
1204                                 "anonymous bound region {:?} in return but not args",
1205                                 br);
1206                         }
1207                     };
1208                     tcx.sess.add_lint(
1209                         lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1210                         ast_ty.id,
1211                         ast_ty.span,
1212                         format!("return type references lifetime `{}`, \
1213                                  which does not appear in the trait input types",
1214                                 br_name));
1215                 }
1216                 tcx.mk_fn_ptr(bare_fn_ty)
1217             }
1218             hir::TyTraitObject(ref bounds, ref lifetime) => {
1219                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1220             }
1221             hir::TyImplTrait(ref bounds) => {
1222                 use collect::{compute_bounds, SizedByDefault};
1223
1224                 // Figure out if we can allow an `impl Trait` here, by walking up
1225                 // to a `fn` or inherent `impl` method, going only through `Ty`
1226                 // or `TraitRef` nodes (as nothing else should be in types) and
1227                 // ensuring that we reach the `fn`/method signature's return type.
1228                 let mut node_id = ast_ty.id;
1229                 let fn_decl = loop {
1230                     let parent = tcx.hir.get_parent_node(node_id);
1231                     match tcx.hir.get(parent) {
1232                         hir::map::NodeItem(&hir::Item {
1233                             node: hir::ItemFn(ref fn_decl, ..), ..
1234                         }) => break Some(fn_decl),
1235
1236                         hir::map::NodeImplItem(&hir::ImplItem {
1237                             node: hir::ImplItemKind::Method(ref sig, _), ..
1238                         }) => {
1239                             match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1240                                 hir::ItemImpl(.., None, _, _) => {
1241                                     break Some(&sig.decl)
1242                                 }
1243                                 _ => break None
1244                             }
1245                         }
1246
1247                         hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1248
1249                         _ => break None
1250                     }
1251                     node_id = parent;
1252                 };
1253                 let allow = fn_decl.map_or(false, |fd| {
1254                     match fd.output {
1255                         hir::DefaultReturn(_) => false,
1256                         hir::Return(ref ty) => ty.id == node_id
1257                     }
1258                 });
1259
1260                 // Create the anonymized type.
1261                 if allow {
1262                     let def_id = tcx.hir.local_def_id(ast_ty.id);
1263                     if let Err(ErrorReported) = self.get_generics(ast_ty.span, def_id) {
1264                         return tcx.types.err;
1265                     }
1266                     let substs = Substs::identity_for_item(tcx, def_id);
1267                     let ty = tcx.mk_anon(tcx.hir.local_def_id(ast_ty.id), substs);
1268
1269                     // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1270                     let bounds = compute_bounds(self, ty, bounds,
1271                                                 SizedByDefault::Yes,
1272                                                 ast_ty.span);
1273                     let predicates = bounds.predicates(tcx, ty);
1274                     let predicates = tcx.lift_to_global(&predicates).unwrap();
1275                     tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1276                         parent: None,
1277                         predicates: predicates
1278                     });
1279
1280                     ty
1281                 } else {
1282                     span_err!(tcx.sess, ast_ty.span, E0562,
1283                               "`impl Trait` not allowed outside of function \
1284                                and inherent method return types");
1285                     tcx.types.err
1286                 }
1287             }
1288             hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1289                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1290                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1291                     self.ast_ty_to_ty(qself)
1292                 });
1293                 self.def_to_ty(opt_self_ty, path, false)
1294             }
1295             hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1296                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1297                 let ty = self.ast_ty_to_ty(qself);
1298
1299                 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1300                     path.def
1301                 } else {
1302                     Def::Err
1303                 };
1304                 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1305             }
1306             hir::TyArray(ref ty, length) => {
1307                 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1308                     tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1309                 } else {
1310                     self.tcx().types.err
1311                 }
1312             }
1313             hir::TyTypeof(ref _e) => {
1314                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1315                                  "`typeof` is a reserved keyword but unimplemented")
1316                     .span_label(ast_ty.span, &format!("reserved keyword"))
1317                     .emit();
1318
1319                 tcx.types.err
1320             }
1321             hir::TyInfer => {
1322                 // TyInfer also appears as the type of arguments or return
1323                 // values in a ExprClosure, or as
1324                 // the type of local variables. Both of these cases are
1325                 // handled specially and will not descend into this routine.
1326                 self.ty_infer(ast_ty.span)
1327             }
1328         };
1329
1330         cache.borrow_mut().insert(ast_ty.id, result_ty);
1331
1332         result_ty
1333     }
1334
1335     pub fn ty_of_arg(&self,
1336                      ty: &hir::Ty,
1337                      expected_ty: Option<Ty<'tcx>>)
1338                      -> Ty<'tcx>
1339     {
1340         match ty.node {
1341             hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1342             hir::TyInfer => self.ty_infer(ty.span),
1343             _ => self.ast_ty_to_ty(ty),
1344         }
1345     }
1346
1347     pub fn ty_of_fn(&self,
1348                     unsafety: hir::Unsafety,
1349                     abi: abi::Abi,
1350                     decl: &hir::FnDecl)
1351                     -> &'tcx ty::BareFnTy<'tcx> {
1352         debug!("ty_of_fn");
1353
1354         let input_tys: Vec<Ty> =
1355             decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1356
1357         let output_ty = match decl.output {
1358             hir::Return(ref output) => self.ast_ty_to_ty(output),
1359             hir::DefaultReturn(..) => self.tcx().mk_nil(),
1360         };
1361
1362         debug!("ty_of_fn: output_ty={:?}", output_ty);
1363
1364         self.tcx().mk_bare_fn(ty::BareFnTy {
1365             unsafety: unsafety,
1366             abi: abi,
1367             sig: ty::Binder(self.tcx().mk_fn_sig(
1368                 input_tys.into_iter(),
1369                 output_ty,
1370                 decl.variadic
1371             )),
1372         })
1373     }
1374
1375     pub fn ty_of_closure(&self,
1376         unsafety: hir::Unsafety,
1377         decl: &hir::FnDecl,
1378         abi: abi::Abi,
1379         expected_sig: Option<ty::FnSig<'tcx>>)
1380         -> ty::ClosureTy<'tcx>
1381     {
1382         debug!("ty_of_closure(expected_sig={:?})",
1383                expected_sig);
1384
1385         let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1386             let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1387                 // no guarantee that the correct number of expected args
1388                 // were supplied
1389                 if i < e.inputs().len() {
1390                     Some(e.inputs()[i])
1391                 } else {
1392                     None
1393                 }
1394             });
1395             self.ty_of_arg(a, expected_arg_ty)
1396         });
1397
1398         let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1399
1400         let is_infer = match decl.output {
1401             hir::Return(ref output) if output.node == hir::TyInfer => true,
1402             hir::DefaultReturn(..) => true,
1403             _ => false
1404         };
1405
1406         let output_ty = match decl.output {
1407             _ if is_infer && expected_ret_ty.is_some() =>
1408                 expected_ret_ty.unwrap(),
1409             _ if is_infer => self.ty_infer(decl.output.span()),
1410             hir::Return(ref output) =>
1411                 self.ast_ty_to_ty(&output),
1412             hir::DefaultReturn(..) => bug!(),
1413         };
1414
1415         debug!("ty_of_closure: output_ty={:?}", output_ty);
1416
1417         ty::ClosureTy {
1418             unsafety: unsafety,
1419             abi: abi,
1420             sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1421         }
1422     }
1423
1424     /// Given the bounds on an object, determines what single region bound (if any) we can
1425     /// use to summarize this type. The basic idea is that we will use the bound the user
1426     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1427     /// for region bounds. It may be that we can derive no bound at all, in which case
1428     /// we return `None`.
1429     fn compute_object_lifetime_bound(&self,
1430         span: Span,
1431         existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1432         -> Option<&'tcx ty::Region> // if None, use the default
1433     {
1434         let tcx = self.tcx();
1435
1436         debug!("compute_opt_region_bound(existential_predicates={:?})",
1437                existential_predicates);
1438
1439         if let Some(principal) = existential_predicates.principal() {
1440             if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1441                 return Some(tcx.mk_region(ty::ReStatic));
1442             }
1443         }
1444
1445         // No explicit region bound specified. Therefore, examine trait
1446         // bounds and see if we can derive region bounds from those.
1447         let derived_region_bounds =
1448             object_region_bounds(tcx, existential_predicates);
1449
1450         // If there are no derived region bounds, then report back that we
1451         // can find no region bound. The caller will use the default.
1452         if derived_region_bounds.is_empty() {
1453             return None;
1454         }
1455
1456         // If any of the derived region bounds are 'static, that is always
1457         // the best choice.
1458         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1459             return Some(tcx.mk_region(ty::ReStatic));
1460         }
1461
1462         // Determine whether there is exactly one unique region in the set
1463         // of derived region bounds. If so, use that. Otherwise, report an
1464         // error.
1465         let r = derived_region_bounds[0];
1466         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1467             span_err!(tcx.sess, span, E0227,
1468                       "ambiguous lifetime bound, explicit lifetime bound required");
1469         }
1470         return Some(r);
1471     }
1472 }
1473
1474 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1475 /// remaining general trait bounds.
1476 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1477                                          trait_bounds: &'b [hir::PolyTraitRef])
1478     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1479 {
1480     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1481         match bound.trait_ref.path.def {
1482             Def::Trait(trait_did) => {
1483                 // Checks whether `trait_did` refers to one of the builtin
1484                 // traits, like `Send`, and adds it to `auto_traits` if so.
1485                 if Some(trait_did) == tcx.lang_items.send_trait() ||
1486                     Some(trait_did) == tcx.lang_items.sync_trait() {
1487                     let segments = &bound.trait_ref.path.segments;
1488                     let parameters = &segments[segments.len() - 1].parameters;
1489                     if !parameters.types().is_empty() {
1490                         check_type_argument_count(tcx, bound.trait_ref.path.span,
1491                                                   parameters.types().len(), &[]);
1492                     }
1493                     if !parameters.lifetimes().is_empty() {
1494                         report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1495                                                      parameters.lifetimes().len(), 0);
1496                     }
1497                     true
1498                 } else {
1499                     false
1500                 }
1501             }
1502             _ => false
1503         }
1504     });
1505
1506     let auto_traits = auto_traits.into_iter().map(|tr| {
1507         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1508             trait_did
1509         } else {
1510             unreachable!()
1511         }
1512     }).collect::<Vec<_>>();
1513
1514     (auto_traits, trait_bounds)
1515 }
1516
1517 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1518                              ty_param_defs: &[ty::TypeParameterDef]) {
1519     let accepted = ty_param_defs.len();
1520     let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
1521     if supplied < required {
1522         let expected = if required < accepted {
1523             "expected at least"
1524         } else {
1525             "expected"
1526         };
1527         let arguments_plural = if required == 1 { "" } else { "s" };
1528
1529         struct_span_err!(tcx.sess, span, E0243,
1530                 "wrong number of type arguments: {} {}, found {}",
1531                 expected, required, supplied)
1532             .span_label(span,
1533                 &format!("{} {} type argument{}",
1534                     expected,
1535                     required,
1536                     arguments_plural))
1537             .emit();
1538     } else if supplied > accepted {
1539         let expected = if required < accepted {
1540             format!("expected at most {}", accepted)
1541         } else {
1542             format!("expected {}", accepted)
1543         };
1544         let arguments_plural = if accepted == 1 { "" } else { "s" };
1545
1546         struct_span_err!(tcx.sess, span, E0244,
1547                 "wrong number of type arguments: {}, found {}",
1548                 expected, supplied)
1549             .span_label(
1550                 span,
1551                 &format!("{} type argument{}",
1552                     if accepted == 0 { "expected no" } else { &expected },
1553                     arguments_plural)
1554             )
1555             .emit();
1556     }
1557 }
1558
1559 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1560     let label = if number < expected {
1561         if expected == 1 {
1562             format!("expected {} lifetime parameter", expected)
1563         } else {
1564             format!("expected {} lifetime parameters", expected)
1565         }
1566     } else {
1567         let additional = number - expected;
1568         if additional == 1 {
1569             "unexpected lifetime parameter".to_string()
1570         } else {
1571             format!("{} unexpected lifetime parameters", additional)
1572         }
1573     };
1574     struct_span_err!(tcx.sess, span, E0107,
1575                      "wrong number of lifetime parameters: expected {}, found {}",
1576                      expected, number)
1577         .span_label(span, &label)
1578         .emit();
1579 }
1580
1581 // A helper struct for conveniently grouping a set of bounds which we pass to
1582 // and return from functions in multiple places.
1583 #[derive(PartialEq, Eq, Clone, Debug)]
1584 pub struct Bounds<'tcx> {
1585     pub region_bounds: Vec<&'tcx ty::Region>,
1586     pub implicitly_sized: bool,
1587     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1588     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1589 }
1590
1591 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1592     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1593                       -> Vec<ty::Predicate<'tcx>>
1594     {
1595         let mut vec = Vec::new();
1596
1597         // If it could be sized, and is, add the sized predicate
1598         if self.implicitly_sized {
1599             if let Some(sized) = tcx.lang_items.sized_trait() {
1600                 let trait_ref = ty::TraitRef {
1601                     def_id: sized,
1602                     substs: tcx.mk_substs_trait(param_ty, &[])
1603                 };
1604                 vec.push(trait_ref.to_predicate());
1605             }
1606         }
1607
1608         for &region_bound in &self.region_bounds {
1609             // account for the binder being introduced below; no need to shift `param_ty`
1610             // because, at present at least, it can only refer to early-bound regions
1611             let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1612             vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1613         }
1614
1615         for bound_trait_ref in &self.trait_bounds {
1616             vec.push(bound_trait_ref.to_predicate());
1617         }
1618
1619         for projection in &self.projection_bounds {
1620             vec.push(projection.to_predicate());
1621         }
1622
1623         vec
1624     }
1625 }
1626
1627 pub enum ExplicitSelf<'tcx> {
1628     ByValue,
1629     ByReference(&'tcx ty::Region, hir::Mutability),
1630     ByBox
1631 }
1632
1633 impl<'tcx> ExplicitSelf<'tcx> {
1634     /// We wish to (for now) categorize an explicit self
1635     /// declaration like `self: SomeType` into either `self`,
1636     /// `&self`, `&mut self`, or `Box<self>`. We do this here
1637     /// by some simple pattern matching. A more precise check
1638     /// is done later in `check_method_self_type()`.
1639     ///
1640     /// Examples:
1641     ///
1642     /// ```
1643     /// impl Foo for &T {
1644     ///     // Legal declarations:
1645     ///     fn method1(self: &&T); // ExplicitSelf::ByReference
1646     ///     fn method2(self: &T); // ExplicitSelf::ByValue
1647     ///     fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1648     ///
1649     ///     // Invalid cases will be caught later by `check_method_self_type`:
1650     ///     fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1651     /// }
1652     /// ```
1653     ///
1654     /// To do the check we just count the number of "modifiers"
1655     /// on each type and compare them. If they are the same or
1656     /// the impl has more, we call it "by value". Otherwise, we
1657     /// look at the outermost modifier on the method decl and
1658     /// call it by-ref, by-box as appropriate. For method1, for
1659     /// example, the impl type has one modifier, but the method
1660     /// type has two, so we end up with
1661     /// ExplicitSelf::ByReference.
1662     pub fn determine(untransformed_self_ty: Ty<'tcx>,
1663                      self_arg_ty: Ty<'tcx>)
1664                      -> ExplicitSelf<'tcx> {
1665         fn count_modifiers(ty: Ty) -> usize {
1666             match ty.sty {
1667                 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1668                 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1669                 _ => 0,
1670             }
1671         }
1672
1673         let impl_modifiers = count_modifiers(untransformed_self_ty);
1674         let method_modifiers = count_modifiers(self_arg_ty);
1675
1676         if impl_modifiers >= method_modifiers {
1677             ExplicitSelf::ByValue
1678         } else {
1679             match self_arg_ty.sty {
1680                 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1681                 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1682                 _ => ExplicitSelf::ByValue,
1683             }
1684         }
1685     }
1686 }