]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Fix accidental quadratic loops
[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 use rustc_data_structures::accumulate_vec::AccumulateVec;
16 use hir::{self, GenericArg};
17 use hir::def::Def;
18 use hir::def_id::DefId;
19 use middle::resolve_lifetime as rl;
20 use namespace::Namespace;
21 use rustc::ty::subst::{Subst, Substs};
22 use rustc::traits;
23 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
24 use rustc::ty::GenericParamDefKind;
25 use rustc::ty::wf::object_region_bounds;
26 use rustc_target::spec::abi;
27 use std::slice;
28 use require_c_abi_if_variadic;
29 use util::common::ErrorReported;
30 use util::nodemap::{FxHashSet, FxHashMap};
31 use errors::FatalError;
32
33 use std::iter;
34 use syntax::ast;
35 use syntax::feature_gate::{GateIssue, emit_feature_err};
36 use syntax_pos::Span;
37
38 pub trait AstConv<'gcx, 'tcx> {
39     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
40
41     /// Returns the set of bounds in scope for the type parameter with
42     /// the given id.
43     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
44                                  -> ty::GenericPredicates<'tcx>;
45
46     /// What lifetime should we use when a lifetime is omitted (and not elided)?
47     fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
48                 -> Option<ty::Region<'tcx>>;
49
50     /// What type should we use when a type is omitted?
51     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
52
53     /// Same as ty_infer, but with a known type parameter definition.
54     fn ty_infer_for_def(&self,
55                         _def: &ty::GenericParamDef,
56                         span: Span) -> Ty<'tcx> {
57         self.ty_infer(span)
58     }
59
60     /// Projecting an associated type from a (potentially)
61     /// higher-ranked trait reference is more complicated, because of
62     /// the possibility of late-bound regions appearing in the
63     /// associated type binding. This is not legal in function
64     /// signatures for that reason. In a function body, we can always
65     /// handle it because we can use inference variables to remove the
66     /// late-bound regions.
67     fn projected_ty_from_poly_trait_ref(&self,
68                                         span: Span,
69                                         item_def_id: DefId,
70                                         poly_trait_ref: ty::PolyTraitRef<'tcx>)
71                                         -> Ty<'tcx>;
72
73     /// Normalize an associated type coming from the user.
74     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
75
76     /// Invoked when we encounter an error from some prior pass
77     /// (e.g. resolve) that is translated into a ty-error. This is
78     /// used to help suppress derived errors typeck might otherwise
79     /// report.
80     fn set_tainted_by_errors(&self);
81
82     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
83 }
84
85 struct ConvertedBinding<'tcx> {
86     item_name: ast::Name,
87     ty: Ty<'tcx>,
88     span: Span,
89 }
90
91 struct ParamRange {
92     required: usize,
93     accepted: usize
94 }
95
96 /// Dummy type used for the `Self` of a `TraitRef` created for converting
97 /// a trait object, and which gets removed in `ExistentialTraitRef`.
98 /// This type must not appear anywhere in other converted types.
99 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
100
101 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
102     pub fn ast_region_to_region(&self,
103         lifetime: &hir::Lifetime,
104         def: Option<&ty::GenericParamDef>)
105         -> ty::Region<'tcx>
106     {
107         let tcx = self.tcx();
108         let lifetime_name = |def_id| {
109             tcx.hir.name(tcx.hir.as_local_node_id(def_id).unwrap()).as_interned_str()
110         };
111
112         let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
113         let r = match tcx.named_region(hir_id) {
114             Some(rl::Region::Static) => {
115                 tcx.types.re_static
116             }
117
118             Some(rl::Region::LateBound(debruijn, id, _)) => {
119                 let name = lifetime_name(id);
120                 tcx.mk_region(ty::ReLateBound(debruijn,
121                     ty::BrNamed(id, name)))
122             }
123
124             Some(rl::Region::LateBoundAnon(debruijn, index)) => {
125                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
126             }
127
128             Some(rl::Region::EarlyBound(index, id, _)) => {
129                 let name = lifetime_name(id);
130                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
131                     def_id: id,
132                     index,
133                     name,
134                 }))
135             }
136
137             Some(rl::Region::Free(scope, id)) => {
138                 let name = lifetime_name(id);
139                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
140                     scope,
141                     bound_region: ty::BrNamed(id, name)
142                 }))
143
144                     // (*) -- not late-bound, won't change
145             }
146
147             None => {
148                 self.re_infer(lifetime.span, def)
149                     .unwrap_or_else(|| {
150                         // This indicates an illegal lifetime
151                         // elision. `resolve_lifetime` should have
152                         // reported an error in this case -- but if
153                         // not, let's error out.
154                         tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
155
156                         // Supply some dummy value. We don't have an
157                         // `re_error`, annoyingly, so use `'static`.
158                         tcx.types.re_static
159                     })
160             }
161         };
162
163         debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
164                 lifetime,
165                 r);
166
167         r
168     }
169
170     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
171     /// returns an appropriate set of substitutions for this particular reference to `I`.
172     pub fn ast_path_substs_for_ty(&self,
173         span: Span,
174         def_id: DefId,
175         item_segment: &hir::PathSegment)
176         -> &'tcx Substs<'tcx>
177     {
178
179         let (substs, assoc_bindings) =
180             item_segment.with_generic_args(|generic_args| {
181                 self.create_substs_for_ast_path(
182                     span,
183                     def_id,
184                     generic_args,
185                     item_segment.infer_types,
186                     None)
187             });
188
189         assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
190
191         substs
192     }
193
194     /// Given the type/region arguments provided to some path (along with
195     /// an implicit Self, if this is a trait reference) returns the complete
196     /// set of substitutions. This may involve applying defaulted type parameters.
197     ///
198     /// Note that the type listing given here is *exactly* what the user provided.
199     fn create_substs_for_ast_path(&self,
200         span: Span,
201         def_id: DefId,
202         generic_args: &hir::GenericArgs,
203         infer_types: bool,
204         self_ty: Option<Ty<'tcx>>)
205         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
206     {
207         let tcx = self.tcx();
208
209         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
210                generic_args={:?})",
211                def_id, self_ty, generic_args);
212
213         // If the type is parameterized by this region, then replace this
214         // region with the current anon region binding (in other words,
215         // whatever & would get replaced with).
216         let mut lt_provided = 0;
217         let mut ty_provided = 0;
218         for arg in &generic_args.args {
219             match arg {
220                 GenericArg::Lifetime(_) => lt_provided += 1,
221                 GenericArg::Type(_) => ty_provided += 1,
222             }
223         }
224
225         let decl_generics = tcx.generics_of(def_id);
226         let mut lt_accepted = 0;
227         let mut ty_params = ParamRange { required: 0, accepted: 0 };
228         for param in &decl_generics.params {
229             match param.kind {
230                 GenericParamDefKind::Lifetime => {
231                     lt_accepted += 1;
232                 }
233                 GenericParamDefKind::Type { has_default, .. } => {
234                     ty_params.accepted += 1;
235                     if !has_default {
236                         ty_params.required += 1;
237                     }
238                 }
239             };
240         }
241         if self_ty.is_some() {
242             ty_params.required -= 1;
243             ty_params.accepted -= 1;
244         }
245
246         if lt_accepted != lt_provided {
247             report_lifetime_number_error(tcx, span, lt_provided, lt_accepted);
248         }
249
250         // If a self-type was declared, one should be provided.
251         assert_eq!(decl_generics.has_self, self_ty.is_some());
252
253         // Check the number of type parameters supplied by the user.
254         if !infer_types || ty_provided > ty_params.required {
255             check_type_argument_count(tcx, span, ty_provided, ty_params);
256         }
257
258         let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
259         let default_needs_object_self = |param: &ty::GenericParamDef| {
260             if let GenericParamDefKind::Type { has_default, .. } = param.kind {
261                 if is_object && has_default {
262                     if tcx.at(span).type_of(param.def_id).has_self_ty() {
263                         // There is no suitable inference default for a type parameter
264                         // that references self, in an object type.
265                         return true;
266                     }
267                 }
268             }
269
270             false
271         };
272
273         let own_self = self_ty.is_some() as usize;
274         // FIXME(varkor): Separating out the parameters is messy.
275         let lifetimes: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg {
276             GenericArg::Lifetime(lt) => Some(lt),
277             _ => None,
278         }).collect();
279         let types: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg {
280             GenericArg::Type(ty) => Some(ty),
281             _ => None,
282         }).collect();
283         let substs = Substs::for_item(tcx, def_id, |param, substs| {
284             match param.kind {
285                 GenericParamDefKind::Lifetime => {
286                     let i = param.index as usize - own_self;
287                     if let Some(lt) = lifetimes.get(i) {
288                         self.ast_region_to_region(lt, Some(param)).into()
289                     } else {
290                         tcx.types.re_static.into()
291                     }
292                 }
293                 GenericParamDefKind::Type { has_default, .. } => {
294                     let i = param.index as usize;
295
296                     // Handle Self first, so we can adjust the index to match the AST.
297                     if let (0, Some(ty)) = (i, self_ty) {
298                         return ty.into();
299                     }
300
301                     let i = i - (lt_accepted + own_self);
302                     if i < ty_provided {
303                         // A provided type parameter.
304                         self.ast_ty_to_ty(&types[i]).into()
305                     } else if infer_types {
306                         // No type parameters were provided, we can infer all.
307                         if !default_needs_object_self(param) {
308                             self.ty_infer_for_def(param, span).into()
309                         } else {
310                             self.ty_infer(span).into()
311                         }
312                     } else if has_default {
313                         // No type parameter provided, but a default exists.
314
315                         // If we are converting an object type, then the
316                         // `Self` parameter is unknown. However, some of the
317                         // other type parameters may reference `Self` in their
318                         // defaults. This will lead to an ICE if we are not
319                         // careful!
320                         if default_needs_object_self(param) {
321                             struct_span_err!(tcx.sess, span, E0393,
322                                              "the type parameter `{}` must be explicitly \
323                                              specified",
324                                              param.name)
325                                 .span_label(span,
326                                             format!("missing reference to `{}`", param.name))
327                                 .note(&format!("because of the default `Self` reference, \
328                                                 type parameters must be specified on object \
329                                                 types"))
330                                 .emit();
331                             tcx.types.err.into()
332                         } else {
333                             // This is a default type parameter.
334                             self.normalize_ty(
335                                 span,
336                                 tcx.at(span).type_of(param.def_id)
337                                     .subst_spanned(tcx, substs, Some(span))
338                             ).into()
339                         }
340                     } else {
341                         // We've already errored above about the mismatch.
342                         tcx.types.err.into()
343                     }
344                 }
345             }
346         });
347
348         let assoc_bindings = generic_args.bindings.iter().map(|binding| {
349             ConvertedBinding {
350                 item_name: binding.name,
351                 ty: self.ast_ty_to_ty(&binding.ty),
352                 span: binding.span,
353             }
354         }).collect();
355
356         debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
357                decl_generics, self_ty, substs);
358
359         (substs, assoc_bindings)
360     }
361
362     /// Instantiates the path for the given trait reference, assuming that it's
363     /// bound to a valid trait type. Returns the def_id for the defining trait.
364     /// The type _cannot_ be a type other than a trait type.
365     ///
366     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
367     /// are disallowed. Otherwise, they are pushed onto the vector given.
368     pub fn instantiate_mono_trait_ref(&self,
369         trait_ref: &hir::TraitRef,
370         self_ty: Ty<'tcx>)
371         -> ty::TraitRef<'tcx>
372     {
373         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
374
375         let trait_def_id = self.trait_def_id(trait_ref);
376         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
377                                         trait_def_id,
378                                         self_ty,
379                                         trait_ref.path.segments.last().unwrap())
380     }
381
382     /// Get the DefId of the given trait ref. It _must_ actually be a trait.
383     fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
384         let path = &trait_ref.path;
385         match path.def {
386             Def::Trait(trait_def_id) => trait_def_id,
387             Def::TraitAlias(alias_def_id) => alias_def_id,
388             Def::Err => {
389                 FatalError.raise();
390             }
391             _ => unreachable!(),
392         }
393     }
394
395     /// The given `trait_ref` must actually be trait.
396     pub(super) fn instantiate_poly_trait_ref_inner(&self,
397         trait_ref: &hir::TraitRef,
398         self_ty: Ty<'tcx>,
399         poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>,
400         speculative: bool)
401         -> ty::PolyTraitRef<'tcx>
402     {
403         let trait_def_id = self.trait_def_id(trait_ref);
404
405         debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
406
407         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
408
409         let (substs, assoc_bindings) =
410             self.create_substs_for_ast_trait_ref(trait_ref.path.span,
411                                                  trait_def_id,
412                                                  self_ty,
413                                                  trait_ref.path.segments.last().unwrap());
414         let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
415
416         let mut dup_bindings = FxHashMap::default();
417         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
418             // specify type to assert that error was already reported in Err case:
419             let predicate: Result<_, ErrorReported> =
420                 self.ast_type_binding_to_poly_projection_predicate(
421                     trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
422             predicate.ok() // ok to ignore Err() because ErrorReported (see above)
423         }));
424
425         debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
426                trait_ref, poly_projections, poly_trait_ref);
427         poly_trait_ref
428     }
429
430     pub fn instantiate_poly_trait_ref(&self,
431         poly_trait_ref: &hir::PolyTraitRef,
432         self_ty: Ty<'tcx>,
433         poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
434         -> ty::PolyTraitRef<'tcx>
435     {
436         self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
437                                               poly_projections, false)
438     }
439
440     fn ast_path_to_mono_trait_ref(&self,
441                                   span: Span,
442                                   trait_def_id: DefId,
443                                   self_ty: Ty<'tcx>,
444                                   trait_segment: &hir::PathSegment)
445                                   -> ty::TraitRef<'tcx>
446     {
447         let (substs, assoc_bindings) =
448             self.create_substs_for_ast_trait_ref(span,
449                                                  trait_def_id,
450                                                  self_ty,
451                                                  trait_segment);
452         assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
453         ty::TraitRef::new(trait_def_id, substs)
454     }
455
456     fn create_substs_for_ast_trait_ref(&self,
457                                        span: Span,
458                                        trait_def_id: DefId,
459                                        self_ty: Ty<'tcx>,
460                                        trait_segment: &hir::PathSegment)
461                                        -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
462     {
463         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
464                trait_segment);
465
466         let trait_def = self.tcx().trait_def(trait_def_id);
467
468         if !self.tcx().features().unboxed_closures &&
469             trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
470             != trait_def.paren_sugar {
471             // For now, require that parenthetical notation be used only with `Fn()` etc.
472             let msg = if trait_def.paren_sugar {
473                 "the precise format of `Fn`-family traits' type parameters is subject to change. \
474                  Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
475             } else {
476                 "parenthetical notation is only stable when used with `Fn`-family traits"
477             };
478             emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
479                              span, GateIssue::Language, msg);
480         }
481
482         trait_segment.with_generic_args(|generic_args| {
483             self.create_substs_for_ast_path(span,
484                                             trait_def_id,
485                                             generic_args,
486                                             trait_segment.infer_types,
487                                             Some(self_ty))
488         })
489     }
490
491     fn trait_defines_associated_type_named(&self,
492                                            trait_def_id: DefId,
493                                            assoc_name: ast::Name)
494                                            -> bool
495     {
496         self.tcx().associated_items(trait_def_id).any(|item| {
497             item.kind == ty::AssociatedKind::Type &&
498             self.tcx().hygienic_eq(assoc_name, item.name, trait_def_id)
499         })
500     }
501
502     fn ast_type_binding_to_poly_projection_predicate(
503         &self,
504         ref_id: ast::NodeId,
505         trait_ref: ty::PolyTraitRef<'tcx>,
506         binding: &ConvertedBinding<'tcx>,
507         speculative: bool,
508         dup_bindings: &mut FxHashMap<DefId, Span>)
509         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
510     {
511         let tcx = self.tcx();
512
513         if !speculative {
514             // Given something like `U : SomeTrait<T=X>`, we want to produce a
515             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
516             // subtle in the event that `T` is defined in a supertrait of
517             // `SomeTrait`, because in that case we need to upcast.
518             //
519             // That is, consider this case:
520             //
521             // ```
522             // trait SubTrait : SuperTrait<int> { }
523             // trait SuperTrait<A> { type T; }
524             //
525             // ... B : SubTrait<T=foo> ...
526             // ```
527             //
528             // We want to produce `<B as SuperTrait<int>>::T == foo`.
529
530             // Find any late-bound regions declared in `ty` that are not
531             // declared in the trait-ref. These are not wellformed.
532             //
533             // Example:
534             //
535             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
536             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
537             let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
538             let late_bound_in_ty =
539                 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
540             debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
541             debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
542             for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
543                 let br_name = match *br {
544                     ty::BrNamed(_, name) => name,
545                     _ => {
546                         span_bug!(
547                             binding.span,
548                             "anonymous bound region {:?} in binding but not trait ref",
549                             br);
550                     }
551                 };
552                 struct_span_err!(tcx.sess,
553                                 binding.span,
554                                 E0582,
555                                 "binding for associated type `{}` references lifetime `{}`, \
556                                 which does not appear in the trait input types",
557                                 binding.item_name, br_name)
558                     .emit();
559             }
560         }
561
562         let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
563                                                                     binding.item_name) {
564             // Simple case: X is defined in the current trait.
565             Ok(trait_ref)
566         } else {
567             // Otherwise, we have to walk through the supertraits to find
568             // those that do.
569             let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
570                 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
571             });
572             self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
573                                           binding.item_name, binding.span)
574         }?;
575
576         let (assoc_ident, def_scope) =
577             tcx.adjust_ident(binding.item_name.to_ident(), candidate.def_id(), ref_id);
578         let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
579             i.kind == ty::AssociatedKind::Type && i.name.to_ident() == assoc_ident
580         }).expect("missing associated type");
581
582         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
583             let msg = format!("associated type `{}` is private", binding.item_name);
584             tcx.sess.span_err(binding.span, &msg);
585         }
586         tcx.check_stability(assoc_ty.def_id, Some(ref_id), binding.span);
587
588         if !speculative {
589             dup_bindings.entry(assoc_ty.def_id)
590                 .and_modify(|prev_span| {
591                     let mut err = self.tcx().struct_span_lint_node(
592                         ::rustc::lint::builtin::DUPLICATE_ASSOCIATED_TYPE_BINDINGS,
593                         ref_id,
594                         binding.span,
595                         &format!("associated type binding `{}` specified more than once",
596                                 binding.item_name)
597                     );
598                     err.span_label(binding.span, "used more than once");
599                     err.span_label(*prev_span, format!("first use of `{}`", binding.item_name));
600                     err.emit();
601                 })
602                 .or_insert(binding.span);
603         }
604
605         Ok(candidate.map_bound(|trait_ref| {
606             ty::ProjectionPredicate {
607                 projection_ty: ty::ProjectionTy::from_ref_and_name(
608                     tcx,
609                     trait_ref,
610                     binding.item_name,
611                 ),
612                 ty: binding.ty,
613             }
614         }))
615     }
616
617     fn ast_path_to_ty(&self,
618         span: Span,
619         did: DefId,
620         item_segment: &hir::PathSegment)
621         -> Ty<'tcx>
622     {
623         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
624         self.normalize_ty(
625             span,
626             self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
627         )
628     }
629
630     /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
631     /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
632     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
633                                 -> ty::ExistentialTraitRef<'tcx> {
634         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
635         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
636     }
637
638     fn conv_object_ty_poly_trait_ref(&self,
639         span: Span,
640         trait_bounds: &[hir::PolyTraitRef],
641         lifetime: &hir::Lifetime)
642         -> Ty<'tcx>
643     {
644         let tcx = self.tcx();
645
646         if trait_bounds.is_empty() {
647             span_err!(tcx.sess, span, E0224,
648                       "at least one non-builtin trait is required for an object type");
649             return tcx.types.err;
650         }
651
652         let mut projection_bounds = vec![];
653         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
654         let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
655                                                         dummy_self,
656                                                         &mut projection_bounds);
657
658         for trait_bound in trait_bounds[1..].iter() {
659             // Sanity check for non-principal trait bounds
660             self.instantiate_poly_trait_ref(trait_bound,
661                                             dummy_self,
662                                             &mut vec![]);
663         }
664
665         let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
666
667         if !trait_bounds.is_empty() {
668             let b = &trait_bounds[0];
669             let span = b.trait_ref.path.span;
670             struct_span_err!(self.tcx().sess, span, E0225,
671                 "only auto traits can be used as additional traits in a trait object")
672                 .span_label(span, "non-auto additional trait")
673                 .emit();
674         }
675
676         // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
677         let existential_principal = principal.map_bound(|trait_ref| {
678             self.trait_ref_to_existential(trait_ref)
679         });
680         let existential_projections = projection_bounds.iter().map(|bound| {
681             bound.map_bound(|b| {
682                 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
683                 ty::ExistentialProjection {
684                     ty: b.ty,
685                     item_def_id: b.projection_ty.item_def_id,
686                     substs: trait_ref.substs,
687                 }
688             })
689         });
690
691         // check that there are no gross object safety violations,
692         // most importantly, that the supertraits don't contain Self,
693         // to avoid ICE-s.
694         let object_safety_violations =
695             tcx.astconv_object_safety_violations(principal.def_id());
696         if !object_safety_violations.is_empty() {
697             tcx.report_object_safety_error(
698                 span, principal.def_id(), object_safety_violations)
699                 .emit();
700             return tcx.types.err;
701         }
702
703         let mut associated_types = FxHashSet::default();
704         for tr in traits::supertraits(tcx, principal) {
705             associated_types.extend(tcx.associated_items(tr.def_id())
706                 .filter(|item| item.kind == ty::AssociatedKind::Type)
707                 .map(|item| item.def_id));
708         }
709
710         for projection_bound in &projection_bounds {
711             associated_types.remove(&projection_bound.projection_def_id());
712         }
713
714         for item_def_id in associated_types {
715             let assoc_item = tcx.associated_item(item_def_id);
716             let trait_def_id = assoc_item.container.id();
717             struct_span_err!(tcx.sess, span, E0191,
718                 "the value of the associated type `{}` (from the trait `{}`) must be specified",
719                         assoc_item.name,
720                         tcx.item_path_str(trait_def_id))
721                         .span_label(span, format!(
722                             "missing associated type `{}` value", assoc_item.name))
723                         .emit();
724         }
725
726         // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
727         auto_traits.sort();
728         auto_traits.dedup();
729
730         // skip_binder is okay, because the predicates are re-bound.
731         let mut v =
732             iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
733             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
734             .chain(existential_projections
735                    .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
736             .collect::<AccumulateVec<[_; 8]>>();
737         v.sort_by(|a, b| a.stable_cmp(tcx, b));
738         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
739
740
741         // Explicitly specified region bound. Use that.
742         let region_bound = if !lifetime.is_elided() {
743             self.ast_region_to_region(lifetime, None)
744         } else {
745             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
746                 let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
747                 if tcx.named_region(hir_id).is_some() {
748                     self.ast_region_to_region(lifetime, None)
749                 } else {
750                     self.re_infer(span, None).unwrap_or_else(|| {
751                         span_err!(tcx.sess, span, E0228,
752                                   "the lifetime bound for this object type cannot be deduced \
753                                    from context; please supply an explicit bound");
754                         tcx.types.re_static
755                     })
756                 }
757             })
758         };
759
760         debug!("region_bound: {:?}", region_bound);
761
762         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
763         debug!("trait_object_type: {:?}", ty);
764         ty
765     }
766
767     fn report_ambiguous_associated_type(&self,
768                                         span: Span,
769                                         type_str: &str,
770                                         trait_str: &str,
771                                         name: &str) {
772         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
773             .span_label(span, "ambiguous associated type")
774             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
775                   type_str, trait_str, name))
776             .emit();
777
778     }
779
780     // Search for a bound on a type parameter which includes the associated item
781     // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
782     // This function will fail if there are no suitable bounds or there is
783     // any ambiguity.
784     fn find_bound_for_assoc_item(&self,
785                                  ty_param_def_id: DefId,
786                                  assoc_name: ast::Name,
787                                  span: Span)
788                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
789     {
790         let tcx = self.tcx();
791
792         let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
793             .predicates.into_iter().filter_map(|p| p.to_opt_poly_trait_ref()).collect();
794
795         // Check that there is exactly one way to find an associated type with the
796         // correct name.
797         let suitable_bounds =
798             traits::transitive_bounds(tcx, &bounds)
799             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
800
801         let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
802         let param_name = tcx.hir.ty_param_name(param_node_id);
803         self.one_bound_for_assoc_type(suitable_bounds,
804                                       &param_name.as_str(),
805                                       assoc_name,
806                                       span)
807     }
808
809
810     // Checks that bounds contains exactly one element and reports appropriate
811     // errors otherwise.
812     fn one_bound_for_assoc_type<I>(&self,
813                                 mut bounds: I,
814                                 ty_param_name: &str,
815                                 assoc_name: ast::Name,
816                                 span: Span)
817         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
818         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
819     {
820         let bound = match bounds.next() {
821             Some(bound) => bound,
822             None => {
823                 struct_span_err!(self.tcx().sess, span, E0220,
824                           "associated type `{}` not found for `{}`",
825                           assoc_name,
826                           ty_param_name)
827                   .span_label(span, format!("associated type `{}` not found", assoc_name))
828                   .emit();
829                 return Err(ErrorReported);
830             }
831         };
832
833         if let Some(bound2) = bounds.next() {
834             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
835             let mut err = struct_span_err!(
836                 self.tcx().sess, span, E0221,
837                 "ambiguous associated type `{}` in bounds of `{}`",
838                 assoc_name,
839                 ty_param_name);
840             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
841
842             for bound in bounds {
843                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
844                     item.kind == ty::AssociatedKind::Type &&
845                     self.tcx().hygienic_eq(assoc_name, item.name, bound.def_id())
846                 })
847                 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
848
849                 if let Some(span) = bound_span {
850                     err.span_label(span, format!("ambiguous `{}` from `{}`",
851                                                   assoc_name,
852                                                   bound));
853                 } else {
854                     span_note!(&mut err, span,
855                                "associated type `{}` could derive from `{}`",
856                                ty_param_name,
857                                bound);
858                 }
859             }
860             err.emit();
861         }
862
863         return Ok(bound);
864     }
865
866     // Create a type from a path to an associated type.
867     // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
868     // and item_segment is the path segment for D. We return a type and a def for
869     // the whole path.
870     // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
871     // parameter or Self.
872     pub fn associated_path_def_to_ty(&self,
873                                      ref_id: ast::NodeId,
874                                      span: Span,
875                                      ty: Ty<'tcx>,
876                                      ty_path_def: Def,
877                                      item_segment: &hir::PathSegment)
878                                      -> (Ty<'tcx>, Def)
879     {
880         let tcx = self.tcx();
881         let assoc_name = item_segment.name;
882
883         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
884
885         self.prohibit_generics(slice::from_ref(item_segment));
886
887         // Find the type of the associated item, and the trait where the associated
888         // item is declared.
889         let bound = match (&ty.sty, ty_path_def) {
890             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
891                 // `Self` in an impl of a trait - we have a concrete self type and a
892                 // trait reference.
893                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
894                     Some(trait_ref) => trait_ref,
895                     None => {
896                         // A cycle error occurred, most likely.
897                         return (tcx.types.err, Def::Err);
898                     }
899                 };
900
901                 let candidates =
902                     traits::supertraits(tcx, ty::Binder::bind(trait_ref))
903                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
904                                                                          assoc_name));
905
906                 match self.one_bound_for_assoc_type(candidates, "Self", assoc_name, span) {
907                     Ok(bound) => bound,
908                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
909                 }
910             }
911             (&ty::TyParam(_), Def::SelfTy(Some(param_did), None)) |
912             (&ty::TyParam(_), Def::TyParam(param_did)) => {
913                 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
914                     Ok(bound) => bound,
915                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
916                 }
917             }
918             _ => {
919                 // Don't print TyErr to the user.
920                 if !ty.references_error() {
921                     self.report_ambiguous_associated_type(span,
922                                                           &ty.to_string(),
923                                                           "Trait",
924                                                           &assoc_name.as_str());
925                 }
926                 return (tcx.types.err, Def::Err);
927             }
928         };
929
930         let trait_did = bound.def_id();
931         let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_name.to_ident(), trait_did, ref_id);
932         let item = tcx.associated_items(trait_did).find(|i| {
933             Namespace::from(i.kind) == Namespace::Type &&
934             i.name.to_ident() == assoc_ident
935         })
936         .expect("missing associated type");
937
938         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
939         let ty = self.normalize_ty(span, ty);
940
941         let def = Def::AssociatedTy(item.def_id);
942         if !item.vis.is_accessible_from(def_scope, tcx) {
943             let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
944             tcx.sess.span_err(span, &msg);
945         }
946         tcx.check_stability(item.def_id, Some(ref_id), span);
947
948         (ty, def)
949     }
950
951     fn qpath_to_ty(&self,
952                    span: Span,
953                    opt_self_ty: Option<Ty<'tcx>>,
954                    item_def_id: DefId,
955                    trait_segment: &hir::PathSegment,
956                    item_segment: &hir::PathSegment)
957                    -> Ty<'tcx>
958     {
959         let tcx = self.tcx();
960         let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
961
962         self.prohibit_generics(slice::from_ref(item_segment));
963
964         let self_ty = if let Some(ty) = opt_self_ty {
965             ty
966         } else {
967             let path_str = tcx.item_path_str(trait_def_id);
968             self.report_ambiguous_associated_type(span,
969                                                   "Type",
970                                                   &path_str,
971                                                   &item_segment.name.as_str());
972             return tcx.types.err;
973         };
974
975         debug!("qpath_to_ty: self_type={:?}", self_ty);
976
977         let trait_ref = self.ast_path_to_mono_trait_ref(span,
978                                                         trait_def_id,
979                                                         self_ty,
980                                                         trait_segment);
981
982         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
983
984         self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
985     }
986
987     pub fn prohibit_generics(&self, segments: &[hir::PathSegment]) {
988         for segment in segments {
989             segment.with_generic_args(|generic_args| {
990                 let (mut err_for_lt, mut err_for_ty) = (false, false);
991                 for arg in &generic_args.args {
992                     let (mut span_err, span, kind) = match arg {
993                         hir::GenericArg::Lifetime(lt) => {
994                             if err_for_lt { continue }
995                             err_for_lt = true;
996                             (struct_span_err!(self.tcx().sess, lt.span, E0110,
997                                             "lifetime parameters are not allowed on \
998                                                 this type"),
999                              lt.span,
1000                              "lifetime")
1001                         }
1002                         hir::GenericArg::Type(ty) => {
1003                             if err_for_ty { continue }
1004                             err_for_ty = true;
1005                             (struct_span_err!(self.tcx().sess, ty.span, E0109,
1006                                             "type parameters are not allowed on this type"),
1007                              ty.span,
1008                              "type")
1009                         }
1010                     };
1011                     span_err.span_label(span, format!("{} parameter not allowed", kind))
1012                             .emit();
1013                     if err_for_lt && err_for_ty {
1014                         break;
1015                     }
1016                 }
1017                 for binding in &generic_args.bindings {
1018                     self.prohibit_projection(binding.span);
1019                     break;
1020                 }
1021             })
1022         }
1023     }
1024
1025     pub fn prohibit_projection(&self, span: Span) {
1026         let mut err = struct_span_err!(self.tcx().sess, span, E0229,
1027                                        "associated type bindings are not allowed here");
1028         err.span_label(span, "associated type not allowed here").emit();
1029     }
1030
1031     // Check a type Path and convert it to a Ty.
1032     pub fn def_to_ty(&self,
1033                      opt_self_ty: Option<Ty<'tcx>>,
1034                      path: &hir::Path,
1035                      permit_variants: bool)
1036                      -> Ty<'tcx> {
1037         let tcx = self.tcx();
1038
1039         debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1040                path.def, opt_self_ty, path.segments);
1041
1042         let span = path.span;
1043         match path.def {
1044             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1045             Def::Union(did) | Def::TyForeign(did) => {
1046                 assert_eq!(opt_self_ty, None);
1047                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1048                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1049             }
1050             Def::Variant(did) if permit_variants => {
1051                 // Convert "variant type" as if it were a real type.
1052                 // The resulting `Ty` is type of the variant's enum for now.
1053                 assert_eq!(opt_self_ty, None);
1054                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1055                 self.ast_path_to_ty(span,
1056                                     tcx.parent_def_id(did).unwrap(),
1057                                     path.segments.last().unwrap())
1058             }
1059             Def::TyParam(did) => {
1060                 assert_eq!(opt_self_ty, None);
1061                 self.prohibit_generics(&path.segments);
1062
1063                 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1064                 let item_id = tcx.hir.get_parent_node(node_id);
1065                 let item_def_id = tcx.hir.local_def_id(item_id);
1066                 let generics = tcx.generics_of(item_def_id);
1067                 let index = generics.param_def_id_to_index[&tcx.hir.local_def_id(node_id)];
1068                 tcx.mk_ty_param(index, tcx.hir.name(node_id).as_interned_str())
1069             }
1070             Def::SelfTy(_, Some(def_id)) => {
1071                 // Self in impl (we know the concrete type).
1072
1073                 assert_eq!(opt_self_ty, None);
1074                 self.prohibit_generics(&path.segments);
1075
1076                 tcx.at(span).type_of(def_id)
1077             }
1078             Def::SelfTy(Some(_), None) => {
1079                 // Self in trait.
1080                 assert_eq!(opt_self_ty, None);
1081                 self.prohibit_generics(&path.segments);
1082                 tcx.mk_self_type()
1083             }
1084             Def::AssociatedTy(def_id) => {
1085                 self.prohibit_generics(&path.segments[..path.segments.len()-2]);
1086                 self.qpath_to_ty(span,
1087                                  opt_self_ty,
1088                                  def_id,
1089                                  &path.segments[path.segments.len()-2],
1090                                  path.segments.last().unwrap())
1091             }
1092             Def::PrimTy(prim_ty) => {
1093                 assert_eq!(opt_self_ty, None);
1094                 self.prohibit_generics(&path.segments);
1095                 match prim_ty {
1096                     hir::TyBool => tcx.types.bool,
1097                     hir::TyChar => tcx.types.char,
1098                     hir::TyInt(it) => tcx.mk_mach_int(it),
1099                     hir::TyUint(uit) => tcx.mk_mach_uint(uit),
1100                     hir::TyFloat(ft) => tcx.mk_mach_float(ft),
1101                     hir::TyStr => tcx.mk_str()
1102                 }
1103             }
1104             Def::Err => {
1105                 self.set_tainted_by_errors();
1106                 return self.tcx().types.err;
1107             }
1108             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1109         }
1110     }
1111
1112     /// Parses the programmer's textual representation of a type into our
1113     /// internal notion of a type.
1114     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1115         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1116                ast_ty.id, ast_ty);
1117
1118         let tcx = self.tcx();
1119
1120         let result_ty = match ast_ty.node {
1121             hir::TySlice(ref ty) => {
1122                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1123             }
1124             hir::TyPtr(ref mt) => {
1125                 tcx.mk_ptr(ty::TypeAndMut {
1126                     ty: self.ast_ty_to_ty(&mt.ty),
1127                     mutbl: mt.mutbl
1128                 })
1129             }
1130             hir::TyRptr(ref region, ref mt) => {
1131                 let r = self.ast_region_to_region(region, None);
1132                 debug!("TyRef r={:?}", r);
1133                 let t = self.ast_ty_to_ty(&mt.ty);
1134                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1135             }
1136             hir::TyNever => {
1137                 tcx.types.never
1138             },
1139             hir::TyTup(ref fields) => {
1140                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1141             }
1142             hir::TyBareFn(ref bf) => {
1143                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1144                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1145             }
1146             hir::TyTraitObject(ref bounds, ref lifetime) => {
1147                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1148             }
1149             hir::TyImplTraitExistential(_, def_id, ref lifetimes) => {
1150                 self.impl_trait_ty_to_ty(def_id, lifetimes)
1151             }
1152             hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1153                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1154                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1155                     self.ast_ty_to_ty(qself)
1156                 });
1157                 self.def_to_ty(opt_self_ty, path, false)
1158             }
1159             hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1160                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1161                 let ty = self.ast_ty_to_ty(qself);
1162
1163                 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1164                     path.def
1165                 } else {
1166                     Def::Err
1167                 };
1168                 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1169             }
1170             hir::TyArray(ref ty, ref length) => {
1171                 let length_def_id = tcx.hir.local_def_id(length.id);
1172                 let substs = Substs::identity_for_item(tcx, length_def_id);
1173                 let length = ty::Const::unevaluated(tcx, length_def_id, substs, tcx.types.usize);
1174                 let array_ty = tcx.mk_ty(ty::TyArray(self.ast_ty_to_ty(&ty), length));
1175                 self.normalize_ty(ast_ty.span, array_ty)
1176             }
1177             hir::TyTypeof(ref _e) => {
1178                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1179                                  "`typeof` is a reserved keyword but unimplemented")
1180                     .span_label(ast_ty.span, "reserved keyword")
1181                     .emit();
1182
1183                 tcx.types.err
1184             }
1185             hir::TyInfer => {
1186                 // TyInfer also appears as the type of arguments or return
1187                 // values in a ExprClosure, or as
1188                 // the type of local variables. Both of these cases are
1189                 // handled specially and will not descend into this routine.
1190                 self.ty_infer(ast_ty.span)
1191             }
1192             hir::TyErr => {
1193                 tcx.types.err
1194             }
1195         };
1196
1197         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1198         result_ty
1199     }
1200
1201     pub fn impl_trait_ty_to_ty(
1202         &self,
1203         def_id: DefId,
1204         lifetimes: &[hir::Lifetime],
1205     ) -> Ty<'tcx> {
1206         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1207         let tcx = self.tcx();
1208
1209         let generics = tcx.generics_of(def_id);
1210
1211         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1212         let substs = Substs::for_item(tcx, def_id, |param, _| {
1213             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1214                 // Our own parameters are the resolved lifetimes.
1215                 match param.kind {
1216                     GenericParamDefKind::Lifetime => {
1217                         self.ast_region_to_region(&lifetimes[i], None).into()
1218                     }
1219                     _ => bug!()
1220                 }
1221             } else {
1222                 // Replace all parent lifetimes with 'static.
1223                 match param.kind {
1224                     GenericParamDefKind::Lifetime => {
1225                         tcx.types.re_static.into()
1226                     }
1227                     _ => tcx.mk_param_from_def(param)
1228                 }
1229             }
1230         });
1231         debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1232
1233         let ty = tcx.mk_anon(def_id, substs);
1234         debug!("impl_trait_ty_to_ty: {}", ty);
1235         ty
1236     }
1237
1238     pub fn ty_of_arg(&self,
1239                      ty: &hir::Ty,
1240                      expected_ty: Option<Ty<'tcx>>)
1241                      -> Ty<'tcx>
1242     {
1243         match ty.node {
1244             hir::TyInfer if expected_ty.is_some() => {
1245                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1246                 expected_ty.unwrap()
1247             }
1248             _ => self.ast_ty_to_ty(ty),
1249         }
1250     }
1251
1252     pub fn ty_of_fn(&self,
1253                     unsafety: hir::Unsafety,
1254                     abi: abi::Abi,
1255                     decl: &hir::FnDecl)
1256                     -> ty::PolyFnSig<'tcx> {
1257         debug!("ty_of_fn");
1258
1259         let tcx = self.tcx();
1260         let input_tys: Vec<Ty> =
1261             decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1262
1263         let output_ty = match decl.output {
1264             hir::Return(ref output) => self.ast_ty_to_ty(output),
1265             hir::DefaultReturn(..) => tcx.mk_nil(),
1266         };
1267
1268         debug!("ty_of_fn: output_ty={:?}", output_ty);
1269
1270         let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1271             input_tys.into_iter(),
1272             output_ty,
1273             decl.variadic,
1274             unsafety,
1275             abi
1276         ));
1277
1278         // Find any late-bound regions declared in return type that do
1279         // not appear in the arguments. These are not wellformed.
1280         //
1281         // Example:
1282         //     for<'a> fn() -> &'a str <-- 'a is bad
1283         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1284         let inputs = bare_fn_ty.inputs();
1285         let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1286             &inputs.map_bound(|i| i.to_owned()));
1287         let output = bare_fn_ty.output();
1288         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1289         for br in late_bound_in_ret.difference(&late_bound_in_args) {
1290             let lifetime_name = match *br {
1291                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1292                 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => format!("an anonymous lifetime"),
1293             };
1294             let mut err = struct_span_err!(tcx.sess,
1295                                            decl.output.span(),
1296                                            E0581,
1297                                            "return type references {} \
1298                                             which is not constrained by the fn input types",
1299                                            lifetime_name);
1300             if let ty::BrAnon(_) = *br {
1301                 // The only way for an anonymous lifetime to wind up
1302                 // in the return type but **also** be unconstrained is
1303                 // if it only appears in "associated types" in the
1304                 // input. See #47511 for an example. In this case,
1305                 // though we can easily give a hint that ought to be
1306                 // relevant.
1307                 err.note("lifetimes appearing in an associated type \
1308                           are not considered constrained");
1309             }
1310             err.emit();
1311         }
1312
1313         bare_fn_ty
1314     }
1315
1316     /// Given the bounds on an object, determines what single region bound (if any) we can
1317     /// use to summarize this type. The basic idea is that we will use the bound the user
1318     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1319     /// for region bounds. It may be that we can derive no bound at all, in which case
1320     /// we return `None`.
1321     fn compute_object_lifetime_bound(&self,
1322         span: Span,
1323         existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1324         -> Option<ty::Region<'tcx>> // if None, use the default
1325     {
1326         let tcx = self.tcx();
1327
1328         debug!("compute_opt_region_bound(existential_predicates={:?})",
1329                existential_predicates);
1330
1331         // No explicit region bound specified. Therefore, examine trait
1332         // bounds and see if we can derive region bounds from those.
1333         let derived_region_bounds =
1334             object_region_bounds(tcx, existential_predicates);
1335
1336         // If there are no derived region bounds, then report back that we
1337         // can find no region bound. The caller will use the default.
1338         if derived_region_bounds.is_empty() {
1339             return None;
1340         }
1341
1342         // If any of the derived region bounds are 'static, that is always
1343         // the best choice.
1344         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1345             return Some(tcx.types.re_static);
1346         }
1347
1348         // Determine whether there is exactly one unique region in the set
1349         // of derived region bounds. If so, use that. Otherwise, report an
1350         // error.
1351         let r = derived_region_bounds[0];
1352         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1353             span_err!(tcx.sess, span, E0227,
1354                       "ambiguous lifetime bound, explicit lifetime bound required");
1355         }
1356         return Some(r);
1357     }
1358 }
1359
1360 /// Divides a list of general trait bounds into two groups: auto traits (e.g. Sync and Send) and the
1361 /// remaining general trait bounds.
1362 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1363                                          trait_bounds: &'b [hir::PolyTraitRef])
1364     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1365 {
1366     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1367         // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
1368         match bound.trait_ref.path.def {
1369             Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
1370                 true
1371             }
1372             _ => false
1373         }
1374     });
1375
1376     let auto_traits = auto_traits.into_iter().map(|tr| {
1377         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1378             trait_did
1379         } else {
1380             unreachable!()
1381         }
1382     }).collect::<Vec<_>>();
1383
1384     (auto_traits, trait_bounds)
1385 }
1386
1387 fn check_type_argument_count(tcx: TyCtxt,
1388                              span: Span,
1389                              supplied: usize,
1390                              ty_params: ParamRange)
1391 {
1392     let (required, accepted) = (ty_params.required, ty_params.accepted);
1393     if supplied < required {
1394         let expected = if required < accepted {
1395             "expected at least"
1396         } else {
1397             "expected"
1398         };
1399         let arguments_plural = if required == 1 { "" } else { "s" };
1400
1401         struct_span_err!(tcx.sess, span, E0243,
1402                 "wrong number of type arguments: {} {}, found {}",
1403                 expected, required, supplied)
1404             .span_label(span,
1405                 format!("{} {} type argument{}",
1406                     expected,
1407                     required,
1408                     arguments_plural))
1409             .emit();
1410     } else if supplied > accepted {
1411         let expected = if required < accepted {
1412             format!("expected at most {}", accepted)
1413         } else {
1414             format!("expected {}", accepted)
1415         };
1416         let arguments_plural = if accepted == 1 { "" } else { "s" };
1417
1418         struct_span_err!(tcx.sess, span, E0244,
1419                 "wrong number of type arguments: {}, found {}",
1420                 expected, supplied)
1421             .span_label(
1422                 span,
1423                 format!("{} type argument{}",
1424                     if accepted == 0 { "expected no" } else { &expected },
1425                     arguments_plural)
1426             )
1427             .emit();
1428     }
1429 }
1430
1431 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1432     let label = if number < expected {
1433         if expected == 1 {
1434             format!("expected {} lifetime parameter", expected)
1435         } else {
1436             format!("expected {} lifetime parameters", expected)
1437         }
1438     } else {
1439         let additional = number - expected;
1440         if additional == 1 {
1441             "unexpected lifetime parameter".to_string()
1442         } else {
1443             format!("{} unexpected lifetime parameters", additional)
1444         }
1445     };
1446     struct_span_err!(tcx.sess, span, E0107,
1447                      "wrong number of lifetime parameters: expected {}, found {}",
1448                      expected, number)
1449         .span_label(span, label)
1450         .emit();
1451 }
1452
1453 // A helper struct for conveniently grouping a set of bounds which we pass to
1454 // and return from functions in multiple places.
1455 #[derive(PartialEq, Eq, Clone, Debug)]
1456 pub struct Bounds<'tcx> {
1457     pub region_bounds: Vec<ty::Region<'tcx>>,
1458     pub implicitly_sized: bool,
1459     pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1460     pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1461 }
1462
1463 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1464     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1465                       -> Vec<ty::Predicate<'tcx>>
1466     {
1467         let mut vec = Vec::new();
1468
1469         // If it could be sized, and is, add the sized predicate
1470         if self.implicitly_sized {
1471             if let Some(sized) = tcx.lang_items().sized_trait() {
1472                 let trait_ref = ty::TraitRef {
1473                     def_id: sized,
1474                     substs: tcx.mk_substs_trait(param_ty, &[])
1475                 };
1476                 vec.push(trait_ref.to_predicate());
1477             }
1478         }
1479
1480         for &region_bound in &self.region_bounds {
1481             // account for the binder being introduced below; no need to shift `param_ty`
1482             // because, at present at least, it can only refer to early-bound regions
1483             let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1484             vec.push(
1485                 ty::Binder::dummy(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1486         }
1487
1488         for bound_trait_ref in &self.trait_bounds {
1489             vec.push(bound_trait_ref.to_predicate());
1490         }
1491
1492         for projection in &self.projection_bounds {
1493             vec.push(projection.to_predicate());
1494         }
1495
1496         vec
1497     }
1498 }